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/Ralphkay/django-private-chat/blob/master/django_private_chat/management/commands/run_chat_server.py
|
Github Open Source
|
Open Source
|
ISC
| 2,017
|
django-private-chat
|
Ralphkay
|
Python
|
Code
| 55
| 335
|
import asyncio
import websockets
from django.conf import settings
from django.core.management.base import BaseCommand
from django_private_chat import channels, handlers
from django_private_chat.utils import logger
class Command(BaseCommand):
help = 'Starts message center chat engine'
def handle(self, *args, **options):
asyncio.async(
websockets.serve(
handlers.main_handler,
settings.CHAT_WS_SERVER_HOST,
settings.CHAT_WS_SERVER_PORT
)
)
logger.info('Chat server started')
asyncio.async(handlers.new_messages_handler(channels.new_messages))
asyncio.async(handlers.users_changed_handler(channels.users_changed))
asyncio.async(handlers.gone_online(channels.online))
asyncio.async(handlers.check_online(channels.check_online))
asyncio.async(handlers.gone_offline(channels.offline))
asyncio.async(handlers.is_typing_handler(channels.is_typing))
asyncio.async(handlers.read_message_handler(channels.read_unread))
loop = asyncio.get_event_loop()
loop.run_forever()
| 12,303
|
https://github.com/ALyman/pears-ts/blob/master/parsers/index.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
pears-ts
|
ALyman
|
TypeScript
|
Code
| 36
| 73
|
export * from "./parser-base";
export * from "./alternative";
export * from "./equal";
export * from "./lookahead";
export * from "./match";
export * from "./noop";
export * from "./sequence";
export * from "./map";
export * from "./many";
| 8,268
|
https://github.com/imjonos/laravel-blog/blob/master/app/Providers/AppServiceProvider.php
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
laravel-blog
|
imjonos
|
PHP
|
Code
| 78
| 318
|
<?php
namespace App\Providers;
use App\Interfaces\Repositories\CategoryRepositoryInterface;
use App\Interfaces\Repositories\CommentRepositoryInterface;
use App\Interfaces\Repositories\PostRepositoryInterface;
use App\Repositories\CategoryRepository;
use App\Repositories\CommentRepository;
use App\Repositories\PostRepository;
use App\Services\CategoryService;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register(): void
{
$this->app->bind(PostRepositoryInterface::class, PostRepository::class);
$this->app->bind(CategoryRepositoryInterface::class, CategoryRepository::class);
$this->app->bind(CommentRepositoryInterface::class, CommentRepository::class);
}
/**
* Bootstrap any application services.
*
* @return void
* @throws BindingResolutionException
*/
public function boot(): void
{
$categoryService = $this->app->make(CategoryService::class);
$categories = $categoryService->all();
view()->share('categories', $categories);
}
}
| 2,769
|
https://github.com/nawarissa/apistore/blob/master/routes/api.php
|
Github Open Source
|
Open Source
|
MIT
| null |
apistore
|
nawarissa
|
PHP
|
Code
| 67
| 237
|
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Booking;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('login', 'API\UserController@login')->name('api-login');
Route::post('register', 'API\UserController@register')->name('api-register');
Route::get("tables", 'API\BookingController@tables')->name('api_tables');
Route::post("logout", 'API\UserController@logout')->name("api-logout");
Route::group(['middleware' => 'auth:api'], function() {
Route::post('booking', 'API\BookingController@book')->name("api-book");
});
| 4,385
|
https://github.com/xcorshinex/python-http-enum/blob/master/http-enum.py
|
Github Open Source
|
Open Source
|
MIT
| null |
python-http-enum
|
xcorshinex
|
Python
|
Code
| 272
| 1,019
|
#!/usr/bin/python
import os, sys, argparse, datetime
def scan(cmd, ip, dir, log, name, tool):
print("[%s / %s] %s starting...." % (ip, name, tool))
os.system(cmd)
print("\tLog: %s" % log)
print("\tResults: %s" % dir)
print("[%s / %s] %s complete." % (ip, name, tool))
def main():
# binaries
_gobuster = "/root/go/bin/gobuster"
_eyewitness = "/usr/bin/eyewitness"
_whatweb = "/usr/bin/whatweb"
_nikto = "/usr/bin/nikto"
_valid_codes = "'200,204,301,307,405,500'"
_agent = "'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'"
_date = datetime.datetime.now().strftime('%Y%m%d')
# tool args
_gob_args = "-n -q -r -e -t 30 -k -s %s -a %s" % (_valid_codes, _agent)
_eye_args = "--web --threads 10 --no-prompt --results 20 --user-agent %s" % (_agent)
_nikto_args = "-Format txt -Save ."
# user argumentss
parser = argparse.ArgumentParser()
parser.add_argument("--ip", dest="_ip")
args = parser.parse_args()
# whatweb scan
_ww_dir = "Enumeration/whatweb_%s.log" % _date
_ww_log = "Logs/whatweb_%s.log" % _date
_cmd = "%s --log-brief=%s %s > %s 2>&1" % (_whatweb, _ww_dir, args._ip, _ww_log)
scan(_cmd, args._ip, _ww_dir, _ww_log, "normal", _whatweb)
# nikto scan
_nikto_dir = "Enumeration/nikto_%s.log" % _date
_nikto_log = "Logs/nikto_%s.log" % _date
_cmd = "%s %s -host %s -output %s > %s 2>&1" % (_nikto, _nikto_args, args._ip, _nikto_dir, _nikto_log)
scan(_cmd, args._ip, _nikto_dir, _nikto_log, "normal", _nikto)
# first gobuster scan
_gob_dir = "Enumeration/gobuster_%s_%s.log" % ("fast", _date)
_gob_log="Logs/gobuster_fast_%s.log" % (_date)
_cmd = "%s %s -u %s -o %s -w %s > %s 2>&1" % (_gobuster, _gob_args, args._ip, _gob_dir, "/mnt/resources/WordLists/wordlist_small_20190319.log", _gob_log)
scan(_cmd, args._ip, _gob_dir, _gob_log, "fast", _gobuster)
# first eyewitness scan
_eye_dir = "Enumeration/eyewitness_%s_%s.log" % ("fast", _date)
_eye_log="Logs/eyewitness_fast_%s.log" % (_date)
_cmd = "%s %s -d %s -f %s > %s 2>&1" % (_eyewitness, _eye_args, _eye_log, _gob_dir, _eye_log)
scan(_cmd, args._ip, _eye_dir, _eye_log, "fast", _eyewitness)
if __name__ == "__main__":
main()
| 34,756
|
https://github.com/pmarino84/react-store/blob/master/examples/todo-app/src/store/todos/reducer.js
|
Github Open Source
|
Open Source
|
MIT
| null |
react-store
|
pmarino84
|
JavaScript
|
Code
| 80
| 260
|
import handleActions from "@pietro-marino/reactjs-store/handleActions";
import { ADD_TODO, COMPLETE_TODO, REMOVE_TODO } from "./actions";
function addTodo(state, action) {
return [...state, action.payload];
}
function removeTodo(state, action) {
return state.filter((todo) => todo.id !== action.payload);
}
function completeTodo(state, action) {
const todoId = action.payload;
return state.reduce((list, todo) => {
const itemToInsert = { ...todo };
if (todo.id === todoId) {
itemToInsert.completed = true;
}
list.push(itemToInsert);
return list;
}, []);
}
const todosReducer = handleActions({
[ADD_TODO]: addTodo,
[REMOVE_TODO]: removeTodo,
[COMPLETE_TODO]: completeTodo,
}, []);
export default todosReducer;
| 37,528
|
https://github.com/psaile/ngeo/blob/master/examples/control.js
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
ngeo
|
psaile
|
JavaScript
|
Code
| 102
| 361
|
goog.provide('control');
goog.require('ngeo.controlDirective');
goog.require('ngeo.mapDirective');
goog.require('ol.Map');
goog.require('ol.View');
goog.require('ol.control.MousePosition');
goog.require('ol.layer.Tile');
goog.require('ol.source.OSM');
/** @const **/
var app = {};
/** @type {!angular.Module} **/
app.module = angular.module('app', ['ngeo']);
/**
* @constructor
*/
app.MainController = function() {
/** @type {ol.Map} */
this['map'] = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: [0, 0],
zoom: 4
})
});
/**
* The "control" directive requires a function that creates the
* control instance.
*
* @param {Element} target Target element.
* @return {ol.control.MousePosition} Mouse position control.
*/
this['createControl'] = function(target) {
return new ol.control.MousePosition({
className: 'mouse-position',
target: target
});
};
};
app.module.controller('MainController', app.MainController);
| 36,121
|
https://github.com/tomcamp0228/ibeo_ros2/blob/master/src/ibeo_8l_sdk/src/ibeosdk/devices/IbeoTcpIpAcceptorBase.hpp
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ibeo_ros2
|
tomcamp0228
|
C++
|
Code
| 1,349
| 4,051
|
//======================================================================
/*! \file IbeoTcpIpAcceptorBase.hpp
*
* \copydoc Copyright
* \author Julia Nitsch (jn)
* \date May 17, 2016
*///-------------------------------------------------------------------
//======================================================================
#ifndef IBEOSDK_IBEOTCPIPACCEPTORBASE_HPP_SEEN
#define IBEOSDK_IBEOTCPIPACCEPTORBASE_HPP_SEEN
//======================================================================
#include <ibeosdk/LogFileManager.hpp>
#include <ibeosdk/misc/WinCompatibility.hpp>
#include <ibeosdk/misc/StatusCodes.hpp>
#include <boost/asio.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/optional/optional.hpp>
#include <set>
//======================================================================
namespace ibeosdk {
//======================================================================
class DataBlock;
//======================================================================
/*!\brief Class for accepting connections via TCP/IP and sending data
* via this connection.
* \author Julia Nitsch (jn)
* \version 0.1
* \date May 17, 2016
*///-------------------------------------------------------------------
class IbeoTcpIpAcceptorBase {
public:
//========================================
/*!\brief Convenience ptr for boost shared_ptr.
*///-------------------------------------
typedef boost::shared_ptr<IbeoTcpIpAcceptorBase> Ptr;
//=====================================================================
/*!\brief Class which holds the current connection.
* \author Julia Nitsch (jn)
* \version 0.1
* \date May 17, 2016
*///-------------------------------------------------------------------
class SessionBase {
public:
//========================================
/*!\brief Convenience ptr for boost shared_ptr.
*///-------------------------------------
typedef boost::shared_ptr<SessionBase> Ptr;
public:
//========================================
/*!\brief Creates a SessionBase.
*
* \param[in] io_service Service which
* established connection.
* \param[in] deviceId Device id of our simulated device
* needed for ibeo data header.
*///-------------------------------------
SessionBase(IbeoTcpIpAcceptorBase* const parent,
boost::asio::io_service& io_service,
const UINT8 deviceId = 1);
//========================================
/*!\brief Creates a SessionBase.
*
* \param[in] io_service Service which
* \param[in] rangeStart Start of initial filter
* range which decides
* which DataBlock will be
* send via this session.
* \param[in] rangeEnd End of initial filter
* range which decides
* which DataBlock will be
* send via this session.
* established connection.
* \param[in] deviceId Device id of our simulated device
* needed for ibeo data header.
*///-------------------------------------
SessionBase(IbeoTcpIpAcceptorBase* const parent,
boost::asio::io_service& io_service,
const DataTypeId rangeStart,
const DataTypeId rangeEnd,
const UINT8 deviceId = 1);
//========================================
/*!\brief Destructs a SessionBase.
*
* Closes socket.
*///-------------------------------------
virtual ~SessionBase();
//========================================
/*!\brief Send a DataBlock.
* \param[in] dataBlock the DataBlock which should be sent.
* \return The result whether the operation could be started or not.
* \sa ErrorCode
*///-------------------------------------
statuscodes::Codes sendDatablock(const ibeosdk::DataBlock& dataBlock);
//========================================
/*!\brief Starts listening thread.
*///-------------------------------------
void startListening() { startListen(); }
//========================================
/*!\brief Checks whether connection is valid.
* \return \c true if connection is still valid,
* \c false otherwise.
*///-------------------------------------
bool isConnectionValid() { return (m_connectionALive && m_socket.is_open()); }
public:
boost::asio::ip::tcp::socket& getSocket() { return m_socket; }
bool getConnectionALive() { return m_connectionALive; }
public:
void setConnectionALive(const bool connectionALive) { m_connectionALive = connectionALive; }
//========================================
/*!\brief
* \param[in] startRange Start of filter
* range which decides
* which DataBlock will be
* send via this session.
* \param[in] endRange End of filter
* range which decides
* which DataBlock will be
* send via this session.
* established connection.
*
*///-------------------------------------
void setRange(const DataTypeId& startRange, const DataTypeId& endRange)
{
boost::mutex::scoped_lock lock(m_sendMutex);
m_startRange = startRange;
m_endRange = endRange;
}
void setSizeOfPrevMsg(const uint32_t sizePrevMsg) { m_sizePrevMsg = sizePrevMsg; }
public:
void cancelAsyncIos() { m_socket.cancel(); }
protected:
//========================================
/*!\brief Worker function for m_ListenThreadPtr
* needs to be overloaded by child.
*///-------------------------------------
virtual void startListen() = 0;
protected:
IbeoTcpIpAcceptorBase* const m_parent;
//========================================
/*!\brief Socket which holds the connection.
*///-------------------------------------
boost::asio::ip::tcp::socket m_socket;
//========================================
/*!\brief Holds device id, needed when
* writing an IbeoDataHeader.
* \note Default value is 1.
*///-------------------------------------
UINT8 m_deviceId;
protected:
//========================================
/*!\brief Lock sending function
*
* Can be called by listening thread, when replying,
* but also by other writing threads.
*///-------------------------------------
boost::mutex m_sendMutex;
//========================================
/*!\brief Saves the size of the last send msg.
*
* Needed when writing an IbeoDataHeader when
* sending a DataBlock or replying to commands.
*///-------------------------------------
UINT32 m_sizePrevMsg;
//========================================
/*!\brief Flag which holds information/guess
* whether the socket is still connected.
*///-------------------------------------
bool m_connectionALive;
//========================================
/*!\brief Starting range id for DataBlocks which
* should be sent.
* \note Initialized with DataTypeId::DataType_Unknown.
*///-------------------------------------
DataTypeId m_startRange;
//========================================
/*!\brief Ending range id for DataBlocks which
* should be sent
* \note Initialized with DataTypeId::DataType_LastId.
*///-------------------------------------
DataTypeId m_endRange;
std::vector<char> m_sendBuffer;
}; //IbeoTcpIpAcceptorBase::SessionBase
public:
//========================================
/*!\brief Creates an IbeoTcpIpAcceptorBase.
*
* \param[in] logFileManager LogFileManager which is
* handle the splitting of
* output files and log files.
* \param[in] port Port number for the connection.
*///-------------------------------------
IbeoTcpIpAcceptorBase(ibeosdk::LogFileManager* const logFileManager, const unsigned short port = 12002);
//========================================
/*!\brief Creates an IbeoTcpIpAcceptorBase.
*
* \param[in] logFileManager LogFileManager which is
* handle the splitting of
* output files and log files.
* \param[in] port Port number for the connection.
*///-------------------------------------
IbeoTcpIpAcceptorBase(ibeosdk::LogFileManager* const logFileManager,
const boost::asio::deadline_timer::duration_type writeExpirationTime,
const unsigned short port = 12002);
//========================================
/*!\brief Creates an IbeoTcpIpAcceptorBase.
*
* \param[in] logFileManager LogFileManager which is
* handle the splitting of
* output files and log files.
* \param[in] port Port number for the connection.
*///-------------------------------------
IbeoTcpIpAcceptorBase(ibeosdk::LogFileManager* const logFileManager,
const boost::optional<boost::asio::deadline_timer::duration_type> writeExpirationTime,
const unsigned short port = 12002);
//========================================
/*!\brief Destructor of the IbeoTcpIpAcceptor class.
*
* Stopping io service thread and
* destroying the socket.
*///-------------------------------------
virtual ~IbeoTcpIpAcceptorBase();
public:
//========================================
/*!\brief Initialization for acceptor.
* Start to accept new connections.
*///-------------------------------------
void init();
//========================================
/*!\brief Returns whether there is at least
* one session active.
* \return \c true if at least one session is active.
* \c false otherwise.
*///-------------------------------------
bool hasSessions() const { return !m_sessions.empty(); }
//========================================
/*!\brief Get the number of active sessions.
* \return The number of activate sessions.
*///-------------------------------------
int getNbOfSession() const { return int(m_sessions.size()); }
//========================================
/*!\brief Sends \a dataBlock to all open connections.
* And wait till the writes have finished.
* \param[in] dataBlock The DataBlock which should
* be sent.
* \return The result of the operation.
* \sa statuscodes::Codes
*///-------------------------------------
statuscodes::Codes sendDataBlock(const DataBlock& dataBlock);
protected:
//========================================
/*!\brief Sends \a dataBlock to all open connections.
* \param[in] dataBlock The DataBlock which should
* be sent.
*///-------------------------------------
void issueWriteOperations(const DataBlock& dataBlock);
//========================================
/*!\brief Wait for all write operations to
* be completed.
*///-------------------------------------
void waitForWriteOperationsBeCompleted();
//========================================
/*!\brief Handler for timeout situations.
* \param[in] session Session that started
* the deadline timer.
* \param[in] error Result of waiting for
* the deadline timer of
* the \a session.
* \param[in] nbOfBytesTransfered Number of bytes written
* from the buffer. If an
* error occurred this will be
* less than the expected
* size.
*///-------------------------------------
void writeDone(SessionBase* const session,
const boost::system::error_code& error,
const std::size_t nbOfBytesTransfered);
void writeTimeout(const boost::system::error_code& error);
void cancelWriteOperations();
protected:
//========================================
/*!\brief Gets current session ptr.
*
* Needs to be implemented by child classes.
* \return Session ptr casted to sessionBase.
*///-------------------------------------
virtual SessionBase::Ptr getSessionPtr() = 0;
//========================================
/*!\brief Gets new session ptr initialized with io_service.
* \param[in] io_service Service which handles connections.
* \return Session ptr casted to sessionBase.
*///-------------------------------------
virtual SessionBase::Ptr getNewSessionPtr(boost::asio::io_service& io_service) = 0;
private:
//========================================
/*!\brief Working function for accepting new
* requests from m_acceptIOServiceThreadPtr.
*///-------------------------------------
void acceptorIOServiceThread();
//========================================
/*!\brief Handles accepts, running in context
* of m_acceptIOServiceThreadPtr.
*///-------------------------------------
void handleAccept(const boost::system::error_code& error);
//========================================
/*!\brief Closing acceptor.
*///-------------------------------------
void closeAcceptor();
private:
//========================================
/*!\brief Session ptr which will handle the
* next accept.
*
* Will be append to m_sessions when a new
* session has been accepted. And a new
* session pointer will be created for the
* next session to be accepted.
*///-------------------------------------
SessionBase::Ptr m_sessionPtr;
//========================================
/*!\brief Handles writing of logfile.
* \attention Needs to be set by constructor.
*///-------------------------------------
LogFileManager* m_logFileManager;
//========================================
/*!\brief Service which handles accepts and
* then handed over to sessions.
*///-------------------------------------
boost::asio::io_service m_ioService;
private:
//========================================
/*!\brief Prevent sessions to be accessed
* simultaneously by multiple threads.
*///-------------------------------------
boost::mutex m_sessionsMutex;
//========================================
/*!\brief Vector which holds all open connections.
*
* If connection is detected as being closed
* (e.g during writing) it will be deleted.
*///-------------------------------------
std::vector<SessionBase::Ptr> m_sessions;
private: // used by write operation
//========================================
/*!\brief Maps holds for each session the
* expected number of bytes to be
* send.
*///-------------------------------------
std::map<SessionBase*, uint32_t> m_activeSending;
//========================================
/*!\brief Current status of the write operations
* to all sessions.
*///-------------------------------------
statuscodes::Codes m_sendingStatus;
//========================================
/*!\brief Mutex to guard \a m_activeSending.
*///-------------------------------------
boost::mutex m_writeCondMutex;
//========================================
/*!\brief Condition to signaling whether
* all write operations have been
* completed.
*///-------------------------------------
boost::condition_variable writeCondition;
//========================================
/*!\brief Expiring duration for write operations.
*///-------------------------------------
boost::asio::deadline_timer::duration_type m_writeExpirationPeriod;
//========================================
/*!\brief Deadline timer for write operations.
*///-------------------------------------
boost::asio::deadline_timer m_writeExprirationTimer;
enum WriteState {
WS_Idle,
WS_InProgress,
WS_Error,
WS_TimeOut,
WS_Completed
};
WriteState m_writeState;
private:
//========================================
/*!\brief Accepting requests.
*///-------------------------------------
boost::asio::ip::tcp::acceptor m_acceptor;
//========================================
/*!\brief Thread waiting for connection requests.
*///-------------------------------------
boost::scoped_ptr<boost::thread> m_acceptIOServiceThreadPtr;
}; //IbeoTcpIpAcceptorBase
//======================================================================
} // namespace ibeosdk
//======================================================================
#endif // IBEOSDK_IBEOTCPIPACCEPTORBASE_HPP_SEEN
//======================================================================
| 35,291
|
https://github.com/talsewell/cerberus/blob/master/tests/examples/6.2.5-30.c
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,022
|
cerberus
|
talsewell
|
C
|
Code
| 15
| 35
|
/* STD §6.2.5#30, Example 2 */
/* check types of
struct tag (*[5]) (float)
*/
| 11,073
|
https://github.com/UbuntuEvangelist/OG-Platform/blob/master/projects/OG-Core/src/main/java/com/opengamma/core/marketdatasnapshot/NamedSnapshot.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
OG-Platform
|
UbuntuEvangelist
|
Java
|
Code
| 151
| 298
|
/**
* Copyright (C) 2014 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.core.marketdatasnapshot;
import com.opengamma.id.UniqueId;
import com.opengamma.id.UniqueIdentifiable;
/**
* A common interface to support handling both the old-style
* {@code StructuredMarketDataSnapshot} and the new, more specific
* snapshots.
*/
public interface NamedSnapshot extends UniqueIdentifiable {
/**
* Gets the name of the snapshot.
*
* @return the name, not null
*/
String getName();
/**
* Create a version of this snapshot with the unique id set to the
* supplied value. Ideally, mutable implementations would return a
* copy but this interface does not make this restriction.
* <p>
* This is intended for use by masters when inserting new snapshots.
*
* @param uniqueId the new value for the unique id, not null
* @return a copy of this snapshot, not null
*/
NamedSnapshot withUniqueId(UniqueId uniqueId);
}
| 50,009
|
https://github.com/lestor/kohana/blob/master/system/config/encrypt.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,018
|
kohana
|
lestor
|
PHP
|
Code
| 47
| 117
|
<?php
return array(
'default' => array(
/**
* The following options must be set:
*
* string key The secret key (must be 32 chars long!)
* integer cipher The encryption cipher, one of the Sodium cipher constants
*/
'key' => NULL,
'cipher' => Encrypt::CIPHER_XCHACHA20_POLY1305_IETF
)
);
| 42,440
|
https://github.com/phimuemue/openschafkopf/blob/master/main/build.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
openschafkopf
|
phimuemue
|
Rust
|
Code
| 194
| 1,051
|
use openschafkopf_util::*;
use image::GenericImageView;
use as_num::*;
use std::{env, fs::File, io::Write, path::Path, process::Command};
fn main() {
// adapted from https://doc.rust-lang.org/cargo/reference/build-scripts.html#case-study-code-generation
let execute_external = |path_in: &Path, cmd: &mut Command| {
println!("cargo:rerun-if-changed={}", unwrap!(path_in.to_str()));
let output = unwrap!(cmd.output());
assert!(output.status.success(), "{:?}: {:?}", cmd, output);
output
};
let path_resources = Path::new("tools");
let str_env_var_out_dir = unwrap!(env::var("OUT_DIR"));
let path_out_dir = Path::new(&str_env_var_out_dir); // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts
unwrap!(std::fs::create_dir_all(&path_out_dir));
// TODO can we avoid lessc depencency?
let path_css_in = path_resources.join("css.less");
unwrap!(
unwrap!(
File::create(&path_out_dir.join("css.css"))
)
.write_all(&execute_external(
&path_css_in,
Command::new("lessc")
.arg(&path_css_in)
).stdout)
);
// TODO can we avoid inkscape depencency?
let path_svg_in = path_resources.join("cards.svg");
execute_external(
&path_svg_in,
Command::new("inkscape")
.arg(&path_svg_in)
.arg(format!("--export-filename={}", unwrap!(path_out_dir.join("cards.png").to_str())))
);
let path_svg_3dpi = path_out_dir.join("cards_3dpi.png");
execute_external(
&path_svg_in,
Command::new("inkscape")
.arg(&path_svg_in)
.arg(format!("--export-filename={}", unwrap!(path_svg_3dpi.to_str())))
.arg(format!("--export-dpi={}", 3*/*default DPI*/96))
);
let img = unwrap!(image::open(path_svg_3dpi));
let (n_width, n_height) = img.dimensions();
let str_efarbe = "EGHS";
let str_eschlag = "AZKOU987";
assert_eq!(n_width % str_eschlag.len().as_num::<u32>(), 0);
let n_width_card = n_width / str_eschlag.len().as_num::<u32>();
assert_eq!(n_height % str_efarbe.len().as_num::<u32>(), 0);
let n_height_card = n_height / str_efarbe.len().as_num::<u32>();
for (i_efarbe, ch_efarbe) in str_efarbe.chars().enumerate() {
for (i_eschlag, ch_eschlag) in str_eschlag.chars().enumerate() {
unwrap!(
img.view(
/*x*/n_width_card * i_eschlag.as_num::<u32>(),
/*y*/n_height_card * i_efarbe.as_num::<u32>(),
n_width_card,
n_height_card,
)
.to_image()
.save({
let path_img = path_resources // TODO allowed to write into this directory?
.join("site")
.join("img");
unwrap!(std::fs::create_dir_all(&path_img));
path_img.join(format!("{}{}.png", ch_efarbe, ch_eschlag))
})
);
}
}
}
| 31,568
|
https://github.com/alex-davidson/clrspy/blob/master/ClrSpy/Native/PointerUtils.cs
|
Github Open Source
|
Open Source
|
Unlicense, Apache-2.0, MIT
| 2,021
|
clrspy
|
alex-davidson
|
C#
|
Code
| 39
| 132
|
using System;
using System.Diagnostics;
namespace ClrSpy.Native
{
public static class PointerUtils
{
public static IntPtr CastLongToIntPtr(long longValue)
{
if (IntPtr.Size == 4)
{
Debug.Assert(longValue <= UInt32.MaxValue);
Debug.Assert(longValue >= UInt32.MinValue);
return new IntPtr((int)longValue);
}
return new IntPtr(longValue);
}
}
}
| 15,716
|
https://github.com/ScalablyTyped/SlinkyTyped/blob/master/k/kendo-ui/src/main/scala/typingsSlinky/kendoUi/kendo/dataviz/ChartPoint.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
SlinkyTyped
|
ScalablyTyped
|
Scala
|
Code
| 69
| 232
|
package typingsSlinky.kendoUi.kendo.dataviz
import typingsSlinky.kendoUi.kendo.Observable
import typingsSlinky.kendoUi.kendo.drawing.Element
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait ChartPoint extends Observable {
var category: String | js.Date | Double = js.native
var dataItem: js.Any = js.native
var options: ChartPointOptions = js.native
var percentage: Double = js.native
var runningTotal: Double = js.native
var total: Double = js.native
var value: Double = js.native
var visual: Element = js.native
}
| 23,813
|
https://github.com/Jarlyk/Rain-of-Stages/blob/master/Assets/RainOfStages/RoR2/GeneratedProxies/RoR2/OrbitalLaserController.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Rain-of-Stages
|
Jarlyk
|
C#
|
Code
| 16
| 69
|
#if THUNDERKIT_CONFIGURED
using global::RoR2;
namespace PassivePicasso.ThunderKit.Proxy.RoR2
{
public partial class OrbitalLaserController : global::RoR2.OrbitalLaserController {}
}
#endif
| 7,532
|
https://github.com/honorarac/core-framework/blob/master/UIComponents/Dashboard/Search/Groups.php
|
Github Open Source
|
Open Source
|
MIT, BSD-3-Clause
| 2,019
|
core-framework
|
honorarac
|
PHP
|
Code
| 68
| 590
|
<?php
namespace Webkul\UVDesk\CoreFrameworkBundle\UIComponents\Dashboard\Search;
use Webkul\UVDesk\CoreFrameworkBundle\Dashboard\Segments\SearchItemInterface;
class Groups implements SearchItemInterface
{
CONST SVG = <<<SVG
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="30px" height="30px" viewBox="0 0 60 60">
<path fill-rule="evenodd" d="M54,36V52H45V36H42V24a3.807,3.807,0,0,1,4-4h7a3.807,3.807,0,0,1,4,4V36H54ZM49.5,18A4.5,4.5,0,1,1,54,13.5,4.487,4.487,0,0,1,49.5,18ZM33,52H27V39H20l6.37-16.081A4.224,4.224,0,0,1,30.379,20h0.253a4.244,4.244,0,0,1,4.009,2.922L40,39H33V52ZM30.49,18a4.5,4.5,0,1,1,4.5-4.5A4.487,4.487,0,0,1,30.49,18ZM15,52H6V36H3V24a3.807,3.807,0,0,1,4-4h7a3.807,3.807,0,0,1,4,4V36H15V52ZM10.5,18A4.5,4.5,0,1,1,15,13.5,4.487,4.487,0,0,1,10.5,18Z"></path>
</svg>
SVG;
public static function getIcon() : string
{
return self::SVG;
}
public static function getTitle() : string
{
return "Groups";
}
public static function getRouteName() : string
{
return 'helpdesk_member_support_group_collection';
}
public function getChildrenRoutes() : array
{
return [];
}
}
| 25,003
|
https://github.com/elear-solutions/kibana/blob/master/x-pack/legacy/plugins/security/public/views/management/edit_user/components/edit_user_page.test.tsx
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-proprietary-license, LicenseRef-scancode-other-permissive, Apache-2.0, BSD-3-Clause, MIT, OFL-1.1, Elastic-2.0, LicenseRef-scancode-elastic-license-2018
| 2,023
|
kibana
|
elear-solutions
|
TSX
|
Code
| 319
| 1,080
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { mountWithIntl } from 'test_utils/enzyme_helpers';
import { EditUserPage } from './edit_user_page';
import React from 'react';
import { UserAPIClient } from '../../../../lib/api';
import { User, Role } from '../../../../../common/model';
import { ReactWrapper } from 'enzyme';
jest.mock('ui/kfetch');
const buildClient = () => {
const apiClient = new UserAPIClient();
const createUser = (username: string) => {
const user: User = {
username,
full_name: 'my full name',
email: 'foo@bar.com',
roles: ['idk', 'something'],
enabled: true,
};
if (username === 'reserved_user') {
user.metadata = {
_reserved: true,
};
}
return Promise.resolve(user);
};
apiClient.getUser = jest.fn().mockImplementation(createUser);
apiClient.getCurrentUser = jest.fn().mockImplementation(() => createUser('current_user'));
apiClient.getRoles = jest.fn().mockImplementation(() => {
return Promise.resolve([
{
name: 'role 1',
elasticsearch: {
cluster: ['all'],
indices: [],
run_as: [],
},
kibana: [],
},
{
name: 'role 2',
elasticsearch: {
cluster: [],
indices: [],
run_as: ['bar'],
},
kibana: [],
},
] as Role[]);
});
return apiClient;
};
function expectSaveButton(wrapper: ReactWrapper<any, any>) {
expect(wrapper.find('EuiButton[data-test-subj="userFormSaveButton"]')).toHaveLength(1);
}
function expectMissingSaveButton(wrapper: ReactWrapper<any, any>) {
expect(wrapper.find('EuiButton[data-test-subj="userFormSaveButton"]')).toHaveLength(0);
}
describe('EditUserPage', () => {
it('allows reserved users to be viewed', async () => {
const apiClient = buildClient();
const wrapper = mountWithIntl(
<EditUserPage.WrappedComponent
username={'reserved_user'}
apiClient={apiClient}
changeUrl={path => path}
intl={null as any}
/>
);
await waitForRender(wrapper);
expect(apiClient.getUser).toBeCalledTimes(1);
expect(apiClient.getCurrentUser).toBeCalledTimes(1);
expectMissingSaveButton(wrapper);
});
it('allows new users to be created', async () => {
const apiClient = buildClient();
const wrapper = mountWithIntl(
<EditUserPage.WrappedComponent
username={''}
apiClient={apiClient}
changeUrl={path => path}
intl={null as any}
/>
);
await waitForRender(wrapper);
expect(apiClient.getUser).toBeCalledTimes(0);
expect(apiClient.getCurrentUser).toBeCalledTimes(0);
expectSaveButton(wrapper);
});
it('allows existing users to be edited', async () => {
const apiClient = buildClient();
const wrapper = mountWithIntl(
<EditUserPage.WrappedComponent
username={'existing_user'}
apiClient={apiClient}
changeUrl={path => path}
intl={null as any}
/>
);
await waitForRender(wrapper);
expect(apiClient.getUser).toBeCalledTimes(1);
expect(apiClient.getCurrentUser).toBeCalledTimes(1);
expectSaveButton(wrapper);
});
});
async function waitForRender(wrapper: ReactWrapper<any, any>) {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
wrapper.update();
}
| 34,648
|
https://github.com/fcollonval/beakerx_tabledisplay/blob/master/beakerx_tabledisplay/js/src/dataGrid/cell/DataGridCell.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
beakerx_tabledisplay
|
fcollonval
|
TypeScript
|
Code
| 479
| 1,315
|
/*
* Copyright 2017 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in 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.
*/
import { CellRenderer, DataModel } from '@lumino/datagrid';
import { BeakerXDataGrid } from '../BeakerXDataGrid';
import { ColumnManager } from '../column/ColumnManager';
import { COLUMN_TYPES } from '../column/enums';
import { DataGridHelpers } from '../Helpers';
import { ICellData } from '../interface/ICell';
export class DataGridCell {
static isHeaderCell(config: CellRenderer.CellConfig | ICellData) {
return config && (config.region === 'column-header' || config.region === 'corner-header');
}
static getCellData(dataGrid: BeakerXDataGrid, clientX: number, clientY: number): ICellData | null {
if (!dataGrid.viewport) {
return null;
}
let column: { index: number; delta: number } | null = null;
const rect = dataGrid.viewport.node.getBoundingClientRect();
const x = clientX - rect.left;
const y = clientY - rect.top;
if (x > dataGrid.headerWidth + dataGrid.bodyWidth || y > dataGrid.headerHeight + dataGrid.bodyHeight) {
return null;
}
// Test for a match in the corner header first.
if (x <= dataGrid.headerWidth && y <= dataGrid.headerHeight) {
if (x <= dataGrid.headerWidth) {
column = DataGridHelpers.findSectionIndex(dataGrid.getRowHeaderSections(), x);
}
if (column) {
return {
column: column.index,
row: 0,
delta: column.delta,
type: column.index === 0 ? COLUMN_TYPES.index : COLUMN_TYPES.body,
offset: dataGrid.getColumnOffset(
column.index,
ColumnManager.getColumnRegionByCell({ region: 'corner-header' }),
),
offsetTop: dataGrid.headerHeight,
region: 'corner-header',
value: dataGrid.dataModel.data('corner-header', 0, column.index),
width: dataGrid.getRowHeaderSections().sizeOf(column.index),
};
}
return null;
}
let region: DataModel.CellRegion = 'body';
let section = dataGrid.getColumnSections();
let pos = x + dataGrid.scrollX - dataGrid.headerWidth;
if (x <= dataGrid.getRowHeaderSections().length) {
section = dataGrid.getRowHeaderSections();
pos += dataGrid.headerWidth;
region = 'row-header';
}
column = DataGridHelpers.findSectionIndex(section, pos);
const row: { index: number; delta: number } | null = DataGridCell.findHoveredRowIndex(dataGrid, y);
const rowIndex = row ? row.index : 0;
if (column) {
const columnType = region !== 'row-header' || column.index > 0 ? COLUMN_TYPES.body : COLUMN_TYPES.index;
return {
column: column.index,
row: rowIndex,
delta: column.delta,
type: columnType,
offset: dataGrid.getColumnOffset(column.index, region),
offsetTop: row ? dataGrid.getRowOffset(row.index) + dataGrid.headerHeight : 0,
region: y <= dataGrid.headerHeight ? 'column-header' : region,
value: dataGrid.dataModel.data(region, rowIndex, column.index),
width: section.sizeOf(column.index),
};
}
return null;
}
static dataEquals(data1: ICellData, data2: ICellData) {
return data1 && data2 && data1.row === data2.row && data1.column === data2.column && data1.region === data2.region;
}
static isCellHovered(hoveredCell: ICellData, comparedCell: ICellData | CellRenderer.CellConfig): boolean {
return (
hoveredCell &&
hoveredCell.row === comparedCell.row &&
hoveredCell.column === comparedCell.column &&
comparedCell.region === hoveredCell.region
);
}
static findHoveredRowIndex(dataGrid: BeakerXDataGrid, y: number) {
// Convert the position into unscrolled coordinates.
const pos = y + dataGrid.scrollY - dataGrid.headerHeight;
return DataGridHelpers.findSectionIndex(dataGrid.getRowSections(), pos);
}
}
| 36,803
|
https://github.com/Patrick64/vscode-kirby-ftp/blob/master/src/models/ftpModel.ts
|
Github Open Source
|
Open Source
|
CC-BY-3.0
| null |
vscode-kirby-ftp
|
Patrick64
|
TypeScript
|
Code
| 616
| 2,199
|
import { ExtensionContext, TreeDataProvider, EventEmitter, TreeItem, Event, window, TreeItemCollapsibleState, Uri, commands, workspace, TextDocumentContentProvider, CancellationToken, ProviderResult, WorkspaceFolder } from 'vscode';
import * as Client from 'ftp';
import * as path from 'path';
import { IEntry } from '../models/ientry';
const fse = require('fs-extra')
import { FtpNode } from '../nodes/ftpNode'
import { kirbyFileSystemProvider } from '../providers/kirbyFileSystemProvider';
export class FtpModel {
private client:Client;
constructor(private host: string, private user: string, private password: string, private port: number, private rootDir:string) {
}
public connect(): Thenable<Client> {
return new Promise((c, e) => {
this.client = new Client();
this.client.on('ready', () => {
c(this.client);
});
this.client.on('error', error => {
e('Error while connecting: ' + error.message);
})
// this.client.on('close', hadErr => {
// e('Couldnt connect: ' + this.host);
// })
// this.client.on('end', () => {
// e('connection closed: ' + this.host);
// })
this.client.connect({
host: this.host,
user: this.user,
password: this.password,
port: this.port,
connTimeout: 10000
});
});
}
public disconnect() {
this.client.end();
}
/**
*
*/
public get roots(): Thenable<FtpNode[]> {
return new Promise((c, e) => {
this.client.list(this.rootDir, (err, list) => {
if (err) {
e(err);
} else {
c(this.sort(
list.filter(entry => entry && entry.name != "." && entry.name != "..")
.map(entry => new FtpNode(entry, this.host, this.rootDir))));
}
});
});
}
public getChildren(node: FtpNode): Thenable<FtpNode[]> {
return new Promise((c, e) => {
try {
this.client.list(node.path, (err, list) => {
try {
if (err) {
return e(err);
}
if (list)
if (typeof list == "undefined") return [];
return c(
this.sort(
list.filter(entry => entry && entry.name != "." && entry.name != "..")
.map(entry => new FtpNode(entry, this.host, node.path))));
} catch (err) {
e(err);
}
});
} catch(err) {
e(err);
}
});
}
public getRootNode() {
return new FtpNode({name: "", type:"d"}, this.host, this.rootDir)
}
private sort(nodes: FtpNode[]): FtpNode[] {
return nodes.sort((n1, n2) => {
if (n1.isFolder && !n2.isFolder) {
return -1;
}
if (!n1.isFolder && n2.isFolder) {
return 1;
}
return n1.name.localeCompare(n2.name);
});
}
public getContentFromNode(node:FtpNode):Promise<string> {
return new Promise((c, e) => {
this.client.get(node.path, (err, stream) => {
if (err) {
return e(err);
}
let string = ''
stream.on('data', function (buffer) {
if (buffer) {
var part = buffer.toString();
string += part;
}
});
stream.on('end', function () {
c(string);
});
});
});
}
public getContent(resource: Uri): Thenable<string> {
return this.connect().then(client => {
return new Promise((c, e) => {
client.get(resource.path.substr(2), (err, stream) => {
if (err) {
return e(err);
}
let string = ''
stream.on('data', function (buffer) {
if (buffer) {
var part = buffer.toString();
string += part;
}
});
stream.on('end', function () {
client.end();
c(string);
});
});
});
});
}
public getBuffer(node:FtpNode): Promise<Buffer> {
return new Promise((c, e) => {
this.client.get(node.path, (err, stream) => {
try {
if (err) {
return e(err);
}
var bufs = [];
stream.on('data', function (data) {
bufs.push(data);
});
stream.on('end', function () {
c( Buffer.concat(bufs));
});
stream.on("error", (err)=>{
e(err);
});
} catch(err) {
e(err);
}
});
});
}
public writeFileFromStream(node:FtpNode,stream) {
return new Promise((resolve,reject) => {
// stream.once('end', resolve);
if (stream.once) {
stream.once('error', reject);
}
this.client.put(stream,node.path,resolve);
})
}
public writeNewFileFromStream(parentFolder:FtpNode,filename:string,stream) {
return new Promise((resolve,reject) => {
// stream.once('end', resolve);
stream.once('error', reject);
this.client.put(stream,path.join(parentFolder.path,filename),(err) => {
if (err)
reject(err)
else
resolve();
});
})
}
public createReadStream(node:FtpNode) {
return new Promise((resolve,reject) => {
let wait = setTimeout(() => {
reject("Timeout")
},2000);
this.client.get(node.path, function(err, stream) {
clearTimeout(wait);
if (err) {
reject(err);
} else {
//stream.once('close', function() { this.client.end(); });
resolve(stream);
}
});
});
}
public closeStream() {
this.client.end();
}
public mkdir(parentPath:string,folderName) {
return new Promise((resolve,reject) => {
var p = path.join(this.rootDir,parentPath,folderName);
return this.client.mkdir(p,(err) => {
if (err) reject(err); else resolve();
})
});
}
public async getUri(node:FtpNode,workspaceFolder:WorkspaceFolder):Promise<Uri> {
return node.resource;
}
public async openForEditor(node:FtpNode,onSaveFile:Function) {
// var filepath = path.join(workspaceFolder.uri.fsPath, ".vscode/kirby-ftp/tmp", node.name);
const content:Buffer = await this.getBuffer(node);
// const uri = Uri.parse("kirby:/" + node.name);
await kirbyFileSystemProvider.openFile(
node.resource,
content,
onSaveFile
);
}
}
| 34,896
|
https://github.com/dense-analysis/ale/blob/master/autoload/ale/handlers/cspell.vim
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
ale
|
dense-analysis
|
Vim Script
|
Code
| 172
| 724
|
scriptencoding utf-8
" Author: David Houston <houstdav000>
" Description: Define a handler function for cspell's output
function! ale#handlers#cspell#GetExecutable(buffer) abort
return ale#path#FindExecutable(a:buffer,
\ 'cspell', [
\ 'node_modules/.bin/cspell',
\ 'node_modules/cspell/bin.js',
\ ]
\)
endfunction
function! ale#handlers#cspell#GetCommand(buffer) abort
let l:executable = ale#handlers#cspell#GetExecutable(a:buffer)
let l:options = ale#Var(a:buffer, 'cspell_options')
return ale#node#Executable(a:buffer, l:executable)
\ . ' lint --no-color --no-progress --no-summary'
\ . ale#Pad(l:options)
\ . ' -- stdin'
endfunction
function! ale#handlers#cspell#Handle(buffer, lines) abort
" Look for lines like the following:
"
" /home/user/repos/ale/README.md:3:128 - Unknown word (Neovim)
" match1: 3
" match2: 128
" match3: Unknown word (Neovim)
" match4: Neovim
let l:pattern = '\v^.*:(\d+):(\d+) - ([^\(]+\(([^\)]+)\).*)$'
let l:output = []
for l:match in ale#util#GetMatches(a:lines, l:pattern)
call add(l:output, {
\ 'lnum': l:match[1] + 0,
\ 'col': l:match[2] + 0,
\ 'end_col': l:match[2] + len(l:match[4]) - 1,
\ 'text': l:match[3],
\ 'type': 'W',
\})
endfor
return l:output
endfunction
function! ale#handlers#cspell#DefineLinter(filetype) abort
call ale#Set('cspell_executable', 'cspell')
call ale#Set('cspell_options', '')
call ale#Set('cspell_use_global', get(g:, 'ale_use_global_executables', 0))
call ale#linter#Define(a:filetype, {
\ 'name': 'cspell',
\ 'executable': function('ale#handlers#cspell#GetExecutable'),
\ 'command': function('ale#handlers#cspell#GetCommand'),
\ 'callback': 'ale#handlers#cspell#Handle',
\})
endfunction
| 50,282
|
https://github.com/ProkopHapala/SimpleSimulationEngine/blob/master/cpp/common/molecular/AtomTypes.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
SimpleSimulationEngine
|
ProkopHapala
|
C++
|
Code
| 131
| 399
|
#include <cstdio>
#include <cstdlib>
#include "AtomTypes.h" // THE HEADER
bool AtomTypes::loadFromFile( char const* filename ){
printf(" loading AtomTypes from: >>%s<< \n", filename );
FILE * pFile;
pFile = fopen (filename,"r");
fscanf (pFile, "%i", &ntypes);
//printf("ntypes %i \n", ntypes );
Zs = new int[ ntypes ];
vdwRs = new double[ ntypes ];
vdwEs = new double[ ntypes ];
names = new char* [ ntypes ];
colors = new uint32_t[ ntypes ];
char hexstring[8];
for (int i=0; i<ntypes; i++){
names[i] = new char[6];
fscanf (pFile, " %lf %lf %i %s %s", &vdwRs[i], &vdwEs[i], &Zs[i], names[i], hexstring );
colors[i] = (uint32_t)strtol(hexstring, NULL, 16);
printf( "%i %f %f %i %s %s %i\n", i, vdwRs[i], vdwEs[i], Zs[i], names[i], hexstring, colors[i] );
}
fclose (pFile);
return 0;
}
//AtomTypes::AtomTypes( char const* filename ){ loadFromFile( filename ); };
| 27,814
|
https://github.com/Indexical-Metrics-Measure-Advisory/watchmen-web-client/blob/master/src/admin/pipelines/pipelines-loading.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
watchmen-web-client
|
Indexical-Metrics-Measure-Advisory
|
TSX
|
Code
| 145
| 461
|
import {Logo} from '@/widgets/basic/logo';
import React from 'react';
import styled, {keyframes} from 'styled-components';
const Container = styled.div.attrs({'data-widget': 'pipelines-loading'})`
display : grid;
position : absolute;
grid-template-columns : 1fr;
grid-template-rows : 70% 30%;
height : 100%;
width : 100%;
`;
const Spin = keyframes`
from {
transform : rotate(0deg);
}
to {
transform : rotate(360deg);
}
`;
const Icon = styled.div.attrs({'data-widget': 'pipelines-loading-icon'})`
display : flex;
position : relative;
align-items : center;
justify-content : center;
> svg {
height : 70%;
filter : drop-shadow(2px 4px 6px rgba(0, 0, 0, 0.7));
animation : ${Spin} 60s linear infinite;
}
`;
const Label = styled.div.attrs({'data-widget': 'pipelines-loading-label'})`
display : block;
text-align : center;
font-family : var(--title-font-family);
font-size : 3em;
font-variant : petite-caps;
white-space : nowrap;
overflow : hidden;
text-overflow : ellipsis;
opacity : 0.7;
`;
export const PipelinesLoading = () => {
return <Container>
<Icon>
<Logo/>
</Icon>
<Label>Loading Pipelines Data...</Label>
</Container>;
};
| 21,440
|
https://github.com/xaviguasch/collab-backend/blob/master/db/sequelize.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
collab-backend
|
xaviguasch
|
JavaScript
|
Code
| 65
| 221
|
'use strict';
const Sequelize = require('sequelize');
const sequelize = new Sequelize( process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
dialect: 'mysql',
operatorsAliases: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
});
sequelize
.authenticate()
.then(() => {
// eslint-disable-next-line
console.log('Connection has been established successfully.');
})
.catch(err => {
// eslint-disable-next-line
console.error('Unable to connect to the database:', err);
});
module.exports = {
sequelize,
Sequelize
};
| 17,928
|
https://github.com/HariKishoreP/MahendraFoundationWebsite/blob/master/application/views/admin/listAllReports.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
MahendraFoundationWebsite
|
HariKishoreP
|
PHP
|
Code
| 487
| 2,472
|
<style>
.spanform{min-height:250px !important;}
</style>
<div id="content" class="span9 spanform">
<ul class="breadcrumb">
<li>
<i class="icon-home"></i>
<a href="<?php echo base_url();?>admin_dashboard">Home</a>
<i class="icon-angle-right"></i>
</li>
<li><a href="">Reports for Ads</a></li>
</ul>
<?php if($this->session->flashdata('err') != ''){?>
<div class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close" type="button">
×
</button>
<p>
<?php echo ($this->session->flashdata('err'))?$this->session->flashdata('err'):''?>
</p>
</div>
<br>
<?php }?>
<?php if($this->session->flashdata('msg') != ''){?>
<div class="alert alert-block alert-info fade in no-margin">
<button data-dismiss="alert" class="close" type="button">
×
</button>
<p>
<?php echo ($this->session->flashdata('err'))?$this->session->flashdata('err'):''?>
</p>
</div>
<br>
<?php }?>
<div class="row-fluid sortable">
<div class="box span12">
<div class="box-header" data-original-title>
<h2><i class="halflings-icon white edit"></i><span class="break"></span>Filters for Ad Reports</h2>
<div class="box-icon">
<!--<a href="#" class="btn-setting"><i class="halflings-icon white wrench"></i></a>-->
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
<a href="#" class="btn-close"><i class="halflings-icon white remove"></i></a>
</div>
</div>
<div class="box-content">
<form class="form-horizontal" id="validate" method="post" action='<?php echo base_url()?>admin/AllReports/'>
<fieldset>
<div class='span6'>
<div class="control-group">
<label class="control-label" for="focusedInput">Date Start</label>
<div class="controls">
<input type="text" name="start_date" value="<?php if(isset($posted_data)) echo $posted_data['start_date'] ?>" class="datepicker form-control start_date" placeholder="Start Date"/>
<?php echo form_error("start_date");?>
</div>
</div>
</div>
<div class='span6'>
<div class="control-group">
<label class="control-label" for="typeahead">Date End <span class="text-red">*</span></label>
<div class="controls">
<input type="text" name="end_date" value="<?php if(isset($posted_data)) echo $posted_data['end_date']; ?>" class="datepicker form-control end_date" placeholder="End Date"/>
<?php echo form_error("end_date");?>
</div>
</div>
</div>
<?php //echo '<pre>';print_r($pkg_types);echo '</pre>';?>
<!-- <div class='span6' style='margint:0px;'>
<div class="control-group">
<label class="control-label" for="typeahead">Package Type <span class="text-red">*</span></label>
<div class="controls">
<select name='pkg_type' class='pkg_type'>
<option value='0'> Select Status Type </option>
<?php foreach($pkg_types as $a_status){?>
<option value='<?php echo $a_status->pkg_dur_id;?>'<?php if(isset($posted_data) && $posted_data['pkg_type'] == $a_status->pkg_dur_id)echo 'selected';?>><?php echo ucwords($a_status->pkg_dur_name);?> </option>
<?php }?>
</select>
<?php echo form_error("pkg_type");?>
</div>
</div>
</div> -->
<div class='span6' style='margint:0px;'>
<div class="control-group">
<label class="control-label" for="typeahead">Category Type <span class="text-red">*</span></label>
<div class="controls">
<select name='cat_type' class='cat_type'>
<option value='0'> Select Status Type </option>
<?php foreach($categories as $cat){?>
<option value='<?php echo $cat->category_id?>'<?php if(isset($posted_data) && $posted_data['cat_type'] == $cat->category_id)echo 'selected';?>><?php echo ucwords($cat->category_name);?> </option>
<?php }?>
</select>
<?php echo form_error("cat_type");?>
</div>
</div>
</div>
<div class="form-group">
<div class="col-lg-5"></div>
<div class="col-lg-2">
<input type="submit" name="get_details" value="Get Details" class="btn btn-default"/>
</div>
<div class="col-lg-5"></div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<?php if(isset($ad_reports)){
// echo '<pre>';print_r($ad_reports[0]);echo '</pre>';?>
<div class="row-fluid sortable2">
<div class="box span12">
<div class="box-header" data-original-title style='height:32px;padding:5px;'>
<h2><i class="halflings-icon white user"></i><span class="break"></span>List of Reports</h2>
<div class="box-icon" >
<a href="#" class="btn-minimize"><i class="halflings-icon white chevron-up"></i></a>
<a href="#" class="btn-close"><i class="halflings-icon white remove"></i></a>
</div>
</div>
<div class="box-content">
<table class="table table-striped table-bordered bootstrap-datatable datatable">
<thead>
<tr>
<th>Ad ID</th>
<th>Deal Tag</th>
<th>Report Title</th>
<th>Report Message</th>
<th>Category</th>
<th>Created on</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach($ad_reports as $list){?>
<tr>
<td><?php echo $list->ad_prefix.str_pad($list->ad_id, 7, "0", STR_PAD_LEFT);?></td>
<td><?php
$vasl = ucfirst($list->deal_tag);
echo $vasl;?></td>
<td><?php
$name = ucfirst($list->name);
echo $name;?></td>
<td style='word-break: break-all;'><?php
$val2 = $list->message;
echo $val2;?></td>
<td><?php
echo ucwords($list->category_name);?></td>
<td><?php
$val = date("d-m-Y H:i:s", strtotime($list->r_date));
echo $val;?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
<?php }?>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$(".generate_report").click(function () {
var report_type = $('.report_type').val();
var start_date = $('.start_date').val();
var pkg_type = $('.pkg_type').val();
var cat_type = $('.cat_type').val();
var end_date = $('.end_date').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>Reports/Get_report",
data: {
report_type: report_type,
start_date: start_date,
pkg_type: pkg_type,
cat_type: cat_type,
end_date: end_date
},
success: function (data) {
}
});
});
});
</script>
| 48,892
|
https://github.com/kaoecoito/odoo-brasil/blob/master/l10n_br_sale/models/account_move.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
odoo-brasil
|
kaoecoito
|
Python
|
Code
| 50
| 215
|
from odoo import fields, models
class AccountMove(models.Model):
_inherit = 'account.move'
carrier_partner_id = fields.Many2one('res.partner', string='Transportadora')
num_volumes = fields.Integer('Quant. total de volumes')
quant_peso = fields.Float('Peso')
# peso_uom = fields.Many2one('uom.uom')
nfe_number = fields.Integer(
string=u"Número NFe", compute="_compute_nfe_number")
def _compute_nfe_number(self):
for item in self:
docs = self.env['invoice.eletronic'].search(
[('invoice_id', '=', item.id)])
if docs:
item.nfe_number = docs[0].numero
| 8,364
|
https://github.com/yeoggc/FlinkUserBehaviorAnalysisProject/blob/master/MarketAnalysis/src/main/scala/com/ggc/ma/AdClickStatisticsByGeo.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
FlinkUserBehaviorAnalysisProject
|
yeoggc
|
Scala
|
Code
| 347
| 1,590
|
package com.ggc.ma
import java.sql.Timestamp
import org.apache.flink.api.common.functions.AggregateFunction
import org.apache.flink.api.common.state.{ValueState, ValueStateDescriptor}
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.functions.KeyedProcessFunction
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.scala.function.WindowFunction
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.api.windowing.windows.TimeWindow
import org.apache.flink.util.Collector
case class AdClickLog(userId: Long, adId: Long, province: String, city: String, timestamp: Long)
case class AdCountByProvince(windowEnd: String, province: String, count: Long)
case class BlackListWarning(userId: Long, adId: Long, msg: String)
object AdClickStatisticsByGeo extends App {
val env = StreamExecutionEnvironment.getExecutionEnvironment
env.setParallelism(1)
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)
val blackListOutputTag = new OutputTag[BlackListWarning]("blackListOutputTag")
val inputDS =
env
.readTextFile("/Users/yeoggc/Documents/AtguiguCode/Flink/Flink_Project_Atguigu/FlinkUserBehaviorAnalysisProject/res/AdClickLog.csv")
.map(data => {
val dataArray = data.split(",")
AdClickLog(dataArray(0).toLong, dataArray(1).toLong, dataArray(2), dataArray(3), dataArray(4).toLong)
})
.assignAscendingTimestamps(_.timestamp * 1000L)
// 添加黑名单过滤的逻辑
val filterBlackListDS =
inputDS
.keyBy(data => (data.userId, data.adId))
.process(new FilterBlackListProcessKeyedFunction(100))
val adCountDS =
filterBlackListDS
.keyBy(_.province)
.timeWindow(Time.hours(1), Time.seconds(10))
.aggregate(new CountAgg, new AdCountResultWindow)
adCountDS.print()
filterBlackListDS
.getSideOutput(blackListOutputTag)
.print("BlackList")
env.execute(getClass.getSimpleName)
}
class FilterBlackListProcessKeyedFunction(maxCount: Int) extends KeyedProcessFunction[(Long, Long), AdClickLog, AdClickLog] {
// 定义状态,保存用户对广告的点击量
lazy val countState: ValueState[Long] = getRuntimeContext.getState(new ValueStateDescriptor[Long]("count-state", classOf[Long]))
// 标识位,标记是否发送过黑名单信息
lazy val isSend: ValueState[Boolean] = getRuntimeContext.getState(new ValueStateDescriptor[Boolean]("isSent-state", classOf[Boolean]))
// 保存定时器触发的时间戳
lazy val resetTime: ValueState[Long] = getRuntimeContext.getState(new ValueStateDescriptor[Long]("resetTime-state", classOf[Long]))
override def processElement(value: AdClickLog,
ctx: KeyedProcessFunction[(Long, Long), AdClickLog, AdClickLog]#Context,
out: Collector[AdClickLog]): Unit = {
// 获取当前的count值
val curCount = countState.value()
// 判断如果是第一条数据,count值是0,就注册一个定时器
if (curCount == 0) {
val ts = (ctx.timerService().currentProcessingTime()
/ (1000 * 60 * 60 * 24) + 1) * 24 * 60 * 60 * 1000L
ctx.timerService().registerProcessingTimeTimer(ts)
resetTime.update(ts)
}
countState.update(curCount + 1)
// 判断计数是否超出上限,如果超过输出黑名单信息到侧输出流
if (curCount >= maxCount) {
// 判断如果没有发送过黑名单信息,就输出
if (!isSend.value()) {
// 判断如果没有发送过黑名单信息,就输出
//noinspection FieldFromDelayedInit
ctx.output(AdClickStatisticsByGeo.blackListOutputTag, BlackListWarning(value.userId, value.adId, "Click over " + maxCount + " times today"))
isSend.update(true)
}
} else {
out.collect(value)
}
}
override def onTimer(timestamp: Long,
ctx: KeyedProcessFunction[(Long, Long),
AdClickLog, AdClickLog]#OnTimerContext,
out: Collector[AdClickLog]): Unit = {
// 如果当前定时器是重置状态定时器,那么清空相应状态
if (timestamp == resetTime.value()) {
isSend.clear()
countState.clear()
}
}
}
class CountAgg extends AggregateFunction[AdClickLog, Long, Long] {
override def createAccumulator(): Long = 0L
override def add(value: AdClickLog, accumulator: Long): Long = accumulator + 1
override def getResult(accumulator: Long): Long = accumulator
override def merge(a: Long, b: Long): Long = a + b
}
class AdCountResultWindow extends WindowFunction[Long, AdCountByProvince, String, TimeWindow] {
override def apply(key: String,
window: TimeWindow,
input: Iterable[Long],
out: Collector[AdCountByProvince]): Unit = {
val windowEnd = new Timestamp(window.getEnd).toString
out.collect(AdCountByProvince(windowEnd, key, input.iterator.next()))
}
}
| 33,815
|
https://github.com/shayasmk1/Video/blob/master/config/module.php
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
Video
|
shayasmk1
|
PHP
|
Code
| 18
| 68
|
<?php
# config/module.php
return [
'modules' => [
'Auth',
'Managers',
'User',
'Video',
'Channel',
'Admin',
'Category',
'Settings'
]
];
| 31,017
|
https://github.com/dogukanyldz/FastCommerce/blob/master/FastCommerce.DAL/Migrations/20200830181517_ProductPlacementIds.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
FastCommerce
|
dogukanyldz
|
C#
|
Code
| 56
| 219
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace FastCommerce.DAL.Migrations
{
public partial class ProductPlacementIds : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "ProductID",
table: "Products",
newName: "ProductId");
migrationBuilder.AddColumn<int[]>(
name: "PlacementIds",
table: "Products",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "PlacementIds",
table: "Products");
migrationBuilder.RenameColumn(
name: "ProductId",
table: "Products",
newName: "ProductID");
}
}
}
| 22,745
|
https://github.com/rainner/biscuit-php/blob/master/src/Data/Import.php
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
biscuit-php
|
rainner
|
PHP
|
Code
| 493
| 1,302
|
<?php
/**
* Import class for processing a file and extracting values to be inserted to the db
*
* @package Biscuit
* @author Rainner Lins <rainnerlins@gmail.com>
* @copyright 2016 Rainner Lins
*/
namespace Biscuit\Data;
use Biscuit\Utils\Sanitize;
use Biscuit\Utils\Utils;
class Import {
// props
protected $_file = "";
protected $_format = "";
protected $_keymap = [];
/**
* Constructor
*/
public function __construct( $file="", $format="" )
{
$this->setFile( $file );
$this->setFormat( $format );
}
/**
* Set file to be read
*/
public function setFile( $file )
{
if( is_string( $file ) )
{
$this->_file = Sanitize::toPath( $file );
}
}
/**
* Set format (method) used to serialize the file data
*/
public function setFormat( $format )
{
if( is_string( $format ) )
{
$this->_format = Sanitize::toKey( $format );
}
}
/**
* Set the import keymap (dbColumn => fileParam)
*/
public function setKeymap( $map=[] )
{
if( is_array( $map ) )
{
foreach( $map as $key => $value )
{
$this->_keymap[ $key ] = $value;
}
}
}
/**
* Parse file data
*/
public function parse()
{
$output = [];
if( $data = @file_get_contents( $this->_file ) )
{
switch( $this->_format )
{
case "print_r" : $output = $this->_parsePrint( $data ); break;
case "var_dump" : $output = $this->_parseDump( $data ); break;
case "json_encode" : $output = $this->_parseJson( $data ); break;
case "serialize" : $output = $this->_parseSerial( $data ); break;
}
}
return $output;
}
/**
* Parse file data as PHP print_r() data dump
*/
private function _parsePrint( $data="" )
{
$output = [];
foreach( $this->_keymap as $key => $search )
{
@preg_match( "/(\[".$search."\])([\s\=\>]+)(.*)/u", $data, $matches );
$output[ $key ] = trim( Utils::value( @$matches[ 3 ], "" ) );
}
return $output;
}
/**
* Parse file data as PHP var_dump() data dump
*/
private function _parseDump( $data="" )
{
$output = [];
$data = preg_replace( "/(array|object|string)\(\w*\)(\#\d*\s*)?(\(\d*\))?\s*{?/ui", "", $data );
$data = preg_replace( "/(int|bool)\((\w+)\)/ui", "$2", $data );
$data = preg_replace( "/\s*=>[\r\n]+/ui", " => ", $data );
$data = preg_replace( "/[ ]{2,}/ui", " ", $data );
$data = str_replace( ['"', "{", "}"], "", $data );
foreach( $this->_keymap as $key => $search )
{
@preg_match( "/(\[".$search."\])([\s\=\>]+)(.*)/u", $data, $matches );
$output[ $key ] = trim( Utils::value( @$matches[ 3 ], "" ) );
}
return $output;
}
/**
* Parse file data as PHP json_encode() data dump
*/
private function _parseJson( $data="" )
{
$output = [];
if( $data = @json_decode( $data, true ) )
{
foreach( $this->_keymap as $key => $search )
{
if( array_key_exists( $search, $data ) )
{
$output[ $key ] = trim( $data[ $search ] );
}
}
}
return $output;
}
/**
* Parse file data as PHP serialize() data dump
*/
private function _parseSerial( $data="" )
{
$output = [];
if( $data = @unserialize( $data ) )
{
foreach( $this->_keymap as $key => $search )
{
if( array_key_exists( $search, $data ) )
{
$output[ $key ] = trim( $data[ $search ] );
}
}
}
return $output;
}
}
| 40,248
|
https://github.com/9tee/beego/blob/master/adapter/migration/migration.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
beego
|
9tee
|
Go
|
Code
| 451
| 969
|
// Copyright 2014 beego Author. 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.
// 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 migration is used for migration
//
// The table structure is as follow:
//
// CREATE TABLE `migrations` (
// `id_migration` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT 'surrogate key',
// `name` varchar(255) DEFAULT NULL COMMENT 'migration name, unique',
// `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'date migrated or rolled back',
// `statements` longtext COMMENT 'SQL statements for this migration',
// `rollback_statements` longtext,
// `status` enum('update','rollback') DEFAULT NULL COMMENT 'update indicates it is a normal migration while rollback means this migration is rolled back',
// PRIMARY KEY (`id_migration`)
// ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
package migration
import (
"github.com/Sonek-HoangBui/beego/v2/client/orm/migration"
)
// const the data format for the bee generate migration datatype
const (
DateFormat = "20060102_150405"
DBDateFormat = "2006-01-02 15:04:05"
)
// Migrationer is an interface for all Migration struct
type Migrationer interface {
Up()
Down()
Reset()
Exec(name, status string) error
GetCreated() int64
}
// Migration defines the migrations by either SQL or DDL
type Migration migration.Migration
// Up implement in the Inheritance struct for upgrade
func (m *Migration) Up() {
(*migration.Migration)(m).Up()
}
// Down implement in the Inheritance struct for down
func (m *Migration) Down() {
(*migration.Migration)(m).Down()
}
// Migrate adds the SQL to the execution list
func (m *Migration) Migrate(migrationType string) {
(*migration.Migration)(m).Migrate(migrationType)
}
// SQL add sql want to execute
func (m *Migration) SQL(sql string) {
(*migration.Migration)(m).SQL(sql)
}
// Reset the sqls
func (m *Migration) Reset() {
(*migration.Migration)(m).Reset()
}
// Exec execute the sql already add in the sql
func (m *Migration) Exec(name, status string) error {
return (*migration.Migration)(m).Exec(name, status)
}
// GetCreated get the unixtime from the Created
func (m *Migration) GetCreated() int64 {
return (*migration.Migration)(m).GetCreated()
}
// Register register the Migration in the map
func Register(name string, m Migrationer) error {
return migration.Register(name, m)
}
// Upgrade upgrade the migration from lasttime
func Upgrade(lasttime int64) error {
return migration.Upgrade(lasttime)
}
// Rollback rollback the migration by the name
func Rollback(name string) error {
return migration.Rollback(name)
}
// Reset reset all migration
// run all migration's down function
func Reset() error {
return migration.Reset()
}
// Refresh first Reset, then Upgrade
func Refresh() error {
return migration.Refresh()
}
| 33,717
|
https://github.com/zstars/booledeusto/blob/master/include/antlr/CharScanner.hpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
booledeusto
|
zstars
|
C++
|
Code
| 1,751
| 4,712
|
#ifndef INC_CharScanner_hpp__
#define INC_CharScanner_hpp__
/*
* <b>SOFTWARE RIGHTS</b>
* <p>
* ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001
* <p>
* $Id: //depot/code/org.antlr/main/main/lib/cpp/antlr/CharScanner.hpp#11 $
* <p>
* We reserve no legal rights to the ANTLR--it is fully in the
* public domain. An individual or company may do whatever
* they wish with source code distributed with ANTLR or the
* code generated by ANTLR, including the incorporation of
* ANTLR, or its output, into commerical software.
* <p>
* We encourage users to develop software with ANTLR. However,
* we do ask that credit is given to us for developing
* ANTLR. By "credit", we mean that if you use ANTLR or
* incorporate any source code into one of your programs
* (commercial product, research project, or otherwise) that
* you acknowledge this fact somewhere in the documentation,
* research report, etc... If you like ANTLR and have
* developed a nice tool with the output, please mention that
* you developed it using ANTLR. In addition, we ask that the
* headers remain intact in our source code. As long as these
* guidelines are kept, we expect to continue enhancing this
* system and expect to make other tools available as they are
* completed.
* <p>
* The ANTLR gang:
* @version ANTLR 2.7.1 MageLang Insitute, 1999, 2000, 2001
* @author Terence Parr, <a href=http://www.MageLang.com>MageLang Institute</a>
* @author <br>John Lilley, <a href=http://www.Empathy.com>Empathy Software</a>
* @author <br><a href="mailto:pete@yamuna.demon.co.uk">Pete Wells</a>
*/
#include <antlr/config.hpp>
#include <antlr/TokenStream.hpp>
#include <antlr/RecognitionException.hpp>
#include <antlr/MismatchedCharException.hpp>
#include <antlr/InputBuffer.hpp>
#include <antlr/BitSet.hpp>
#include <antlr/LexerSharedInputState.hpp>
#include <map>
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
namespace antlr {
#endif
class ANTLR_API CharScanner;
ANTLR_C_USING(tolower)
#ifdef ANTLR_REALLY_NO_STRCASECMP
// Apparently, neither strcasecmp nor stricmp is standard, and Codewarrior
// on the mac has neither...
inline int strcasecmp(const char *s1, const char *s2)
{
while (true)
{
char c1 = tolower(*s1++),
c2 = tolower(*s2++);
if (c1 < c2) return -1;
if (c1 > c2) return 1;
if (c1 == 0) return 0;
}
}
#else
#ifdef NO_STRCASECMP
ANTLR_C_USING(stricmp)
#else
ANTLR_C_USING(strcasecmp)
#endif
#endif
/** Functor for the literals map
*/
class ANTLR_API CharScannerLiteralsLess : public ANTLR_USE_NAMESPACE(std)binary_function<ANTLR_USE_NAMESPACE(std)string,ANTLR_USE_NAMESPACE(std)string,bool> {
private:
const CharScanner* scanner;
public:
#ifdef NO_TEMPLATE_PARTS
CharScannerLiteralsLess(); // not really used
#endif
CharScannerLiteralsLess(const CharScanner* theScanner)
: scanner(theScanner)
{
}
bool operator() (const ANTLR_USE_NAMESPACE(std)string& x,const ANTLR_USE_NAMESPACE(std)string& y) const;
// defaults are good enough..
// CharScannerLiteralsLess(const CharScannerLiteralsLess&);
// CharScannerLiteralsLess& operator=(const CharScannerLiteralsLess&);
};
/** Superclass of generated lexers
*/
class ANTLR_API CharScanner : public TokenStream {
protected:
typedef RefToken (*factory_type)();
public:
CharScanner();
CharScanner(InputBuffer& cb);
CharScanner(InputBuffer* cb);
CharScanner(const LexerSharedInputState& state);
virtual ~CharScanner()
{
}
virtual int LA(int i);
virtual void append(char c)
{
if (saveConsumedInput) {
int l = text.length();
if ((l%256) == 0)
text.reserve(l+256);
text.replace(l,0,&c,1);
}
}
virtual void append(const ANTLR_USE_NAMESPACE(std)string& s)
{
if (saveConsumedInput)
text+=s;
}
virtual void commit()
{
inputState->getInput().commit();
}
virtual void consume();
/** Consume chars until one matches the given char */
virtual void consumeUntil(int c)
{
for(;;)
{
int la_1 = LA(1);
if( la_1 == EOF_CHAR || la_1 == c )
break;
consume();
}
}
/** Consume chars until one matches the given set */
virtual void consumeUntil(const BitSet& set)
{
int la_1 = LA(1);
while( la_1 != EOF_CHAR && !set.member(la_1) )
consume();
}
/// Mark the current position and return a id for it
virtual int mark()
{
return inputState->getInput().mark();
}
/// Rewind the scanner to a previously marked position
virtual void rewind(int pos)
{
inputState->getInput().rewind(pos);
}
/// See if input contains character 'c' throw MismatchedCharException if not
virtual void match(int c)
{
int la_1 = LA(1);
if ( la_1 != c )
throw MismatchedCharException(la_1, c, false, this);
consume();
}
/** See if input contains element from bitset b
* throw MismatchedCharException if not
*/
virtual void match(const BitSet& b)
{
if (!b.member(LA(1))) {
throw MismatchedCharException(LA(1),b,false,this);
}
consume();
}
/// See if input contains string 's' throw MismatchedCharException if not
virtual void match(const ANTLR_USE_NAMESPACE(std)string& s)
{
int len = s.length();
for (int i = 0; i < len; i++)
{
int la_1 = LA(1);
if ( la_1 != s[i] )
throw MismatchedCharException(la_1, s[i], false, this);
consume();
}
}
/** See if input does not contain character 'c'
* throw MismatchedCharException if not
*/
virtual void matchNot(int c)
{
int la_1 = LA(1);
if ( la_1 == c )
throw MismatchedCharException(la_1, c, true, this);
consume();
}
/** See if input contains character in range c1-c2
* throw MismatchedCharException if not
*/
virtual void matchRange(int c1, int c2)
{
int la_1 = LA(1);
if ( la_1 < c1 || la_1 > c2 )
throw MismatchedCharException(la_1, c1, c2, false, this);
consume();
}
virtual bool getCaseSensitive() const
{
return caseSensitive;
}
virtual void setCaseSensitive(bool t)
{
caseSensitive = t;
}
virtual bool getCaseSensitiveLiterals() const=0;
/// Get the line the scanner currently is in (starts at 1)
virtual int getLine() const
{
return inputState->line;
}
/// set the line number
virtual void setLine(int l)
{
inputState->line = l;
}
/// Get the column the scanner currently is in (starts at 1)
virtual int getColumn() const
{
return inputState->column;
}
/// set the column number
virtual void setColumn(int c)
{
inputState->column = c;
}
/// get the filename for the file currently used
virtual const ANTLR_USE_NAMESPACE(std)string& getFilename() const
{
return inputState->filename;
}
/// Set the filename the scanner is using (used in error messages)
virtual void setFilename(const ANTLR_USE_NAMESPACE(std)string& f)
{
inputState->filename=f;
}
virtual bool getCommitToPath() const
{
return commitToPath;
}
virtual void setCommitToPath(bool commit)
{
commitToPath = commit;
}
/** return a copy of the current text buffer */
virtual const ANTLR_USE_NAMESPACE(std)string& getText() const
{
return text;
}
virtual void setText(const ANTLR_USE_NAMESPACE(std)string& s)
{
text = s;
}
virtual void resetText()
{
text="";
inputState->tokenStartColumn = inputState->column;
inputState->tokenStartLine = inputState->line;
}
virtual RefToken getTokenObject() const
{
return _returnToken;
}
/** Used to keep track of line breaks, needs to be called from
* within generated lexers when a \n \r is encountered.
*/
virtual void newline()
{
++inputState->line;
inputState->column=1;
}
/** Advance the current column number by an appropriate amount according
* to the tabsize. This methad is called automatically from consume()
*/
virtual void tab()
{
int c = getColumn();
int nc = ( ((c-1)/tabsize) + 1) * tabsize + 1; // calculate tab stop
setColumn( nc );
}
/// set the tabsize. Returns the old tabsize
int setTabsize( int size )
{
int oldsize = tabsize;
tabsize = size;
return oldsize;
}
/// Return the tabsize used by the scanner
int getTabSize() const
{
return tabsize;
}
/// Called when a unrecoverable error is encountered
void panic();
/// Called when a unrecoverable error is encountered
void panic(const ANTLR_USE_NAMESPACE(std)string& s);
/** Report exception errors caught in nextToken() */
virtual void reportError(const RecognitionException& e);
/** Parser error-reporting function can be overridden in subclass */
virtual void reportError(const ANTLR_USE_NAMESPACE(std)string& s);
/** Parser warning-reporting function can be overridden in subclass */
virtual void reportWarning(const ANTLR_USE_NAMESPACE(std)string& s);
virtual InputBuffer& getInputBuffer()
{
return inputState->getInput();
}
virtual LexerSharedInputState getInputState()
{
return inputState;
}
/** set the input state for the lexer.
* @note state is a reference counted object, hence no reference */
virtual void setInputState(LexerSharedInputState state)
{
inputState = state;
}
/// Set the factory for created tokens
virtual void setTokenObjectFactory(factory_type factory)
{
tokenFactory = factory;
}
/** Test the token text against the literals table
* Override this method to perform a different literals test
*/
virtual int testLiteralsTable(int ttype) const
{
ANTLR_USE_NAMESPACE(std)map<ANTLR_USE_NAMESPACE(std)string,int,CharScannerLiteralsLess>::const_iterator i = literals.find(text);
if (i != literals.end())
ttype = (*i).second;
return ttype;
}
/** Test the text passed in against the literals table
* Override this method to perform a different literals test
* This is used primarily when you want to test a portion of
* a token
*/
virtual int testLiteralsTable(const ANTLR_USE_NAMESPACE(std)string& txt,int ttype) const
{
ANTLR_USE_NAMESPACE(std)map<ANTLR_USE_NAMESPACE(std)string,int,CharScannerLiteralsLess>::const_iterator i = literals.find(txt);
if (i != literals.end())
ttype = (*i).second;
return ttype;
}
/// Override this method to get more specific case handling
virtual int toLower(int c) const
{
// test on EOF_CHAR for buggy (?) STLPort tolower (or HPUX tolower?)
// also VC++ 6.0 does this. (see fix 422 (is reverted by this fix)
// this one is more structural. Maybe make this configurable.
return (c == EOF_CHAR ? EOF_CHAR : tolower(c));
}
/** This method is called by YourLexer::nextToken() when the lexer has
* hit EOF condition. EOF is NOT a character.
* This method is not called if EOF is reached during
* syntactic predicate evaluation or during evaluation
* of normal lexical rules, which presumably would be
* an IOException. This traps the "normal" EOF condition.
*
* uponEOF() is called after the complete evaluation of
* the previous token and only if your parser asks
* for another token beyond that last non-EOF token.
*
* You might want to throw token or char stream exceptions
* like: "Heh, premature eof" or a retry stream exception
* ("I found the end of this file, go back to referencing file").
*/
virtual void uponEOF()
{
}
/// Methods used to change tracing behavior
virtual void traceIndent();
virtual void traceIn(const char* rname);
virtual void traceOut(const char* rname);
#ifndef NO_STATIC_CONSTS
static const int EOF_CHAR = EOF;
#else
enum {
EOF_CHAR = EOF
};
#endif
protected:
ANTLR_USE_NAMESPACE(std)string text; ///< Text of current token
/// flag indicating wether consume saves characters
bool saveConsumedInput;
factory_type tokenFactory; ///< Factory for tokens
bool caseSensitive; ///< Is this lexer case sensitive
ANTLR_USE_NAMESPACE(std)map<ANTLR_USE_NAMESPACE(std)string,int,CharScannerLiteralsLess> literals; // set by subclass
RefToken _returnToken; ///< used to return tokens w/o using return val
/// Input state, gives access to input stream, shared among different lexers
LexerSharedInputState inputState;
/** Used during filter mode to indicate that path is desired.
* A subsequent scan error will report an error as usual
* if acceptPath=true;
*/
bool commitToPath;
int tabsize; ///< tab size the scanner uses.
/// Create a new RefToken of type t
virtual RefToken makeToken(int t)
{
RefToken tok = tokenFactory();
tok->setType(t);
tok->setColumn(inputState->tokenStartColumn);
tok->setLine(inputState->tokenStartLine);
return tok;
}
/** Tracer class, used when -traceLexer is passed to antlr
*/
class Tracer {
private:
CharScanner* parser;
const char* text;
public:
Tracer( CharScanner* p,const char* t )
: parser(p), text(t)
{
parser->traceIn(text);
}
~Tracer()
{
parser->traceOut(text);
}
};
int traceDepth;
private:
#ifndef NO_STATIC_CONSTS
static const int NO_CHAR = 0;
#else
enum {
NO_CHAR = 0
};
#endif
};
inline int CharScanner::LA(int i)
{
int c = inputState->getInput().LA(i);
if ( caseSensitive )
return c;
else
return toLower(c); // VC 6 tolower bug caught in toLower.
}
inline bool CharScannerLiteralsLess::operator() (const ANTLR_USE_NAMESPACE(std)string& x,const ANTLR_USE_NAMESPACE(std)string& y) const
{
if (scanner->getCaseSensitiveLiterals()) {
return ANTLR_USE_NAMESPACE(std)less<ANTLR_USE_NAMESPACE(std)string>()(x,y);
} else {
#ifdef NO_STRCASECMP
return (stricmp(x.c_str(),y.c_str())<0);
#else
return (strcasecmp(x.c_str(),y.c_str())<0);
#endif
}
}
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
}
#endif
#endif //INC_CharScanner_hpp__
| 46,298
|
https://github.com/ProteoWizard/pwiz/blob/master/pwiz_tools/Bumbershoot/idpicker/Qonverter/waffles/GOptimizer.cpp
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-free-unknown, Apache-2.0
| 2,023
|
pwiz
|
ProteoWizard
|
C++
|
Code
| 444
| 1,714
|
/*
Copyright (C) 2006, Mike Gashler
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
see http://www.gnu.org/copyleft/lesser.html
*/
#include "GOptimizer.h"
#include <string.h>
#include "GVec.h"
#include "GRand.h"
namespace GClasses {
using std::vector;
GTargetFunction::GTargetFunction(size_t dims)
{
m_pRelation = new GUniformRelation(dims, 0);
}
// -------------------------------------------------------
GOptimizer::GOptimizer(GTargetFunction* pCritic)
: m_pCritic(pCritic)
{
}
/*virtual*/ GOptimizer::~GOptimizer()
{
}
double GOptimizer::searchUntil(size_t nBurnInIterations, size_t nIterations, double dImprovement)
{
for(size_t i = 1; i < nBurnInIterations; i++)
iterate();
double dPrevError;
double dError = iterate();
while(true)
{
dPrevError = dError;
for(size_t i = 1; i < nIterations; i++)
iterate();
dError = iterate();
if((dPrevError - dError) / dPrevError < dImprovement)
break;
}
return dError;
}
// -------------------------------------------------------
GParallelOptimizers::GParallelOptimizers(size_t dims)
{
if(dims > 0)
m_pRelation = new GUniformRelation(dims, 0);
std::vector<GTargetFunction*> m_targetFunctions;
std::vector<GOptimizer*> m_optimizers;
}
GParallelOptimizers::~GParallelOptimizers()
{
for(vector<GOptimizer*>::iterator it = m_optimizers.begin(); it != m_optimizers.end(); it++)
delete(*it);
for(vector<GTargetFunction*>::iterator it = m_targetFunctions.begin(); it != m_targetFunctions.end(); it++)
delete(*it);
}
void GParallelOptimizers::add(GTargetFunction* pTargetFunction, GOptimizer* pOptimizer)
{
m_targetFunctions.push_back(pTargetFunction);
m_optimizers.push_back(pOptimizer);
}
double GParallelOptimizers::iterateAll()
{
double err = 0;
for(vector<GOptimizer*>::iterator it = m_optimizers.begin(); it != m_optimizers.end(); it++)
err += (*it)->iterate();
return err;
}
double GParallelOptimizers::searchUntil(size_t nBurnInIterations, size_t nIterations, double dImprovement)
{
for(size_t i = 1; i < nBurnInIterations; i++)
iterateAll();
double dPrevError;
double dError = iterateAll();
while(true)
{
dPrevError = dError;
for(size_t i = 1; i < nIterations; i++)
iterateAll();
dError = iterateAll();
if((dPrevError - dError) / dPrevError < dImprovement)
break;
}
return dError;
}
// -------------------------------------------------------
class GAction
{
protected:
int m_nAction;
GAction* m_pPrev;
unsigned int m_nRefs;
~GAction()
{
if(m_pPrev)
m_pPrev->Release(); // todo: this could overflow the stack with recursion
}
public:
GAction(int nAction, GAction* pPrev)
: m_nAction(nAction), m_nRefs(0)
{
m_pPrev = pPrev;
if(pPrev)
pPrev->AddRef();
}
void AddRef()
{
m_nRefs++;
}
void Release()
{
if(--m_nRefs == 0)
delete(this);
}
GAction* GetPrev() { return m_pPrev; }
int GetAction() { return m_nAction; }
};
// -------------------------------------------------------
GActionPath::GActionPath(GActionPathState* pState) : m_pLastAction(NULL), m_nPathLen(0)
{
m_pHeadState = pState;
}
GActionPath::~GActionPath()
{
if(m_pLastAction)
m_pLastAction->Release();
delete(m_pHeadState);
}
void GActionPath::doAction(size_t nAction)
{
GAction* pPrevAction = m_pLastAction;
m_pLastAction = new GAction((int)nAction, pPrevAction);
m_pLastAction->AddRef(); // referenced by m_pLastAction
if(pPrevAction)
pPrevAction->Release(); // no longer referenced by m_pLastAction
m_nPathLen++;
m_pHeadState->performAction(nAction);
}
GActionPath* GActionPath::fork()
{
GActionPath* pNewPath = new GActionPath(m_pHeadState->copy());
pNewPath->m_nPathLen = m_nPathLen;
pNewPath->m_pLastAction = m_pLastAction;
if(m_pLastAction)
m_pLastAction->AddRef();
return pNewPath;
}
void GActionPath::path(size_t nCount, size_t* pOutBuf)
{
while(nCount > m_nPathLen)
pOutBuf[--nCount] = -1;
size_t i = m_nPathLen;
GAction* pAction = m_pLastAction;
while(i > nCount)
{
i--;
pAction = pAction->GetPrev();
}
while(i > 0)
{
pOutBuf[--i] = pAction->GetAction();
pAction = pAction->GetPrev();
}
}
double GActionPath::critique()
{
return m_pHeadState->critiquePath(m_nPathLen, m_pLastAction);
}
} // namespace GClasses
| 27,421
|
https://github.com/janehmueller/trufflesqueak/blob/master/src/de.hpi.swa.trufflesqueak/src/de/hpi/swa/trufflesqueak/tools/SqueakMessageInterceptor.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
trufflesqueak
|
janehmueller
|
Java
|
Code
| 249
| 914
|
/*
* Copyright (c) 2017-2022 Software Architecture Group, Hasso Plattner Institute
* Copyright (c) 2021-2022 Oracle and/or its affiliates
*
* Licensed under the MIT License.
*/
package de.hpi.swa.trufflesqueak.tools;
import org.graalvm.polyglot.Context;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.instrumentation.EventContext;
import com.oracle.truffle.api.instrumentation.ExecutionEventListener;
import com.oracle.truffle.api.instrumentation.SourceSectionFilter;
import com.oracle.truffle.api.instrumentation.StandardTags.CallTag;
import com.oracle.truffle.api.instrumentation.TruffleInstrument;
import de.hpi.swa.trufflesqueak.SqueakLanguage;
import de.hpi.swa.trufflesqueak.SqueakOptions;
@TruffleInstrument.Registration(id = SqueakMessageInterceptor.ID, services = SqueakMessageInterceptor.class)
public final class SqueakMessageInterceptor extends TruffleInstrument {
public static final String ID = "squeak-message-interceptor";
private static final String DEFAULTS = "TestCase>>runCase,TestCase>>logFailure:,TestCase>>signalFailure:,Object>>halt,Object>>inform:," + //
"SmalltalkImage>>logSqueakError:inContext:,UnhandledError>>defaultAction,SyntaxErrorNotification>>setClass:code:doitFlag:errorMessage:location:";
private static String[] breakpoints;
public static void enableIfRequested(final SqueakLanguage.Env env) {
if (env.getOptions().hasBeenSet(SqueakOptions.InterceptMessages)) {
/* Looking up instrument to activate it. */
breakpoints = (DEFAULTS + "," + env.getOptions().get(SqueakOptions.InterceptMessages)).split(",");
Context.getCurrent().getEngine().getInstruments().get(ID).lookup(SqueakMessageInterceptor.class);
}
}
@Override
protected void onCreate(final Env env) {
assert breakpoints != null;
env.registerService(this);
env.getInstrumenter().attachExecutionEventListener(
SourceSectionFilter.newBuilder().tagIs(CallTag.class).rootNameIs(s -> {
if (s == null) {
return false;
}
for (final String breakpoint : breakpoints) {
if (s.contains(breakpoint)) {
return true;
}
}
return false;
}).build(),
new ExecutionEventListener() {
/*
* This is the "halt" method - put a breakpoint in your IDE on the print
* statement within.
*/
@Override
public void onEnter(final EventContext context, final VirtualFrame frame) {
printToStdOut(context);
}
@TruffleBoundary
private void printToStdOut(final EventContext context) {
// Checkstyle: stop
System.out.println("Entering " + context.getInstrumentedSourceSection().getSource().getName() + "...");
// Checkstyle: resume
}
@Override
public void onReturnValue(final EventContext context, final VirtualFrame frame, final Object result) {
/* Nothing to do. */
}
@Override
public void onReturnExceptional(final EventContext context, final VirtualFrame frame, final Throwable exception) {
/* Nothing to do. */
}
});
}
}
| 26,230
|
https://github.com/5ulas/shop/blob/master/app/Models/Employee.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
shop
|
5ulas
|
PHP
|
Code
| 58
| 197
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
use HasFactory;
protected $table = 'employees';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'surname',
'age',
'statistics',
'position',
'salary',
'password',
'user_id'
];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
| 50,721
|
https://github.com/ClapeyronThermo/Clapeyron.jl/blob/master/src/modules/solvers/nanmath.jl
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
Clapeyron.jl
|
ClapeyronThermo
|
Julia
|
Code
| 156
| 549
|
const BigNaN = big"NaN"
@inline nan(::T) where T = nan(T)
@inline nan(::Type{Float16}) = NaN16
@inline nan(::Type{Float32}) = NaN32
@inline nan(::Type{Float64}) = NaN64
#TODO: define nan for integer types
@inline nan(::Type{BigFloat}) = BigNaN
@inline nan(::Type{BigInt}) = BigNaN
@inline nan(::Type{T}) where T<:Real = zero(T)/zero(T)
#check if this gives out the correct behaviour.
@inline nan(::Type{T}) where T <: Rational{V} where V = nan(V)
@inline log(x) = Base.log(x)
@inline function log(x::T) where T <:Real
_0 = zero(T)
res = Base.log(max(_0,x))
ifelse(x>=_0,res,nan(res))
end
@inline sqrt(x) = Base.sqrt(x)
@inline function sqrt(x::T) where T <:Real
_0 = zero(x)
res = Base.sqrt(max(_0,x))
ifelse(x>=_0,res,nan(res))
end
@inline log1p(x) = Base.log1p(x)
@inline function log1p(x::T) where T <:Real
_m1 = -one(x)
_0 = zero(x)
res = Base.log1p(max(_m1,x))
ifelse(x>=_m1,res,nan(res))
end
const basepow = Base.:^
@inline function ^(x::Real, y::Real)
x,y,_nan = promote(x,y,nan(x*y)) #this will make pow type-stable, at the cost of losing Integer exponentiation
z = ifelse(x>=zero(x),x,_nan)
return basepow(z,y)
end
@inline function ^(x::Real, y::Int)
return basepow(x,y)
end
^(x,y) = basepow(x,y)
| 36,721
|
https://github.com/ohxh/warpspace/blob/master/src/components/OverviewTab/OverviewTabContextMenu.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
warpspace
|
ohxh
|
TypeScript
|
Code
| 20
| 52
|
import React from "react";
export const OverviewTabContextMenu: React.FC<{}> = ({ children }) => {
//useTabSelection
return <div>
{children}
</div>
}
| 4,404
|
https://github.com/keithtan/main/blob/master/src/test/java/seedu/superta/logic/parser/MarkAttendanceCommandParserTest.java
|
Github Open Source
|
Open Source
|
MIT
| null |
main
|
keithtan
|
Java
|
Code
| 182
| 728
|
package seedu.superta.logic.parser;
import static seedu.superta.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.superta.logic.commands.CommandTestUtil.VALID_STUDENT_ID_AMY;
import static seedu.superta.logic.parser.CliSyntax.PREFIX_GENERAL_STUDENT_ID;
import static seedu.superta.logic.parser.CliSyntax.PREFIX_GENERAL_TUTORIAL_GROUP_ID;
import static seedu.superta.logic.parser.CliSyntax.PREFIX_SESSION_NAME;
import static seedu.superta.logic.parser.CommandParserTestUtil.assertParseFailure;
import static seedu.superta.logic.parser.CommandParserTestUtil.assertParseSuccess;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import seedu.superta.logic.commands.MarkAttendanceCommand;
import seedu.superta.model.attendance.Session;
import seedu.superta.model.student.StudentId;
// @@author triger15
public class MarkAttendanceCommandParserTest {
private MarkAttendanceCommandParser parser = new MarkAttendanceCommandParser();
private final String tgId = "01a";
private final Session session = new Session("Lab 1");
private Set<StudentId> idSet;
@Before
public void setUp() {
idSet = new HashSet<>();
idSet.add(new StudentId(VALID_STUDENT_ID_AMY));
}
@Test
public void parse_allFieldsPresent_success() {
String userInput = " " + PREFIX_GENERAL_TUTORIAL_GROUP_ID + tgId + " "
+ PREFIX_SESSION_NAME + session.getSessionName() + " "
+ PREFIX_GENERAL_STUDENT_ID + VALID_STUDENT_ID_AMY;
MarkAttendanceCommand expectedCommand = new MarkAttendanceCommand(tgId, session, idSet);
assertParseSuccess(parser, userInput, expectedCommand);
}
@Test
public void parse_missingCompulsoryField_failure() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, MarkAttendanceCommand.MESSAGE_USAGE);
// tutorial group id missing
assertParseFailure(parser, " n/" + session.getSessionName() + " st/" + VALID_STUDENT_ID_AMY,
expectedMessage);
// session missing
assertParseFailure(parser, " tg/" + tgId + " st/" + VALID_STUDENT_ID_AMY, expectedMessage);
// student ids missing
assertParseFailure(parser, " n/" + session.getSessionName() + " tg/" + tgId, expectedMessage);
// all prefixes missing
assertParseFailure(parser, "", expectedMessage);
}
}
| 48,855
|
https://github.com/DominikDitoIvosevic/Fusky/blob/master/front-ps/src/App/Components/RadioDescr.purs
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
Fusky
|
DominikDitoIvosevic
|
PureScript
|
Code
| 94
| 319
|
module App.Components.RadioDescr where
import Angular.Common (commonDirectives)
import Angular.Core (Component, createComponent)
import Utilities.Angular (Decorator, toNgClass, DecoratedNgClass, decorateNgClass, NgClassProto, Directive)
type RadioDescrScope = { }
radioDescrScope :: RadioDescrScope
radioDescrScope = { }
radioDescrDirectives :: Array Directive
radioDescrDirectives = [ commonDirectives ]
radioDescrComponent :: Decorator
radioDescrComponent = createComponent {
selector: "radio-descr",
templateUrl: "dest/components/radioDescr/radioDescr.html",
styles: [],
directives: radioDescrDirectives
}
radioDescrProto :: NgClassProto RadioDescrScope RadioDescrMemberFunctions
radioDescrProto = {
name: "radioDescr",
classScope: radioDescrScope,
memberFunctions: radioDescrMemberFunctions
}
type RadioDescrMemberFunctions = { }
radioDescrMemberFunctions :: RadioDescrMemberFunctions
radioDescrMemberFunctions = { }
radioDescr :: DecoratedNgClass
radioDescr = decorateNgClass (toNgClass radioDescrProto) [
radioDescrComponent
] []
| 17,393
|
https://github.com/andreiciortea/thingsnet/blob/master/public/scenario/jane.ttl
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
thingsnet
|
andreiciortea
|
Turtle
|
Code
| 43
| 358
|
@prefix stn: <http://purl.org/stn/core#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
# Jane's profile
<http://localhost:9003/users/f6359041-4b7d-43b4-aa98-b1a79d11ae8d#Jane>
a stn:Person ;
stn:holds <http://localhost:9003/users/f6359041-4b7d-43b4-aa98-b1a79d11ae8d> ;
stn:owns <http://localhost:9003/users/4d78ced5-7ae2-49d4-9fe7-6a7910c44ccd#thing> .
<http://localhost:9003/users/f6359041-4b7d-43b4-aa98-b1a79d11ae8d>
a stn:UserAccount ;
stn:description ( "Doe. Ms. Jane Doe."^^xsd:string ) ;
stn:heldBy <http://localhost:9003/users/f6359041-4b7d-43b4-aa98-b1a79d11ae8d#Jane> ;
stn:hostedBy <http://localhost:9003/assets/stnspecs/thingsnet.ttl#platform> ;
stn:name "Jane Doe"^^xsd:string .
| 4,714
|
https://github.com/NobukazuHanada/creatives/blob/master/purescript/second/src/Main.purs
|
Github Open Source
|
Open Source
|
MIT
| null |
creatives
|
NobukazuHanada
|
PureScript
|
Code
| 400
| 892
|
module Main where
import Prelude
import qualified Math as M
import qualified Data.Vector2 as V
import qualified Data.Vector as V
import Control.Monad.Eff
import Control.Monad.Eff.Console
import Control.Monad.ST
import Control.Monad.Eff.Random
import Control.Apply
import Data.Array.ST
import Graphics.Canvas
import Data.Maybe
import DOM
import Signal
import Signal.Time
foreign import windowWidth :: forall eff. Eff ( dom :: DOM | eff ) Number
foreign import windowHeight :: forall eff. Eff ( dom :: DOM | eff ) Number
main = do
Just element <- getCanvasElementById "canvas"
width <- windowWidth
height <- windowHeight
setCanvasWidth width element
setCanvasHeight height element
context <- getContext2D element
initRef <- emptySTArray
forE 0.0 50.0 (\_ -> do
x <- map (* width) random
y <- map (* height) random
r <- map (\x -> x * 70.0 + 50.0) random
c <- map (\x -> "hsla(" ++ show (x * 360.0) ++ ",100%,50%, 0.4)") random
pushSTArray initRef $ {x:x, y:y, r:r, c:c}
return unit)
runSignal $ loop ~> (\angle -> do
clearRect context {x:0.0,y:0.0,w:width,h:height}
init <- toAssocArray initRef
foreachE init (\{index:_, value:{x:x,y:y,r:r,c:c}} -> do
draw context x y r (angle * (50.0/r)) c
return unit))
loop = foldp (\a b -> b + 0.2) 0.0 (every $ 50.0 * millisecond)
draw context x y radius baseAngle color = do
beginPath context
translate { translateX : x, translateY : y } context
setGlobalAlpha context 0.0
setLineWidth 2.5 context
setFillStyle color context
forE 0.0 samples (\i ->
let
-- previus
preAngle = M.pi * 2.0 * (i - 1.0) / samples
preR = (func (preAngle * 10.0) radius) + radius
prePos = V.scale preR $ V.vec2 (M.sin preAngle) (M.cos preAngle)
-- current
angle = M.pi * 2.0 * i / samples
r = (func (angle * 10.0) radius) + radius
pos = V.scale r $ V.vec2 (M.sin $ angle + baseAngle) (M.cos $ angle + baseAngle)
in
do
line context prePos pos
return unit
)
closePath context
fill context
translate { translateX : (0.0 - x), translateY : (0.0 - y) } context
where
samples = 200.0
func angle radius =
let
a = radius / 20.0
in
a * (10.0 * M.pow (M.sin $ angle / 2.0 + 1.0) 3.0) + (20.0 * (M.sin $ angle + 3.0))
line context origin to =
let
originX = V.get2X origin + 0.5
originY = V.get2Y origin + 0.5
toX = V.get2X to + 0.5
toY = V.get2Y to + 0.5
in
lineTo context toX toY
| 26,763
|
https://github.com/JetBrains/teamcity-s3-artifact-storage-plugin/blob/master/s3-artifact-storage-ui/src/contexts/AwsConnectionsContext.tsx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
teamcity-s3-artifact-storage-plugin
|
JetBrains
|
TSX
|
Code
| 200
| 628
|
import { React } from '@jetbrains/teamcity-api';
import { ReactNode, useContext, useEffect, useMemo, useState } from 'react';
import { Option } from '@jetbrains-internal/tcci-react-ui-components';
import useAwsConnections from '../hooks/useAwsConnections';
import { AwsConnection } from '../App/AwsConnection/AvailableAwsConnectionsConstants';
import { useAppContext } from './AppContext';
type AwsConnectionsContextType = {
isLoading: boolean;
connectionOptions: Option<AwsConnection>[] | undefined;
error: string | undefined;
withFake?: boolean;
reloadConnectionOptions: () => void;
};
const AwsConnectionsContext = React.createContext<AwsConnectionsContextType>({
connectionOptions: undefined,
error: undefined,
isLoading: true,
reloadConnectionOptions: () => {},
});
const { Provider } = AwsConnectionsContext;
interface OwnProps {
children: ReactNode;
}
function AwsConnectionsContextProvider({ children }: OwnProps) {
const {
chosenAwsConnectionId,
accessKeyIdValue,
secretAcessKeyValue,
isDefaultCredentialsChain,
} = useAppContext();
const value = useAwsConnections();
const connectionOptions = useMemo(
() => value.connectionOptions || [],
[value.connectionOptions]
);
const [withFake, setWithFake] = useState(false);
// meaning that we have outdated configuration with secrets
// or migrating from S3 Compatible
useEffect(() => {
if (
!chosenAwsConnectionId &&
((accessKeyIdValue && secretAcessKeyValue) || isDefaultCredentialsChain)
) {
// create a fake connection
const fake = {
key: 'fake',
label: '',
} as Option<AwsConnection>;
connectionOptions.unshift(fake);
setWithFake(true);
}
}, [
accessKeyIdValue,
chosenAwsConnectionId,
connectionOptions,
isDefaultCredentialsChain,
secretAcessKeyValue,
]);
return (
<Provider value={{ ...value, connectionOptions, withFake }}>
{children}
</Provider>
);
}
const useAwsConnectionsContext = () => useContext(AwsConnectionsContext);
export { AwsConnectionsContextProvider, useAwsConnectionsContext };
| 22,087
|
https://github.com/JiangJibo/pinpoint/blob/master/web/src/main/angular/src/app/core/components/chart-layout/index.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
pinpoint
|
JiangJibo
|
TypeScript
|
Code
| 68
| 203
|
import { NgModule } from '@angular/core';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { MatGridListModule } from '@angular/material/grid-list';
import { SharedModule } from 'app/shared';
import { ChartLayoutContainerComponent } from './chart-layout-container.component';
import { ChartLayoutComponent } from './chart-layout.component';
import { ChartLayoutDataService } from './chart-layout-data.service';
@NgModule({
imports: [
SharedModule,
MatGridListModule,
DragDropModule
],
exports: [
ChartLayoutContainerComponent
],
declarations: [
ChartLayoutContainerComponent,
ChartLayoutComponent
],
providers: [
ChartLayoutDataService
],
})
export class ChartLayoutModule { }
| 36,449
|
https://github.com/sanic-org/sanic/blob/master/tests/test_json_encoding.py
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
sanic
|
sanic-org
|
Python
|
Code
| 245
| 845
|
import sys
from dataclasses import asdict, dataclass
from functools import partial
from json import dumps as sdumps
from string import ascii_lowercase
from typing import Dict
import pytest
try:
import ujson
from ujson import dumps as udumps
ujson_version = tuple(
map(int, ujson.__version__.strip(ascii_lowercase).split("."))
)
NO_UJSON = False
DEFAULT_DUMPS = udumps
except ModuleNotFoundError:
NO_UJSON = True
DEFAULT_DUMPS = partial(sdumps, separators=(",", ":"))
ujson_version = None
from sanic import Sanic
from sanic.response import BaseHTTPResponse, json
@dataclass
class Foo:
bar: str
def __json__(self):
return udumps(asdict(self))
@pytest.fixture
def foo():
return Foo(bar="bar")
@pytest.fixture
def payload(foo: Foo):
return {"foo": foo}
@pytest.fixture(autouse=True)
def default_back_to_ujson():
yield
BaseHTTPResponse._dumps = DEFAULT_DUMPS
def test_change_encoder():
Sanic("Test", dumps=sdumps)
assert BaseHTTPResponse._dumps == sdumps
def test_change_encoder_to_some_custom():
def my_custom_encoder():
return "foo"
Sanic("Test", dumps=my_custom_encoder)
assert BaseHTTPResponse._dumps == my_custom_encoder
@pytest.mark.skipif(NO_UJSON is True, reason="ujson not installed")
def test_json_response_ujson(payload: Dict[str, Foo]):
"""ujson will look at __json__"""
response = json(payload)
assert response.body == b'{"foo":{"bar":"bar"}}'
with pytest.raises(
TypeError, match="Object of type Foo is not JSON serializable"
):
json(payload, dumps=sdumps)
Sanic("Test", dumps=sdumps)
with pytest.raises(
TypeError, match="Object of type Foo is not JSON serializable"
):
json(payload)
@pytest.mark.skipif(
NO_UJSON is True or ujson_version >= (5, 4, 0),
reason=(
"ujson not installed or version is 5.4.0 or newer, "
"which can handle arbitrary size integers"
),
)
def test_json_response_json():
"""One of the easiest ways to tell the difference is that ujson cannot
serialize over 64 bits"""
too_big_for_ujson = 111111111111111111111
with pytest.raises(OverflowError, match="int too big to convert"):
json(too_big_for_ujson)
response = json(too_big_for_ujson, dumps=sdumps)
assert sys.getsizeof(response.body) == 54
Sanic("Test", dumps=sdumps)
response = json(too_big_for_ujson)
assert sys.getsizeof(response.body) == 54
| 44,425
|
https://github.com/meharajM/mpp-v1/blob/master/server/routes/login.js
|
Github Open Source
|
Open Source
|
MIT
| null |
mpp-v1
|
meharajM
|
JavaScript
|
Code
| 28
| 77
|
const express = require('express');
const router = express.Router();
const { loginUser, getuser, updateuser } = require('../controllers/login.js');
router.post('/login', function(req, res, next) {
loginUser(req, res, next);
});
module.exports = router;
| 25,310
|
https://github.com/kykrueger/openbis/blob/master/obis/src/vagrant/initialize/stop_services.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
openbis
|
kykrueger
|
Shell
|
Code
| 9
| 33
|
#!/bin/env bash
# Stop openbis
sudo -u openbis /home/openbis/bin/alldown.sh
| 23,964
|
https://github.com/LLNL/FPChecker/blob/master/tests/llvm/dynamic/get_cuda_lib_path.sh
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,022
|
FPChecker
|
LLNL
|
Shell
|
Code
| 44
| 224
|
#!/bin/bash
NVCC_PATH=$(which nvcc)
CUDA_PATH=$(dirname ${NVCC_PATH})
CUDA_PATH=$(dirname ${CUDA_PATH})
#echo "${CUDA_PATH}"
CUDA_LIB_PATH="${CUDA_PATH}/lib"
CUDA_LIB64_PATH="${CUDA_PATH}/lib64"
if [ -d ${CUDA_LIB_PATH} ]; then
lib_path="${CUDA_LIB_PATH}/libcudart.so"
if [ -f "$lib_path" ]; then
echo "${CUDA_LIB_PATH}"
fi
elif [ -d ${CUDA_LIB64_PATH} ]; then
lib_path="${CUDA_LIB64_PATH}/libcudart.so"
if [ -f "$lib_path" ]; then
echo "${CUDA_LIB64_PATH}"
fi
fi
| 22,194
|
https://github.com/bouzuya/purescript-bouzuya-command-line-option-parser/blob/master/src/Bouzuya/CommandLineOption/RecordToArray.purs
|
Github Open Source
|
Open Source
|
MIT
| null |
purescript-bouzuya-command-line-option-parser
|
bouzuya
|
PureScript
|
Code
| 219
| 414
|
module Bouzuya.CommandLineOption.RecordToArray
( class ArrayBuilder
, class ToElement
, build
, toArray
, toElement
) where
import Data.Array as Array
import Data.Symbol (SProxy(..), reflectSymbol)
import Data.Symbol as Symbol
import Prim.Row as Row
import Prim.RowList (class RowToList, Cons, Nil, kind RowList)
import Record as Record
import Type.Data.RowList (RLProxy(..))
class ArrayBuilder (list :: RowList) (from :: # Type) (to :: # Type) (ty :: Type)
| list -> from to where
build :: RLProxy list -> Record to -> Array ty -> Array ty
instance arrayBuilderCons ::
( ArrayBuilder t from from' ty'
, Row.Cons l ty from' to
, Row.Lacks l from'
, Symbol.IsSymbol l
, ToElement ty ty'
) => ArrayBuilder (Cons l ty t) from to ty' where
build _ o a =
build t (Record.delete l o) (Array.snoc a (toElement k v))
where
l = SProxy :: SProxy l
k = reflectSymbol l
v = Record.get l o
t = RLProxy :: RLProxy t
instance arrayBuilderNil :: ArrayBuilder Nil () () ty' where
build _ _ a = a
class ToElement a b where
toElement :: String -> a -> b
toArray ::
forall rows list ty
. RowToList rows list
=> ArrayBuilder list () rows ty
=> Record rows
-> Array ty
toArray obj = build list obj []
where
list = RLProxy :: RLProxy list
| 19,315
|
https://github.com/myckhel/chat-system-example/blob/master/resources/js/icons/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
chat-system-example
|
myckhel
|
JavaScript
|
Code
| 68
| 215
|
import HomeIcon from "./home.svg";
import SearchIcon from "./search.svg";
import MenuIcon from "./menu.svg";
import DropdownIcon from "./dropdown.svg";
import OutlineLogoutIcon from "./outlineLogout.svg";
import MenuDotX from "./menu-dot-x.svg";
import Send from "./send.svg";
import Sent from "./sent.svg";
import DoubleCheck from "./double-check.svg";
import Attachment from "./attachment.svg";
import Mic from "./mic.svg";
import Camera from "./camera.svg";
import Smiley from "./smiley.svg";
export {
HomeIcon,
SearchIcon,
MenuIcon,
DropdownIcon,
OutlineLogoutIcon,
MenuDotX,
Send,
Sent,
DoubleCheck,
Attachment,
Mic,
Camera,
Smiley,
};
| 44,579
|
https://github.com/hummel/gadfly/blob/master/gadfly/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
gadfly
|
hummel
|
Python
|
Code
| 42
| 67
|
"""
This package contains tools for reading and analyzing hdf5 snapshot files
from a modified version of the SPH code Gadget2.
"""
import units
import coordinates
import hdf5
import nbody
import sph
import snapshot
import visualize
import analyze
from sim import *
| 32,594
|
https://github.com/ledlogic/hostile-rpg-char/blob/master/js/st/st-weapons.js
|
Github Open Source
|
Open Source
|
MIT
| null |
hostile-rpg-char
|
ledlogic
|
JavaScript
|
Code
| 63
| 239
|
/* st-weapons.js */
st.weapons = {
init: function() {
st.log("init weapons");
st.weapons.request();
},
request: function(uri) {
st.log("requesting weapons from csv, uri[" + uri + "]");
Papa.parse("csv/st-weapons.csv", {
delimiter: ",",
download: true,
header: true,
complete: function(d) {
st.weapons.response(d);
},
encoding: "UTF-8"
});
},
response: function(d) {
st.log("weapons response");
var fields = d.meta.fields;
var data = d.data;
st.weapons.fields = fields;
st.weapons.data = data;
}
};
| 18,167
|
https://github.com/Dowsley/SteelStats/blob/master/frontend/dashboard/src/components/graficos/GraficoTipoPerda.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
SteelStats
|
Dowsley
|
Vue
|
Code
| 163
| 833
|
<template>
<v-card
rounded
color="#fbfbfb"
:loading="loading"
>
<v-card-actions>
<v-col cols="12">
<v-row
align="start"
justify="space-around"
>
<v-btn
icon
color="#3a3c53"
@click="refresh()"
>
<v-icon>mdi-refresh</v-icon>
</v-btn>
</v-row>
</v-col>
</v-card-actions>
<DxSankey
id="sankey"
:data-source="data"
source-field="source"
target-field="target"
weight-field="weight"
title="Representação das Perdas de ACIARIA"
>
<DxTooltip
:enabled="true"
:customize-link-tooltip="customizeLinkTooltip"
/>
<DxNode
:width="8"
:padding="30"
/>
<DxLink color-mode="gradient"/>
</DxSankey>
</v-card>
</template>
<script>
// DOC: https://js.devexpress.com/Demos/WidgetsGallery/Demo/Charts/SankeyChart/Vue/GreenMist/
const staticData = [
];
import DxSankey, {
DxTooltip,
DxNode,
DxLink
} from 'devextreme-vue/sankey';
import TipoPerdaService from '@/service/TipoPerdaService';
export default {
components: {
DxSankey,
DxTooltip,
DxNode,
DxLink
},
data() {
return {
data: staticData,
loading: false
};
},
methods: {
customizeLinkTooltip(info) {
return {
html: `<b>From:</b> ${info.source}<br/><b>To:</b> ${info.target}<br/><b>Weight:</b> ${info.weight}`
};
},
refresh() {
this.loading = '#ffb900';
TipoPerdaService.retrieveTipoPerda(
null,
null,
null
).then(response => {
console.log(response.data);
let data = [];
for (let i of Object.entries(response.data)) {
data.push(
{
source: 'Total',
weight: i[1]['segmento'],
target: i[1]['tipo']
}
);
}
console.log(data);
this.data = data;
this.loading = false;
});
}
},
mounted () {
this.refresh();
}
};
</script>
<style>
#sankey {
width: 430px;
height: 370px;
}
</style>
| 17,544
|
https://github.com/singyichen/crud-app/blob/master/src/features/todo/todo.controller.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
crud-app
|
singyichen
|
TypeScript
|
Code
| 27
| 80
|
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from '../../guards/auth.guard';
@Controller('todos')
@UseGuards(AuthGuard)
export class TodoController {
@Get()
getAll() {
return [];
}
}
| 30,787
|
https://github.com/pradeepcse504/MixedDrinkIterator/blob/master/src/mixeddrinkiterator/NoonIterator.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
MixedDrinkIterator
|
pradeepcse504
|
Java
|
Code
| 59
| 195
|
package mixeddrinkiterator;
import java.util.*;
public class NoonIterator implements Iterator{
List<MixedDrinkItem> mixedDrinkItems;
int position = 0;
public NoonIterator( List<MixedDrinkItem> mixedDrinkItems) {
this.mixedDrinkItems = mixedDrinkItems;
}
public boolean hasNext() {
if(position >= mixedDrinkItems.size() ) {
return false;
}
else {
return true;
}
}
public MixedDrinkItem next() {
MixedDrinkItem mixedDrinkItem = mixedDrinkItems.get(position);
position = position + 1;
return mixedDrinkItem;
}
}
| 49,601
|
https://github.com/masakih/KCD/blob/master/KCDTests/CombinedBattleTest.swift
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
KCD
|
masakih
|
Swift
|
Code
| 824
| 2,994
|
//
// CombinedBattleTest.swift
// KCDTests
//
// Created by Hori,Masaki on 2017/11/27.
// Copyright © 2017年 Hori,Masaki. All rights reserved.
//
import XCTest
@testable import KCD
import SwiftyJSON
import Doutaku
class CombinedBattleTest: XCTestCase {
var savedShips: [Ship] = []
var shipsHp: [Int] = []
var shipEquipments: [NSOrderedSet] = []
var shipExSlot: [Int] = []
func initBattleFleet() {
savedShips = []
shipsHp = []
shipEquipments = []
shipExSlot = []
// 艦隊を設定
do {
let store = ServerDataStore.oneTimeEditor()
guard let deck1 = store.deck(by: 1) else {
XCTFail("Can not get Deck.")
return
}
(0...5).forEach { deck1.setShip(id: $0 + 1, for: $0) }
deck1.setShip(id: 0, for: 6)
guard let deck2 = store.deck(by: 2) else {
XCTFail("Can not get Deck.")
return
}
(0...5).forEach { deck2.setShip(id: $0 + 1 + 6, for: $0) }
deck2.setShip(id: 0, for: 6)
store.ships(byDeckId: 1).forEach {
$0.nowhp = $0.maxhp
savedShips += [$0]
shipsHp += [$0.nowhp]
shipEquipments += [$0.equippedItem]
shipExSlot += [$0.slot_ex]
}
store.ships(byDeckId: 2).forEach {
$0.nowhp = $0.maxhp
savedShips += [$0]
shipsHp += [$0.nowhp]
shipEquipments += [$0.equippedItem]
shipExSlot += [$0.slot_ex]
}
XCTAssertEqual(shipsHp.count, 12)
}
// 出撃艦隊を設定
do {
let rawValue: [String: Any] = [
"api_result": 1,
"api_data": [
"api_no": 1
]
]
guard let json = JSON(rawValue: rawValue) else {
XCTFail("json is nil")
return
}
XCTAssertNotNil(json["api_result"])
let paramValue: [String: String] = [
"api_deck_id": "1",
"api_maparea_id": "1",
"api_mapinfo_no": "1"
]
let param = Parameter(paramValue)
let api = APIResponse(api: API(endpointPath: Endpoint.start.rawValue), parameter: param, json: json)
XCTAssertEqual(api.json, json)
XCTAssertEqual(api.parameter, param)
let command = MapStartCommand(apiResponse: api)
command.execute()
}
// battleの生成確認
do {
let store = TemporaryDataStore.default
let battle = store.battle()
XCTAssertNotNil(battle)
XCTAssertEqual(battle?.deckId, 1)
}
}
func clear() {
do {
ResetSortie().reset()
}
do {
let store = ServerDataStore.oneTimeEditor()
let ships1 = store.ships(byDeckId: 1)
zip(ships1, shipsHp).forEach { $0.nowhp = $1 }
zip(ships1, shipEquipments).forEach { $0.equippedItem = $1 }
zip(ships1, shipExSlot).forEach { $0.slot_ex = $1 }
guard let deck1 = store.deck(by: 1) else {
XCTFail("Can not get Deck.")
return
}
savedShips.enumerated().forEach { deck1.setShip(id: $0.element.id, for: $0.offset) }
let ships2 = store.ships(byDeckId: 1)
zip(ships2, shipsHp[6...]).forEach { $0.nowhp = $1 }
zip(ships2, shipEquipments[6...]).forEach { $0.equippedItem = $1 }
zip(ships2, shipExSlot[6...]).forEach { $0.slot_ex = $1 }
guard let deck2 = store.deck(by: 2) else {
XCTFail("Can not get Deck.")
return
}
savedShips.enumerated().forEach { deck2.setShip(id: $0.element.id, for: $0.offset) }
}
do {
let store = TemporaryDataStore.default
let battle = store.battle()
XCTAssertNil(battle)
}
}
func normalBattle() {
// 戦闘(昼戦)
do {
let rawValue: [String: Any] = [
"api_result": 1,
"api_data": [
"api_kouku": [
"api_stage3": [
"api_fdam": [
1, 0, 0, 0, 0, 0 // 1番艦
]
],
"api_stage3_combined": [
"api_fdam": [
2, 0, 0, 0, 0, 0 // 第二1番艦
]
]
],
"api_opening_atack": [
"api_fdam": [
0, 2, 0, 0, 0, 0, // 2番艦
0, 2, 0, 0, 0, 0 // 第二2番艦
]
],
"api_hougeki1": [
"api_df_list": [
[2, 2], // 3番艦
[7, 7],
[8, 8] // 第二3番艦
],
"api_damage": [
[0, 3],
[10, 10],
[0, 2]
],
"api_at_eflag": [
1,
0,
1
]
],
"api_hougeki2": [
"api_df_list": [
[3, 3], // 4番艦
[7, 7],
[9, 9] // 第二4番艦
],
"api_damage": [
[0, 4],
[10, 10],
[0, 3]
],
"api_at_eflag": [
1,
0,
1
]
],
"api_hougeki3": [
"api_df_list": [
[4, 4], // 5番艦
[7, 7],
[10, 10] // 第二5番艦
],
"api_damage": [
[0, 5],
[10, 10],
[0, 4]
],
"api_at_eflag": [
1,
0,
1
]
],
"api_raigeki": [
"api_fdam": [
0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1
]
]
]
]
guard let json = JSON(rawValue: rawValue) else {
XCTFail("json is nil")
return
}
let param = Parameter(["Test": "Test"])
let api = APIResponse(api: API(endpointPath: Endpoint.combinedBattle.rawValue), parameter: param, json: json)
let command = BattleCommand(apiResponse: api)
command.execute()
}
do {
let store = TemporaryDataStore.default
let damages = store.damages()
XCTAssertEqual(damages.count, 12)
}
}
func midnightBattle() {
// 戦闘(夜戦)
do {
let rawValue: [String: Any] = [
"api_result": 1,
"api_data": [
"api_hougeki": [
"api_df_list": [
[4], // 5番艦
[5] // 6番艦
],
"api_damage": [
[5],
[7]
],
"api_at_eflag": [
1,
1
]
]
]
]
guard let json = JSON(rawValue: rawValue) else {
XCTFail("json is nil")
return
}
let param = Parameter(["Test": "Test"])
let api = APIResponse(api: API(endpointPath: Endpoint.combinedMidnightBattle.rawValue), parameter: param, json: json)
let command = BattleCommand(apiResponse: api)
command.execute()
}
// 艦娘HP更新
do {
let rawValue: [String: Any] = [
"api_result": 1
]
guard let json = JSON(rawValue: rawValue) else {
XCTFail("json is nil")
return
}
let param = Parameter(["Test": "Test"])
let api = APIResponse(api: API(endpointPath: Endpoint.combinedBattleResult.rawValue), parameter: param, json: json)
let command = BattleCommand(apiResponse: api)
command.execute()
}
}
func checkHP() {
// HPチェック
do {
let store = ServerDataStore.oneTimeEditor()
let ships1 = store.ships(byDeckId: 1)
XCTAssertEqual(ships1.count, 6)
XCTAssertEqual(ships1[0].nowhp, shipsHp[0] - 1)
XCTAssertEqual(ships1[1].nowhp, shipsHp[1] - 2)
XCTAssertEqual(ships1[2].nowhp, shipsHp[2] - 3)
XCTAssertEqual(ships1[3].nowhp, shipsHp[3] - 4)
XCTAssertEqual(ships1[4].nowhp, shipsHp[4] - 10)
XCTAssertEqual(ships1[5].nowhp, shipsHp[5] - 7)
let ships2 = store.ships(byDeckId: 2)
XCTAssertEqual(ships2.count, 6)
XCTAssertEqual(ships2[0].nowhp, shipsHp[6] - 2)
XCTAssertEqual(ships2[1].nowhp, shipsHp[7] - 3)
XCTAssertEqual(ships2[2].nowhp, shipsHp[8] - 3)
XCTAssertEqual(ships2[3].nowhp, shipsHp[9] - 4)
XCTAssertEqual(ships2[4].nowhp, shipsHp[10] - 5)
XCTAssertEqual(ships2[5].nowhp, shipsHp[11] - 1)
}
}
func testCombined() {
initBattleFleet()
normalBattle()
midnightBattle()
checkHP()
clear()
}
}
| 46,598
|
https://github.com/OkunaOrg/openbook-app/blob/master/lib/pages/home/pages/profile/widgets/profile_card/widgets/profile_bio.dart
|
Github Open Source
|
Open Source
|
BSD-3-Clause, MIT
| 2,019
|
openbook-app
|
OkunaOrg
|
Dart
|
Code
| 76
| 278
|
import 'package:Okuna/models/user.dart';
import 'package:Okuna/widgets/theming/actionable_smart_text.dart';
import 'package:flutter/material.dart';
class OBProfileBio extends StatelessWidget {
final User user;
const OBProfileBio(this.user);
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: user.updateSubject,
initialData: user,
builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
var user = snapshot.data;
var bio = user?.getProfileBio();
if (bio == null) return const SizedBox();
return Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Flexible(
child: OBActionableSmartText(
text: bio,
size: OBTextSize.mediumSecondary,
),
)
],
),
);
},
);
}
}
| 5,892
|
https://github.com/SKT-T1-Keyoubi/NeteaseLottery/blob/master/网易彩票/Class/Setting/Model/CPHtmlPage.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
NeteaseLottery
|
SKT-T1-Keyoubi
|
Objective-C
|
Code
| 45
| 146
|
//
// CPHtmlPage.h
// 网易彩票
//
// Created by LoveQiuYi on 16/1/17.
// Copyright © 2016年 LoveQiuYi. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CPHtmlPage : NSObject
@property (nonatomic,copy) NSString * title;
@property (nonatomic,copy) NSString * html;
@property (nonatomic,copy) NSString * htmlId;
+(id)htmlPageWithDic:(NSDictionary *)dic;
@end
| 25,181
|
https://github.com/io7m/coreland-plexlog-ada/blob/master/UNIT_TESTS/t_space.adb
|
Github Open Source
|
Open Source
|
ISC
| 2,010
|
coreland-plexlog-ada
|
io7m
|
Ada
|
Code
| 121
| 397
|
with Plexlog.API;
with test;
procedure t_space is
begin
declare
Space : constant Plexlog.API.Long_Positive := Plexlog.API.Space_Requirement
(Max_Files => 1, Max_Size => 1024);
begin
test.assert
(check => Space = 2048,
pass_message => "Space = " & Plexlog.API.Long_Positive'Image (Space),
fail_message => "Space = " & Plexlog.API.Long_Positive'Image (Space));
end;
declare
Space : constant Plexlog.API.Long_Positive := Plexlog.API.Space_Requirement
(Max_Files => 10, Max_Size => 1024);
begin
test.assert
(check => Space = 11264,
pass_message => "Space = " & Plexlog.API.Long_Positive'Image (Space),
fail_message => "Space = " & Plexlog.API.Long_Positive'Image (Space));
end;
declare
Space : constant Plexlog.API.Long_Positive := Plexlog.API.Space_Requirement
(Max_Files => 100, Max_Size => 10240);
begin
test.assert
(check => Space = 1034240,
pass_message => "Space = " & Plexlog.API.Long_Positive'Image (Space),
fail_message => "Space = " & Plexlog.API.Long_Positive'Image (Space));
end;
end t_space;
| 45,832
|
https://github.com/jboullion/The-Gathering-Place/blob/master/wp-content/plugins/admin-columns-pro/classes/Editing/classes/Model/Post/Status.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
The-Gathering-Place
|
jboullion
|
PHP
|
Code
| 127
| 397
|
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class ACP_Editing_Model_Post_Status extends ACP_Editing_Model {
public function get_view_settings() {
$post_type_object = get_post_type_object( $this->column->get_post_type() );
if ( ! $post_type_object || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
return false;
}
$stati = $this->get_editable_statuses();
if ( ! $stati ) {
return false;
}
$options = array();
foreach ( $stati as $name => $status ) {
if ( in_array( $name, array( 'future', 'trash' ) ) ) {
continue;
}
$options[ $name ] = $status->label;
}
return array(
'type' => 'select',
'options' => $options,
);
}
private function get_editable_statuses() {
return apply_filters( 'acp/editing/post_statuses', get_post_stati( array( 'internal' => 0 ), 'objects' ), $this->column );
}
public function save( $id, $value ) {
$this->strategy->update( $id, array( 'post_status' => $value ) );
}
}
| 35,655
|
https://github.com/dustContributor/lwjgl3/blob/master/modules/lwjgl/sse/src/generated/c/org_lwjgl_util_simd_SSE3.c
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
lwjgl3
|
dustContributor
|
C
|
Code
| 69
| 458
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
#include "common_tools.h"
#include "intrinsics.h"
EXTERN_C_ENTER
JNIEXPORT void JNICALL JavaCritical_org_lwjgl_util_simd_SSE3__1MM_1SET_1DENORMALS_1ZERO_1MODE(jint mode) {
_MM_SET_DENORMALS_ZERO_MODE((unsigned int)mode);
}
JNIEXPORT void JNICALL Java_org_lwjgl_util_simd_SSE3__1MM_1SET_1DENORMALS_1ZERO_1MODE(JNIEnv *__env, jclass clazz, jint mode) {
UNUSED_PARAMS(__env, clazz)
JavaCritical_org_lwjgl_util_simd_SSE3__1MM_1SET_1DENORMALS_1ZERO_1MODE(mode);
}
JNIEXPORT jint JNICALL JavaCritical_org_lwjgl_util_simd_SSE3__1MM_1GET_1DENORMALS_1ZERO_1MODE(void) {
return (jint)_MM_GET_DENORMALS_ZERO_MODE();
}
JNIEXPORT jint JNICALL Java_org_lwjgl_util_simd_SSE3__1MM_1GET_1DENORMALS_1ZERO_1MODE(JNIEnv *__env, jclass clazz) {
UNUSED_PARAMS(__env, clazz)
return JavaCritical_org_lwjgl_util_simd_SSE3__1MM_1GET_1DENORMALS_1ZERO_1MODE();
}
EXTERN_C_EXIT
| 41,748
|
https://github.com/wesamjibreen/dashboard/blob/master/src/components/partials/widgets/stat/SocialStatWidget.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
dashboard
|
wesamjibreen
|
Vue
|
Code
| 67
| 291
|
<script setup lang="ts">
const props = defineProps<{
icon: string
value: string
straight?: boolean
squared?: boolean
colored?: boolean
}>()
</script>
<template>
<div
class="stat-widget followers-stat-widget-v1"
:class="[props.straight && 'is-straight']"
>
<div class="follow-block">
<div
class="follow-icon"
:class="[props.squared && 'is-squared', props.colored && 'is-primary']"
>
<i aria-hidden="true" :class="props.icon"></i>
</div>
<div class="follow-count">
<span class="dark-inverted">{{ props.value }} Followers</span>
<span>Based on your latest stats</span>
</div>
<a href="#" class="go-icon">
<i
aria-hidden="true"
class="iconify"
data-icon="feather:chevron-right"
></i>
</a>
</div>
</div>
</template>
| 42,299
|
https://github.com/iammerrick/StyleManager/blob/master/src/StyleManager.js
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
StyleManager
|
iammerrick
|
JavaScript
|
Code
| 107
| 400
|
//= helpers.js
//= renderers/AbstractRenderer.js
//= renderers/Renderer.js
//= renderers/IERenderer.js
var StyleManager = function(name) {
this.setRenderer(name);
this.stylesheets = {};
this.changed = [];
};
StyleManager.prototype.setRenderer = function(name) {
if (document.createStyleSheet) {
this.renderer = new IERenderer();
} else {
this.renderer = new Renderer();
}
this.renderer.name(name);
};
StyleManager.prototype.register = function(key, source) {
var previous = false;
source = fragment(key, source);
this.changed.push(key);
if (this.stylesheets[key]) {
previous = this.stylesheets[key];
}
this.stylesheets[key] = {
source: source,
node: document.createTextNode(source)
};
this.stylesheets[key].previous = previous;
this.render();
return this;
};
StyleManager.prototype.name = function(name) {
return this.renderer.name(name);
};
StyleManager.prototype.clean = function() {
this.renderer.clean();
};
StyleManager.prototype.render = function() {
this.renderer.render(this.stylesheets, this.changed);
return this;
};
StyleManager.prototype.getRenderer = function() {
return this.renderer;
};
| 28,909
|
https://github.com/LokiMidgard/Fluent.Net/blob/master/Fluent.Net.Test/LangNeg/NegotiateTest.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
Fluent.Net
|
LokiMidgard
|
C#
|
Code
| 1,276
| 4,557
|
using Fluent.Net.Plural;
using FluentAssertions;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
using Fluent.Net.LangNeg;
namespace Fluent.Net.Test.LangNeg
{
public class NegotiateTest
{
public class NegotiateTestCase
{
public string Name { get; set; }
public string Description { get; set; }
public string Group { get; set; }
public string[] RequestedLocales { get; set; }
public string[] AvailableLocales { get; set; }
public Strategy Strategy { get; set; }
public string DefaultLocale { get; set; }
public string[] Expected { get; set; }
public override string ToString()
{
return Description;
}
}
static string[] Strings(params string[] strings)
{
return strings;
}
// because of course, nobody would find typedef
// in c# useful, it's so old world and not modern or anything
static public Dictionary<Strategy, Dictionary<string, NegotiateTestCase[]>> TestData =
new Dictionary<Strategy, Dictionary<string, NegotiateTestCase[]>>()
{
{
Strategy.Filtering,
new Dictionary<string, NegotiateTestCase[]>()
{
{
"exact match",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("en"),
AvailableLocales = Strings("en"),
Expected = Strings("en")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-US"),
AvailableLocales = Strings("en-US"),
Expected = Strings("en-US")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-Latn-US"),
AvailableLocales = Strings("en-Latn-US"),
Expected = Strings("en-Latn-US")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-Latn-US-mac"),
AvailableLocales = Strings("en-Latn-US-mac"),
Expected = Strings("en-Latn-US-mac")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr-FR"),
AvailableLocales = Strings("de", "it", "fr-FR"),
Expected = Strings("fr-FR")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr", "pl", "de-DE"),
AvailableLocales = Strings("pl", "en-US", "de-DE"),
Expected = Strings("pl", "de-DE")
}
}
},
{
"available as range",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("en-US"),
AvailableLocales = Strings("en"),
Expected = Strings("en")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-Latn-US"),
AvailableLocales = Strings("en-US"),
Expected = Strings("en-US")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-US-mac"),
AvailableLocales = Strings("en-US"),
Expected = Strings("en-US"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr-CA", "de-DE"),
AvailableLocales = Strings("fr", "it", "de"),
Expected = Strings("fr", "de"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("ja-JP-mac"),
AvailableLocales = Strings("ja"),
Expected = Strings("ja")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-Latn-GB", "en-Latn-IN"),
AvailableLocales = Strings("en-IN", "en-GB"),
Expected = Strings("en-GB", "en-IN")
}
}
},
{
"should match on likely subtag",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("en"),
AvailableLocales = Strings("en-GB", "de", "en-US"),
Expected = Strings("en-US", "en-GB")
},
new NegotiateTestCase()
{
Name = "en (2)",
RequestedLocales = Strings("en"),
AvailableLocales = Strings("en-Latn-GB", "de", "en-Latn-US"),
Expected = Strings("en-Latn-US", "en-Latn-GB")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr"),
AvailableLocales = Strings("fr-CA", "fr-FR"),
Expected = Strings("fr-FR", "fr-CA"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("az-IR"),
AvailableLocales = Strings("az-Latn", "az-Arab"),
Expected = Strings("az-Arab")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("sr-RU"),
AvailableLocales = Strings("sr-Cyrl", "sr-Latn"),
Expected = Strings("sr-Latn"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("sr"),
AvailableLocales = Strings("sr-Latn", "sr-Cyrl"),
Expected = Strings("sr-Cyrl"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("zh-GB"),
AvailableLocales = Strings("zh-Hans", "zh-Hant"),
Expected = Strings("zh-Hant"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("sr", "ru"),
AvailableLocales = Strings("sr-Latn", "ru"),
Expected = Strings("ru"),
},
new NegotiateTestCase()
{
Name = "sr-RU (2)",
RequestedLocales = Strings("sr-RU"),
AvailableLocales = Strings("sr-Latn-RO", "sr-Cyrl"),
Expected = Strings("sr-Latn-RO"),
},
}
},
{
"should match on a requested locale as a range",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("en-*-US"),
AvailableLocales = Strings("en-US"),
Expected = Strings("en-US"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-Latn-US-*"),
AvailableLocales = Strings("en-Latn-US"),
Expected = Strings("en-Latn-US"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-*-US-*"),
AvailableLocales = Strings("en-US"),
Expected = Strings("en-US"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("*"),
AvailableLocales = Strings("de", "pl", "it", "fr", "ru"),
Expected = Strings("de", "pl", "it", "fr", "ru")
}
}
},
{
"should match cross-region",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("en"),
AvailableLocales = Strings("en-US"),
Expected = Strings("en-US"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-US"),
AvailableLocales = Strings("en-GB"),
Expected = Strings("en-GB"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("en-Latn-US"),
AvailableLocales = Strings("en-Latn-GB"),
Expected = Strings("en-Latn-GB"),
},
new NegotiateTestCase()
{
// This is a cross-region check, because the requested Locale
// is really lang: en, script: *, region: undefined
Name = "en-* cross-region check",
RequestedLocales = Strings("en-*"),
AvailableLocales = Strings("en-US"),
Expected = Strings("en-US"),
}
}
},
{
"should match cross-variant",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("en-US-mac"),
AvailableLocales = Strings("en-US-win"),
Expected = Strings("en-US-win"),
}
}
},
{
"should prioritize properly",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
// exact match first
Name = "en-US exact match first",
RequestedLocales = Strings("en-US"),
AvailableLocales = Strings("en-US-mac", "en", "en-US"),
Expected = Strings("en-US", "en", "en-US-mac"),
},
new NegotiateTestCase()
{
// available as range second
Name = "en-Latn-US available as range second",
RequestedLocales = Strings("en-Latn-US"),
AvailableLocales = Strings("en-GB", "en-US"),
Expected = Strings("en-US", "en-GB"),
},
new NegotiateTestCase()
{
// likely subtags third
Name = "en likely subtags third",
RequestedLocales = Strings("en"),
AvailableLocales = Strings("en-Cyrl-US", "en-Latn-US"),
Expected = Strings("en-Latn-US"),
},
new NegotiateTestCase()
{
// variant range fourth
Name = "en-US-mac variant range fourth",
RequestedLocales = Strings("en-US-mac"),
AvailableLocales = Strings("en-US-win", "en-GB-mac"),
Expected = Strings("en-US-win", "en-GB-mac"),
},
new NegotiateTestCase()
{
// regional range fifth
Name = "en-US-mac regional range fifth",
RequestedLocales = Strings("en-US-mac"),
AvailableLocales = Strings("en-GB-win"),
Expected = Strings("en-GB-win"),
},
}
},
{
"should prioritize properly (extra tests)",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("en-US"),
AvailableLocales = Strings("en-GB", "en"),
Expected = Strings("en", "en-GB"),
},
}
},
{
"should handle default locale properly",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("fr"),
AvailableLocales = Strings("de", "it"),
Expected = Strings()
},
new NegotiateTestCase()
{
Name = "fr (2)",
RequestedLocales = Strings("fr"),
AvailableLocales = Strings("de", "it"),
DefaultLocale = "en-US",
Expected = Strings("en-US")
},
new NegotiateTestCase()
{
Name = "fr (3)",
RequestedLocales = Strings("fr"),
AvailableLocales = Strings("de", "en-US"),
DefaultLocale = "en-US",
Expected = Strings("en-US")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr", "de-DE"),
AvailableLocales = Strings("de-DE", "fr-CA"),
DefaultLocale = "en-US",
Expected= Strings("fr-CA", "de-DE", "en-US")
}
}
},
{
"should handle all matches on the 1st higher than any on the 2nd",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("fr-CA-mac", "de-DE"),
AvailableLocales = Strings("de-DE", "fr-FR-win"),
Expected = Strings("fr-FR-win", "de-DE"),
}
}
},
{
"should handle cases and underscores",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("fr_FR"),
AvailableLocales = Strings("fr-FR"),
Expected = Strings("fr-FR"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr_fr"),
AvailableLocales = Strings("fr-fr"),
Expected = Strings("fr-fr"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr_Fr"),
AvailableLocales = Strings("fr-fR"),
Expected = Strings("fr-fR"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr_lAtN_fr"),
AvailableLocales = Strings("fr-Latn-FR"),
Expected = Strings("fr-Latn-FR"),
},
new NegotiateTestCase()
{
Name = "fr_FR (2)",
RequestedLocales = Strings("fr_FR"),
AvailableLocales = Strings("fr_FR"),
Expected = Strings("fr_FR"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr-FR"),
AvailableLocales = Strings("fr_FR"),
Expected = Strings("fr_FR"),
},
new NegotiateTestCase()
{
RequestedLocales = Strings("fr_Cyrl_FR_mac"),
AvailableLocales = Strings("fr_Cyrl_fr-mac"),
Expected = Strings("fr_Cyrl_fr-mac"),
}
}
},
{
"should not crash on invalid input",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
Name = "null requested locales",
RequestedLocales = null,
AvailableLocales = Strings("fr-FR"),
Expected = Strings()
},
new NegotiateTestCase()
{
Name = "null available locales",
RequestedLocales = Strings("fr-FR"),
AvailableLocales = null,
Expected = Strings()
},
new NegotiateTestCase()
{
Name = "rubbish locale names",
RequestedLocales = Strings("2"),
AvailableLocales = Strings("ąóżł"),
Expected = Strings()
},
}
}
}
},
{
Strategy.Matching,
new Dictionary<string, NegotiateTestCase[]>()
{
{
"should match only one per requested",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("fr", "en"),
AvailableLocales = Strings("en-US", "fr-FR", "en", "fr"),
Expected = Strings("fr", "en")
},
new NegotiateTestCase()
{
RequestedLocales = Strings("*"),
AvailableLocales = Strings("fr", "de", "it", "ru", "pl"),
Expected = Strings("fr")
}
}
},
}
},
{
Strategy.Lookup,
new Dictionary<string, NegotiateTestCase[]>()
{
{
"should match only one",
new NegotiateTestCase[]
{
new NegotiateTestCase()
{
RequestedLocales = Strings("fr-FR", "en"),
AvailableLocales = Strings("en-US", "fr-FR", "en", "fr"),
DefaultLocale = "en-US",
Expected = Strings("fr-FR")
}
}
}
}
}
};
public static IEnumerable<NegotiateTestCase> GetTestCases()
{
foreach (var strategy in TestData)
{
foreach (var group in strategy.Value)
{
foreach (var testCase in group.Value)
{
testCase.Strategy = strategy.Key;
testCase.Description = group.Key + " - " +
(String.IsNullOrEmpty(testCase.Name) ?
String.Join(",", testCase.RequestedLocales) :
testCase.Name);
yield return testCase;
}
}
}
}
[Test, TestCaseSource("GetTestCases")]
public void Test(NegotiateTestCase test)
{
var actual = Negotiate.NegotiateLanguages(test.RequestedLocales,
test.AvailableLocales, test.Strategy, test.DefaultLocale);
actual.Should().BeEquivalentTo(test.Expected,
options => options.WithStrictOrdering());
}
}
}
| 4,142
|
https://github.com/LaserSrl/KrakeAndroid/blob/master/trip/src/main/kotlin/com/krake/bus/viewmodel/BusStopsViewModel.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
KrakeAndroid
|
LaserSrl
|
Kotlin
|
Code
| 147
| 587
|
package com.krake.bus.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.krake.OtpDataRepository
import com.krake.bus.model.BusStop
import com.krake.bus.model.OtpStopTime
import com.krake.core.thread.AsyncTask
import com.krake.core.thread.async
import java.util.*
class BusStopsViewModel : ViewModel() {
private var busStopsTask: AsyncTask<List<BusStop>>? = null
private val mutableBusStops = MutableLiveData<List<BusStop>>()
val busStops: LiveData<List<BusStop>> = mutableBusStops
private var stopTimesTask: AsyncTask<List<OtpStopTime>>? = null
private val mutableStopTimes = MutableLiveData<List<OtpStopTime>>()
val stopTimes: LiveData<List<OtpStopTime>> = mutableStopTimes
private val mutableStatus = MutableLiveData<Status>()
val status: LiveData<Status> = mutableStatus
init {
mutableStatus.value = Idle
}
fun loadStopsByBusRoute(routeId: String) {
mutableStatus.value = Loading
busStopsTask = async {
OtpDataRepository.shared.loadStopsByBusRoute(routeId)
}.completed {
mutableBusStops.value = it.sortedBy { it.name }
mutableStatus.value = Idle
}.error {
mutableStatus.value = Error
}.build()
busStopsTask?.load()
}
fun loadBusTimesByDate(stop: BusStop, routeId: String, date: Date) {
mutableStatus.value = Loading
stopTimesTask = async {
OtpDataRepository.shared.loadBusTimesByDate(stop, routeId, date)
}.completed {
mutableStopTimes.value = it
mutableStatus.value = Idle
}.error {
mutableStatus.value = Error
}.build()
stopTimesTask?.load()
}
override fun onCleared() {
super.onCleared()
busStopsTask?.cancel()
stopTimesTask?.cancel()
}
}
| 23,355
|
https://github.com/jastkand/vk-notifications/blob/master/app/storages/PostsCountStorage.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
vk-notifications
|
jastkand
|
JavaScript
|
Code
| 69
| 205
|
export function getPostsCount() {
return new Promise((resolve) => {
chrome.storage.local.get({ posts_count: {} }, (items) => resolve(items.posts_count))
})
}
export async function resetTotalPostsCount() {
const postsCount = await getPostsCount()
postsCount['total'] = 0
return savePostsCount(postsCount)
}
export function resetPostsCount() {
return new Promise((resolve) => {
chrome.storage.local.remove('posts_count', () => {
resolve({})
})
})
}
export function savePostsCount(postsCount) {
return new Promise((resolve) => {
chrome.storage.local.set({ 'posts_count': postsCount }, () => resolve(postsCount))
})
}
| 1,072
|
https://github.com/hansenhahn/playton-2/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,023
|
playton-2
|
hansenhahn
|
Ignore List
|
Code
| 25
| 79
|
ROM Original/
ROM Modificada/
All Files/
Arquivos Gerados/
Ferramentas/
Programas/
Imagens Originais (Outros)/
Output/4215 - Professor Layton and Pandora's Box (EUR)(BAHAMUT).nds
Textos Traduzidos DELETAR/
Screenshots/
| 7,862
|
https://github.com/aquiladev/ddns-action/blob/master/node_modules/uns/contracts/IUNSRegistry.sol
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ddns-action
|
aquiladev
|
Solidity
|
Code
| 640
| 1,309
|
// @author Unstoppable Domains, Inc.
// @date June 16th, 2021
pragma solidity ^0.8.0;
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol';
import './IRecordStorage.sol';
interface IUNSRegistry is IERC721MetadataUpgradeable, IRecordStorage {
event NewURI(uint256 indexed tokenId, string uri);
event NewURIPrefix(string prefix);
/**
* @dev Function to set the token URI Prefix for all tokens.
* @param prefix string URI to assign
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
/**
* @dev Gets the resolver of the specified token ID.
* @param tokenId uint256 ID of the token to query the resolver of
* @return address currently marked as the resolver of the given token ID
*/
function resolverOf(uint256 tokenId) external view returns (address);
/**
* @dev Provides child token (subdomain) of provided tokenId.
* @param tokenId uint256 ID of the token
* @param label label of subdomain (for `aaa.bbb.crypto` it will be `aaa`)
*/
function childIdOf(uint256 tokenId, string calldata label) external pure returns (uint256);
/**
* @dev Existence of token.
* @param tokenId uint256 ID of the token
*/
function exists(uint256 tokenId) external view returns (bool);
/**
* @dev Transfer domain ownership without resetting domain records.
* @param to address of new domain owner
* @param tokenId uint256 ID of the token to be transferred
*/
function setOwner(address to, uint256 tokenId) external;
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) external;
/**
* @dev Mints token.
* @param to address to mint the new SLD to.
* @param tokenId id of token.
* @param uri domain URI.
*/
function mint(
address to,
uint256 tokenId,
string calldata uri
) external;
/**
* @dev Safely mints token.
* Implements a ERC721Reciever check unlike mint.
* @param to address to mint the new SLD to.
* @param tokenId id of token.
* @param uri domain URI.
*/
function safeMint(
address to,
uint256 tokenId,
string calldata uri
) external;
/**
* @dev Safely mints token.
* Implements a ERC721Reciever check unlike mint.
* @param to address to mint the new SLD to.
* @param tokenId id of token.
* @param uri domain URI.
* @param data bytes data to send along with a safe transfer check
*/
function safeMint(
address to,
uint256 tokenId,
string calldata uri,
bytes calldata data
) external;
/**
* @dev Mints token with records
* @param to address to mint the new SLD to
* @param tokenId id of token
* @param keys New record keys
* @param values New record values
* @param uri domain URI
*/
function mintWithRecords(
address to,
uint256 tokenId,
string calldata uri,
string[] calldata keys,
string[] calldata values
) external;
/**
* @dev Safely mints token with records
* @param to address to mint the new SLD to
* @param tokenId id of token
* @param keys New record keys
* @param values New record values
* @param uri domain URI
*/
function safeMintWithRecords(
address to,
uint256 tokenId,
string calldata uri,
string[] calldata keys,
string[] calldata values
) external;
/**
* @dev Safely mints token with records
* @param to address to mint the new SLD to
* @param tokenId id of token
* @param keys New record keys
* @param values New record values
* @param uri domain URI
* @param data bytes data to send along with a safe transfer check
*/
function safeMintWithRecords(
address to,
uint256 tokenId,
string calldata uri,
string[] calldata keys,
string[] calldata values,
bytes calldata data
) external;
}
| 3,497
|
https://github.com/hsiaoyi0504/SC3/blob/master/test/out/ERS1348818/results.tsv
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
SC3
|
hsiaoyi0504
|
TSV
|
Code
| 8
| 35
|
SRA Heterozygous SNPs Homozygous SNPs
ERR1630361 199474657,199474659, 121434453,
| 15,758
|
https://github.com/Matias-Sala/documents-management/blob/master/angular_document_management/.dart_tool/build/generated/angular_components/lib/mixins/has_tab_index.ddc.js
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
documents-management
|
Matias-Sala
|
JavaScript
|
Code
| 159
| 1,013
|
define(['dart_sdk', 'packages/quiver/strings', 'packages/angular_components/utils/angular/properties/properties'], function(dart_sdk, strings, properties) {
'use strict';
const core = dart_sdk.core;
const dart = dart_sdk.dart;
const dartx = dart_sdk.dartx;
const strings$ = strings.strings;
const utils__angular__properties__properties = properties.utils__angular__properties__properties;
const _root = Object.create(null);
const mixins__has_tab_index = Object.create(_root);
const _tabIndex = Symbol('_tabIndex');
const _computeTabIndex = Symbol('_computeTabIndex');
mixins__has_tab_index.HasTabIndex = class HasTabIndex extends core.Object {
updateTabIndex() {
this[_tabIndex] = this[_computeTabIndex]();
}
get tabIndex() {
let l = this[_tabIndex];
return l != null ? l : this[_computeTabIndex]();
}
[_computeTabIndex]() {
if (dart.test(this.disabled)) {
return "-1";
} else if (!dart.test(strings$.isBlank(this.hostTabIndex))) {
if (!(utils__angular__properties__properties.getInt(this.hostTabIndex) != null)) dart.assertFailed();
return this.hostTabIndex;
} else {
return "0";
}
}
};
(mixins__has_tab_index.HasTabIndex.new = function() {
this[_tabIndex] = null;
}).prototype = mixins__has_tab_index.HasTabIndex.prototype;
dart.addTypeTests(mixins__has_tab_index.HasTabIndex);
dart.setMethodSignature(mixins__has_tab_index.HasTabIndex, () => ({
__proto__: dart.getMethods(mixins__has_tab_index.HasTabIndex.__proto__),
updateTabIndex: dart.fnType(dart.void, []),
[_computeTabIndex]: dart.fnType(core.String, [])
}));
dart.setGetterSignature(mixins__has_tab_index.HasTabIndex, () => ({
__proto__: dart.getGetters(mixins__has_tab_index.HasTabIndex.__proto__),
tabIndex: core.String
}));
dart.setFieldSignature(mixins__has_tab_index.HasTabIndex, () => ({
__proto__: dart.getFields(mixins__has_tab_index.HasTabIndex.__proto__),
[_tabIndex]: dart.fieldType(core.String)
}));
dart.trackLibraries("packages/angular_components/mixins/has_tab_index.ddc", {
"package:angular_components/mixins/has_tab_index.dart": mixins__has_tab_index
}, '{"version":3,"sourceRoot":"","sources":["has_tab_index.dart"],"names":[],"mappings":";;;;;;;;;;;;;AAsBI,qBAAS,GAAG,sBAAgB;IAC9B;;cAGuB,eAAS;6BAAI,sBAAgB;IAAE;;AAGpD,oBAAI,aAAQ,GAAE;AACZ,cAAO;YACF,gBAAK,gBAAO,CAAC,iBAAY,IAAG;AACjC,cAAO,6CAAM,CAAC,iBAAY,KAAK;AAC/B,cAAO,kBAAY;aACd;AACL,cAAO;;IAEX;;;IAnBO,eAAS;EAoBlB","file":"has_tab_index.ddc.js"}');
// Exports:
return {
mixins__has_tab_index: mixins__has_tab_index
};
});
//# sourceMappingURL=has_tab_index.ddc.js.map
| 42,365
|
https://github.com/RevskyAndrey/frontend-course-2021/blob/master/homeworks/kostya.bublyk_ConstBagel/3-async/scripts/script.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
frontend-course-2021
|
RevskyAndrey
|
JavaScript
|
Code
| 222
| 720
|
const url = 'https://jsonplaceholder.typicode.com/posts';
/**
* get json data from response
*/
async function getArticles() {
const response = await fetch(url);
return response.json();
}
/**
* object with functions for sorting
*/
const orderBy = {
DEF: (arr) => [...arr],
ASC: (arr) => [...arr].sort((a, b) => a.title.localeCompare(b.title)),
DESC: (arr) => [...arr].sort((a, b) => b.title.localeCompare(a.title)),
};
/**
* storage for actual sorting and searching parameters.
*/
const stateStorage = {
order: '',
data: null,
};
/**
* Selectors:
*/
const selectOrderField = document.querySelector('[data-role="blog-select-order"]');
const searchInputField = document.querySelector('[data-role="blog-input-search"]');
const mainField = document.querySelector('[data-role="blog-main-section"]');
/** Set order values for option tags */
Object.keys(orderBy)
.forEach((orderName, index) => { selectOrderField.options[index].value = orderName; });
/**
* variables for keeping initial data from response and titles in lower case
*/
let initialData = null;
let titlesWithLowerCase = null;
/**
* Functions:
*/
function displayArticles(articles) {
mainField.innerHTML = articles.map((article) => `
<article class="blog-article">
<h2 class="blog-article-title">${article.title}</h2>
<p class="blog-article-text">${article.body}</p>
</article>
`).join('');
}
async function initApp() {
mainField.classList.add('loader');
initialData = await (new Promise((resolve) => setTimeout(() => {
mainField.classList.remove('loader');
resolve(getArticles());
}, 3000)));
titlesWithLowerCase = initialData.map((article) => article.title.toLowerCase());
stateStorage.order = selectOrderField.options[selectOrderField.selectedIndex].value;
stateStorage.data = [...initialData];
displayArticles(initialData);
}
/**
* Event listeners:
*/
selectOrderField.addEventListener('change', (event) => {
stateStorage.order = event.target.value;
displayArticles(orderBy[stateStorage.order](stateStorage.data));
});
searchInputField.addEventListener('input', (event) => {
const inputText = event.target.value.trim().toLowerCase();
stateStorage.data = initialData
.filter((_, index) => titlesWithLowerCase[index].includes(inputText));
displayArticles(orderBy[stateStorage.order](stateStorage.data));
});
/**
* launch app
*/
(async () => initApp())();
| 40,010
|
https://github.com/claranet/terraform-provider-ansiblevault/blob/master/pkg/provider/in_env_test.go
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
terraform-provider-ansiblevault
|
claranet
|
Go
|
Code
| 218
| 717
|
package provider
import (
"errors"
"fmt"
"path"
"testing"
"github.com/MeilleursAgents/terraform-provider-ansiblevault/v2/pkg/vault"
)
func TestInEnvRead(t *testing.T) {
var cases = []struct {
intention string
env string
key string
want string
wantErr error
}{
{
"simple",
"prod",
"API_KEY",
"PROD_KEEP_IT_SECRET",
nil,
},
{
"not found key",
"prod",
"SECRET_KEY",
"",
errors.New("SECRET_KEY not found in prod vault"),
},
{
"not found env",
"dev",
"SECRET_KEY",
"",
fmt.Errorf("open %s: no such file or directory", path.Join(ansibleFolder, "group_vars/tag_dev/vault.yml")),
},
}
for _, testCase := range cases {
t.Run(testCase.intention, func(t *testing.T) {
data := inEnvResource().Data(nil)
if err := data.Set("env", testCase.env); err != nil {
t.Errorf("unable to set env: %#v", err)
return
}
data.Set("key", testCase.key)
if err := data.Set("key", testCase.key); err != nil {
t.Errorf("unable to set key: %#v", err)
return
}
vaultApp, err := vault.New("secret", ansibleFolder)
if err != nil {
t.Errorf("unable to create vault app: %#v", err)
return
}
err = inEnvRead(data, vaultApp)
result := data.Get("value").(string)
failed := false
if err == nil && testCase.wantErr != nil {
failed = true
} else if err != nil && testCase.wantErr == nil {
failed = true
} else if err != nil && err.Error() != testCase.wantErr.Error() {
failed = true
} else if result != testCase.want {
failed = true
}
if failed {
t.Errorf("InEnvRead(%#v) = (`%s`, %#v), want (`%s`, %#v)", data, result, err, testCase.want, testCase.wantErr)
}
})
}
}
| 39,194
|
https://github.com/lmottasin/Simulation_Lab/blob/master/Assignment 02- Monte Carlo Area/problem1.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Simulation_Lab
|
lmottasin
|
Python
|
Code
| 271
| 966
|
# -*- coding: utf-8 -*-
"""problem1 simulation offline 2
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1PU90MXoRQIPmIMT9qLtaqUqCDgVqCVUA
"""
#import the libraries
import matplotlib.pyplot as plt
import random
import math
import numpy as np
# store values for barplot
est_pi =[]
sim_area =[]
def area_plot(N):
random.seed(10)
#printing the square
square_x = [0,5,5,0,0]
square_y = [0,0,5,5,0]
plt.plot(square_x,square_y,c="blue")
#the one fourth of this circle
circle_x = []
circle_y = []
#count=0
for x in np.arange(0,3.0001,0.0001):
x = round(x,4)
circle_x.append(x)
#print(x)
y = math.sqrt(9-(x)**2)
circle_y.append(y)
plt.plot(circle_x,circle_y,c="blue")
#sample number
hit=0
hit_x =[]
hit_y =[]
miss_x =[]
miss_y =[]
for i in range(1,N+1):
# for one fourth of the circle
x = random.uniform(0,5)
y = random.uniform(0,5)
#if x less than the radius value
if x<=3:
if y<= math.sqrt(9-(x)**2) :
hit+=1
hit_x.append(x)
hit_y.append(y)
else:
miss_x.append(x)
miss_y.append(y)
else:
miss_x.append(x)
miss_y.append(y)
#plotting the random values
plt.scatter(miss_x,miss_y,c='blue',s=5)
plt.scatter(hit_x,hit_y,c='red',s=5)
print("For sample number: ",N)
estimated_pi = (hit/N) * (100/9)
est_pi.append(estimated_pi)
print("Estimated value of PI: ",estimated_pi)
#true value , r=3 , area of circle = pi *r ^2
true_value = math.pi* (3**2)
print("True circle area: ",true_value)
# pi = (area of circle * area of rectange) * (100/9)
#so, area of circle = pi * area of rectange * (9/100)
simulated_area = estimated_pi * (10**2) * (9/100)
sim_area.append(simulated_area)
print("Estimated value of the area of the circle: ", simulated_area)
plt.show()
N = [100,1000,10000]
for i in N:
area_plot(i)
#print(est_pi,sim_area)
# ploting the barplot for pi values
x = np.array(["100","1000","10000"])
y = np.array(est_pi)
plt.bar(x,y,color=["red","green","blue"])
plt.xlabel("N (number of trials)")
plt.ylabel("Estimated Pi Value")
plt.show()
# area of circle barplot
x = np.array(["100","1000","10000"])
y = np.array(sim_area)
plt.bar(x,y,color=["red","green","blue"])
plt.xlabel("N (number of trials)")
plt.ylabel(" Area of the circle")
plt.show()
| 22,622
|
https://github.com/bxb100/action-upload-webdav/blob/master/__tests__/util.test.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
action-upload-webdav
|
bxb100
|
TypeScript
|
Code
| 151
| 684
|
import {filePaths, unmatchedPatterns} from '../src/util'
import * as assert from 'assert'
import * as path from 'path'
const rootPath = path.join(__dirname, '..')
describe('util', () => {
describe('paths', () => {
it('expect github glob function', async () => {
assert.deepStrictEqual(
await filePaths(['test/data/**', 'test/data/does/not/exist/*']),
[path.join(rootPath, 'test/data/foo/test-imge.jpg')]
)
})
it('special pattern', async () => {
assert.deepStrictEqual(await filePaths(['test/*-*/**']), [
path.join(rootPath, 'test/aa-bb/text.txt')
])
})
it('special filetype', async () => {
assert.deepStrictEqual(await filePaths(['test/*-*/*.txt']), [
path.join(rootPath, 'test/aa-bb/text.txt')
])
assert.deepStrictEqual(await filePaths(['test/**/*.txt']), [
path.join(rootPath, 'test/aa-bb/text.txt')
])
assert.deepStrictEqual(await filePaths(['test/**/*.jpg']), [
path.join(rootPath, 'test/data/foo/test-imge.jpg')
])
assert.deepStrictEqual(await filePaths(['test/**/*-*.*']), [
path.join(rootPath, 'test/data/foo/test-imge.jpg')
])
})
it('exclue filetype', async () => {
assert.deepStrictEqual(await filePaths(['test/**', '!**/*.txt']), [
path.join(rootPath, 'test/data/foo/test-imge.jpg')
])
assert.deepStrictEqual(await filePaths(['!**/*.txt']), [])
})
})
describe('unmatchedPatterns', () => {
it("returns the patterns that don't match any files", async () => {
assert.deepStrictEqual(
await unmatchedPatterns([
'test/data/**',
'test/data/does/not/exist/*'
]),
['test/data/does/not/exist/*']
)
})
it("exclude file", async () => {
assert.deepStrictEqual(
await unmatchedPatterns([
'test/data/**',
'test/data/does/not/exist/*',
'!**/*.txt'
]),
['test/data/does/not/exist/*']
)
})
})
})
| 7,222
|
https://github.com/wmacevoy/testrng/blob/master/dieharder/d012/g027/d012_g027_S516976200.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
testrng
|
wmacevoy
|
Shell
|
Code
| 8
| 23
|
#!/bin/bash
dieharder -d 12 -g 27 -S 516976200
| 24,182
|
https://github.com/rodrigosarri/access-control-time/blob/master/src/main/java/br/dev/universos/act/controllers/OccurrenceController.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
access-control-time
|
rodrigosarri
|
Java
|
Code
| 103
| 501
|
package br.dev.universos.act.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.dev.universos.act.models.Occurrence;
import br.dev.universos.act.services.OccurrenceService;
@RestController
@RequestMapping("occurrence")
public class OccurrenceController {
@Autowired
OccurrenceService occurrenceService;
@PostMapping
public Occurrence createOccurrence(@RequestBody Occurrence occurrence) {
return occurrenceService.saveOccurrence(occurrence);
}
@GetMapping
public List<Occurrence> listOccurrence() {
return occurrenceService.findAllOccurrence();
}
@GetMapping("/{id}")
public ResponseEntity<Occurrence> getOccurrence(@PathVariable("id") Long id) throws Exception {
return ResponseEntity.ok(occurrenceService.findOccurrenceById(id).orElseThrow(() -> new Exception("Ocorrência não encontrada")));
}
@PutMapping
public Occurrence updateOccurrence(@RequestBody Occurrence occurrence) {
return occurrenceService.updateOccurrence(occurrence);
}
@DeleteMapping("/{id}")
public ResponseEntity<Occurrence> deleteOccurrence(@PathVariable("id") Long id) {
try {
occurrenceService.deleteOccurrence(id);
} catch (Exception e) {
System.out.println(e);
}
return null;
}
}
| 41,688
|
https://github.com/TeamDDG/AvicusScrimmage/blob/master/src/main/java/in/twizmwaz/cardinal/module/modules/gamerules/GamerulesBuilder.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
AvicusScrimmage
|
TeamDDG
|
Java
|
Code
| 61
| 267
|
package in.twizmwaz.cardinal.module.modules.gamerules;
import in.twizmwaz.cardinal.match.Match;
import in.twizmwaz.cardinal.module.ModuleBuilder;
import in.twizmwaz.cardinal.module.ModuleCollection;
import org.jdom2.Element;
import java.util.HashSet;
import java.util.Set;
public class GamerulesBuilder implements ModuleBuilder {
@Override
public ModuleCollection<Gamerules> load(Match match) {
ModuleCollection<Gamerules> results = new ModuleCollection<>();
Set<String> toDisable = new HashSet<>(128);
for (Element itemRemove : match.getDocument().getRootElement().getChildren("gamerules")) {
for (Element item : itemRemove.getChildren()) {
if (item.getText().equalsIgnoreCase("false")) {
toDisable.add(item.getName());
}
}
}
results.add(new Gamerules(toDisable));
return results;
}
}
| 24,217
|
https://github.com/danielferber/slf4j-toys/blob/master/slf4j-toys/src/main/java/org/usefultoys/slf4j/internal/EventWriter.java
|
Github Open Source
|
Open Source
|
ECL-2.0, Apache-2.0
| 2,019
|
slf4j-toys
|
danielferber
|
Java
|
Code
| 1,063
| 2,464
|
/*
* Copyright 2019 Daniel Felix Ferber
*
* 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 org.usefultoys.slf4j.internal;
import java.util.Map;
import java.util.Map.Entry;
import static org.usefultoys.slf4j.internal.PatternDefinition.*;
import static org.usefultoys.slf4j.internal.SyntaxDefinition.*;
/**
* Provides methods that implement recurrent serialization patterns.
* These patterns are recognized by {@link EventReader}.
* <p>
* To ease serialization of one event and to reduce the amount of parameters,
* EventWrite keeps state of the serialization of the event. For sake of
* simplicity, the EventWrite automatically produces separators.
* <p>
* Thus, the instance might be shared and reused to reduce object creation
* overhead, as long as events are serialized one after the other and within
* the same thread.
*
* @author Daniel Felix Ferber
*/
public final class EventWriter {
private transient boolean firstProperty;
private transient final StringBuilder builder;
/**
* Constructor.
*
* @param builder StringBuilder where encoded event is appended to.
*/
EventWriter(final StringBuilder builder) {
firstProperty = true;
this.builder = builder;
}
/**
* Writes the delimiter that starts the encoded string.
*
* @param prefix Prefix that identifies strings containing an encoded event
*/
void open(final char prefix) {
builder.append(prefix);
builder.append(MESSAGE_OPEN);
}
/**
* Writes the delimiter that ends the encoded string.
*/
void close() {
builder.append(MESSAGE_CLOSE);
}
/**
* Writes a property whose value is an enumeration.
*
* @param name property name
* @param value property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final Enum<?> value) {
property(name, value.name());
return this;
}
/**
* Writes a property whose value is a boolean.
*
* @param name property name
* @param value property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final boolean value) {
property(name, Boolean.toString(value));
return this;
}
/**
* Writes a property whose value is a long integer.
*
* @param name property name
* @param value property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final long value) {
property(name, Long.toString(value));
return this;
}
/**
* Writes a property whose value is a tuple of two long integers.
*
* @param name property name
* @param value1 property value
* @param value2 property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final long value1, final long value2) {
property(name, Long.toString(value1), Long.toString(value2));
return this;
}
/**
* Writes a property whose value is a tuple of three long integers.
*
* @param name property name
* @param value1 property value
* @param value2 property value
* @param value3 property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final long value1, final long value2, final long value3) {
property(name, Long.toString(value1), Long.toString(value2), Long.toString(value3));
return this;
}
/**
* Writes a property whose value is a tuple of four long integers.
*
* @param name property name
* @param value1 property value
* @param value2 property value
* @param value3 property value
* @param value4 property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final long value1, final long value2, final long value3, final long value4) {
property(name, Long.toString(value1), Long.toString(value2), Long.toString(value3), Long.toString(value4));
return this;
}
/**
* Writes a property whose value is a long double.
*
* @param name property name
* @param value property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final double value) {
property(name, Double.toString(value));
return this;
}
/**
* Writes a property whose value is a string.
*
* @param name property name
* @param value property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final String value) {
if (!firstProperty) {
builder.append(PROPERTY_SEPARATOR);
} else {
firstProperty = false;
}
builder.append(name);
builder.append(PROPERTY_EQUALS);
writePropertyValue(value);
return this;
}
/**
* Writes a property whose value is a tuple of tow strings.
*
* @param name property name
* @param value1 property value
* @param value2 property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final String value1, final String value2) {
if (!firstProperty) {
builder.append(PROPERTY_SEPARATOR);
} else {
firstProperty = false;
}
builder.append(name);
builder.append(PROPERTY_EQUALS);
writePropertyValue(value1);
builder.append(PROPERTY_DIV);
writePropertyValue(value2);
return this;
}
/**
* Writes a property whose value is a tuple of three strings.
*
* @param name property name
* @param value1 property value
* @param value2 property value
* @param value3 property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final String value1, final String value2, final String value3) {
if (!firstProperty) {
builder.append(PROPERTY_SEPARATOR);
} else {
firstProperty = false;
}
builder.append(name);
builder.append(PROPERTY_EQUALS);
writePropertyValue(value1);
builder.append(PROPERTY_DIV);
writePropertyValue(value2);
builder.append(PROPERTY_DIV);
writePropertyValue(value3);
return this;
}
/**
* Writes a property whose value is a tuple of four strings.
*
* @param name property name
* @param value1 property value
* @param value2 property value
* @param value3 property value
* @param value4 property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final String value1, final String value2, final String value3, final String value4) {
if (!firstProperty) {
builder.append(PROPERTY_SEPARATOR);
} else {
firstProperty = false;
}
builder.append(name);
builder.append(PROPERTY_EQUALS);
writePropertyValue(value1);
builder.append(PROPERTY_DIV);
writePropertyValue(value2);
builder.append(PROPERTY_DIV);
writePropertyValue(value3);
builder.append(PROPERTY_DIV);
writePropertyValue(value4);
return this;
}
/**
* Writes a property whose value is a map.
*
* @param name property name
* @param map property value
* @return itself for chained method calls.
*/
public EventWriter property(final String name, final Map<String, String> map) {
if (!firstProperty) {
builder.append(PROPERTY_SEPARATOR);
} else {
firstProperty = false;
}
builder.append(name);
builder.append(PROPERTY_EQUALS);
builder.append(MAP_OPEN);
boolean firstEntry = true;
for (final Entry<String, String> entry : map.entrySet()) {
if (!firstEntry) {
builder.append(MAP_SEPARATOR);
} else {
firstEntry = false;
}
final String key = entry.getKey();
final String value = entry.getValue();
builder.append(key);
if (value != null) {
builder.append(MAP_EQUAL);
writeMapValue(value);
}
}
builder.append(MAP_CLOSE);
return this;
}
void writePropertyValue(final String value) {
builder.append(encodePropertyValuePattern.matcher(value).replaceAll(encodeReplacement));
}
void writeMapValue(final String value) {
builder.append(encodeMapValuePattern.matcher(value).replaceAll(encodeReplacement));
}
}
| 8,449
|
https://github.com/XiaoMi/mone/blob/master/hera-all/opentelemetry-java/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ComponentRegistry.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
mone
|
XiaoMi
|
Java
|
Code
| 291
| 675
|
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
package io.opentelemetry.sdk.internal;
import io.opentelemetry.sdk.common.InstrumentationLibraryInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import javax.annotation.Nullable;
/**
* Base class for all the provider classes (TracerProvider, MeterProvider, etc.).
*
* @param <V> the type of the registered value.
*/
public final class ComponentRegistry<V> {
private final ConcurrentMap<InstrumentationLibraryInfo, V> registry = new ConcurrentHashMap<>();
private final Function<InstrumentationLibraryInfo, V> factory;
public ComponentRegistry(Function<InstrumentationLibraryInfo, V> factory) {
this.factory = factory;
}
/**
* Returns the registered value associated with this name and {@code null} version if any,
* otherwise creates a new instance and associates it with the given name and {@code null}
* version.
*
* @param instrumentationName the name of the instrumentation library.
* @return the registered value associated with this name and {@code null} version.
*/
public final V get(String instrumentationName) {
return get(instrumentationName, null);
}
/**
* Returns the registered value associated with this name and version if any, otherwise creates a
* new instance and associates it with the given name and version.
*
* @param instrumentationName the name of the instrumentation library.
* @param instrumentationVersion the version of the instrumentation library.
* @return the registered value associated with this name and version.
*/
public final V get(String instrumentationName, @Nullable String instrumentationVersion) {
InstrumentationLibraryInfo instrumentationLibraryInfo =
InstrumentationLibraryInfo.create(instrumentationName, instrumentationVersion);
// Optimistic lookup, before creating the new component.
V component = registry.get(instrumentationLibraryInfo);
if (component != null) {
return component;
}
V newComponent = factory.apply(instrumentationLibraryInfo);
V oldComponent = registry.putIfAbsent(instrumentationLibraryInfo, newComponent);
return oldComponent != null ? oldComponent : newComponent;
}
/**
* Returns a {@code Collection} view of the registered components.
*
* @return a {@code Collection} view of the registered components.
*/
public final Collection<V> getComponents() {
return Collections.unmodifiableCollection(new ArrayList<>(registry.values()));
}
}
| 50,105
|
https://github.com/googleapis/java-spanner/blob/master/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MockOperationsServiceImpl.java
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,023
|
java-spanner
|
googleapis
|
Java
|
Code
| 455
| 1,615
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.google.cloud.spanner;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.longrunning.CancelOperationRequest;
import com.google.longrunning.DeleteOperationRequest;
import com.google.longrunning.GetOperationRequest;
import com.google.longrunning.ListOperationsRequest;
import com.google.longrunning.ListOperationsResponse;
import com.google.longrunning.Operation;
import com.google.longrunning.OperationsGrpc.OperationsImplBase;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Empty;
import io.grpc.ServerServiceDefinition;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
public class MockOperationsServiceImpl extends OperationsImplBase implements MockGrpcService {
private final AtomicLong operationCounter = new AtomicLong();
private final ConcurrentMap<String, Operation> operations = new ConcurrentHashMap<>();
private final ConcurrentMap<String, Future<?>> futures = new ConcurrentHashMap<>();
private final ExecutorService executor =
Executors.newScheduledThreadPool(
8,
new ThreadFactoryBuilder()
.setThreadFactory(MoreExecutors.platformThreadFactory())
.setNameFormat("mock-operations-%d")
.setDaemon(true)
.build());
String generateOperationName(String parent) {
return String.format("%s/operations/%d", parent, operationCounter.incrementAndGet());
}
<T> Future<T> addOperation(Operation operation, Callable<T> task) {
operations.put(operation.getName(), operation);
Future<T> future = executor.submit(task);
futures.put(operation.getName(), future);
return future;
}
Operation get(String name) {
return operations.get(name);
}
void update(Operation operation) {
Operation existing = operations.get(operation.getName());
if (!existing.getDone()) {
operations.put(operation.getName(), operation);
}
}
Iterable<Operation> iterable() {
return operations.values();
}
@Override
public void listOperations(
ListOperationsRequest request, StreamObserver<ListOperationsResponse> responseObserver) {
ListOperationsResponse.Builder builder = ListOperationsResponse.newBuilder();
for (Operation op : iterable()) {
if (op.getName().startsWith(request.getName())) {
builder.addOperations(op);
}
}
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
@Override
public void getOperation(
GetOperationRequest request, StreamObserver<Operation> responseObserver) {
Operation op = operations.get(request.getName());
if (op != null) {
responseObserver.onNext(op);
responseObserver.onCompleted();
} else {
responseObserver.onError(Status.NOT_FOUND.asRuntimeException());
}
}
@Override
public void deleteOperation(
DeleteOperationRequest request, StreamObserver<Empty> responseObserver) {
Operation op = operations.get(request.getName());
if (op != null) {
if (op.getDone()) {
if (operations.remove(request.getName(), op)) {
futures.remove(request.getName());
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
} else {
responseObserver.onError(Status.NOT_FOUND.asRuntimeException());
}
} else {
responseObserver.onError(
Status.FAILED_PRECONDITION
.withDescription("Operation is not done")
.asRuntimeException());
}
} else {
responseObserver.onError(Status.NOT_FOUND.asRuntimeException());
}
}
@Override
public void cancelOperation(
CancelOperationRequest request, StreamObserver<Empty> responseObserver) {
Operation op = operations.get(request.getName());
Future<?> fut = futures.get(request.getName());
if (op != null && fut != null) {
if (!op.getDone()) {
operations.put(
request.getName(),
op.toBuilder()
.clearResponse()
.setDone(true)
.setError(
com.google.rpc.Status.newBuilder()
.setCode(Status.CANCELLED.getCode().value())
.setMessage("Operation was cancelled")
.build())
.build());
fut.cancel(true);
}
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
} else {
responseObserver.onError(Status.NOT_FOUND.asRuntimeException());
}
}
@Override
public List<AbstractMessage> getRequests() {
return Collections.emptyList();
}
@Override
public void addResponse(AbstractMessage response) {
throw new UnsupportedOperationException();
}
@Override
public void addException(Exception exception) {
throw new UnsupportedOperationException();
}
@Override
public ServerServiceDefinition getServiceDefinition() {
return bindService();
}
@Override
public void reset() {
for (Future<?> fut : futures.values()) {
fut.cancel(true);
}
operations.clear();
futures.clear();
}
}
| 18,920
|
https://github.com/DTStack/flinkStreamSQL/blob/master/polardb/polardb-side/polardb-all-side/src/test/java/com/dtstack/flink/sql/side/polardb/PolardbAllReqRowTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
flinkStreamSQL
|
DTStack
|
Java
|
Code
| 20
| 98
|
package com.dtstack.flink.sql.side.polardb;
import com.dtstack.flink.sql.side.rdb.all.RdbAllReqRowTestBase;
public class PolardbAllReqRowTest extends RdbAllReqRowTestBase {
@Override
protected void init() {
clazz = PolardbAllReqRow.class;
}
}
| 34,819
|
https://github.com/tobiaselsaesser/COPASI/blob/master/copasi/xml/.cvsignore
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-other-copyleft, Artistic-2.0, LicenseRef-scancode-proprietary-license
| 2,018
|
COPASI
|
tobiaselsaesser
|
Ignore List
|
Code
| 3
| 13
|
Makefile
schema
*.xcodeproj
| 6,502
|
https://github.com/baitongda/xy2s/blob/master/application/admin/model/AuthModel.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
xy2s
|
baitongda
|
PHP
|
Code
| 321
| 1,749
|
<?php
namespace app\admin\model;
use think\Model;
use think\Validate;
use app\admin\service\AuthService;
/*目前还不用到模型,要多关联才会用到
要明白这个问题,必须了解 MVC 历史。早在 MVC 出现以前,程序员是将 html、css、js、php、SQL 写在一个 .php 文件内的,那时的网页非常简单。后来复杂了,需要多个人协同开发,一个开发后台,专写 php + SQL,一个开发前端,专写 html + css + js。形成了 VC 架构,但有个问题,他们之间不是异步开发的,而是同步开发,前端写完模板,phper 才能在上面加 php 代码。如果不小心字符串过长了,样式可能会错乱,又要找前端调整样式。这样工作效率很低。最后 M 出现了,phper 可以在 M 上写 php 代码,写完后,进行单元测试即可。前端在 V 上写 html + css + js 代码,这个过程是异步完成的,彼此之间互不影响,最后拼接的时候,用 C 调用一下 M 获得数据后,再渲染到 V 上即可。C 就是个桥接器而已。但现在的开发模式又变了,出现了很多后台和前台框架,这使得 M 和 V 的地位一下子下降了。很多 M 要完成的功能,后台框架包办了,如 ThinkPHP,很多 V 要完成的功能,前台框架包办了,如 Amaze UI。因为框架技术的发展,导致很多程序员的开发效率大增,开发成本大幅度下降。许多 phper 不需要依赖前端也可以开发出非常出色的网站。使得 MVC 本来为了协同开发而设计出来的模式显得不是那么重要了。所以完全可以用 C 替代 M。但受 ThinkPHP 框架限制,有些功能,如多对多关联模型,只能在 M 中实现。所以有时还是要用 M。有时一套 CMS 中要可以选择多套模板,这时就需要前端分担一些工作量,不然 phper 要累死了。
*/
/*
* 用于es_auth表操作的验证的一个类
* @author liyuzhao
*
*以下一个函数功能
* @access public
* @abstract authValide 主要功能:验证auth添加的信息。一个逻辑:主要对接收的auth信息进行验证
* */
class AuthModel extends Model
{
// 设置当前模型对应的完整数据表名称
protected $table = 'es_auth';
/*
* 这是一个验证auth添加的信息
* @param array $data 接收的auth信息,为一个一维数组
* @param string $val 默认为add,这个参数是表名是添加验证还是编辑验证,默认会进行数据添加验证
* @return bool 验证正确返回true
* @return string 失败则返回错误信息
* */
public function authValidate($data, $val = 'add')
{
$validate = validate('AuthValidate');
if (empty($data['auth_dingji_id'])) {
$data['auth_dingji_id'] = ' ';
}
if (empty($data['auth_yiji_id'])) {
$data['auth_yiji_id'] = ' ';
}
$check_data = [
'auth_name' => $data['auth_name'],
'auth_level' => $data['auth_level'],
'auth_dingji_id' => $data['auth_dingji_id'],
'auth_yiji_id' => $data['auth_yiji_id'],
'auth_c' => $data['auth_c'],
'auth_a' => $data['auth_a']
];
//如果为0级
if ($data['auth_level'] == '0') {
if (!$validate->scene('dingji')->check($check_data)) {
return $validate->getError();
} else {
if ($val == 'add') {
//这里调用service模块里面的验证权限名,如果是编辑就不用验证
$as = new AuthService();
$fl = $as->checkName($data);
if ($fl) {
return '权限名存在';
} else {
return true;
}
} else {
return true;
}
}
} else if ($data['auth_level'] == '1') {
if (!$validate->scene('yiji')->check($check_data)) {
return $validate->getError();
} else {
if ($val == 'add') {
//这里调用service模块里面的验证权限名,如果是编辑就不用验证
$as = new AuthService();
$fl = $as->checkName($data);
if ($fl) {
return '权限名存在';
} else {
return true;
}
} else {
return true;
}
}
} else if ($data['auth_level'] == '2') {
if (!$validate->scene('erji')->check($check_data)) {
return $validate->getError();
} else {
if ($val == 'add') {
//这里调用service模块里面的验证权限名,如果是编辑就不用验证
$as = new AuthService();
$fl = $as->checkName($data);
if ($fl) {
return '权限名存在';
} else {
return true;
}
} else {
return true;
}
}
}
}
}
| 2,517
|
https://github.com/phillrog/lista-telefonica/blob/master/ListaTelefonica.Infra.Data/EntityConfig/PersonPhoneConfiguration.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
lista-telefonica
|
phillrog
|
C#
|
Code
| 56
| 285
|
using System;
using System.Collections.Generic;
using System.Text;
using ListaTelefonica.Domain.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace ListaTelefonica.Infra.Data.EntityConfig
{
public class PersonPhoneConfiguration : IEntityTypeConfiguration<PersonPhone>
{
public void Configure(EntityTypeBuilder<PersonPhone> builder)
{
builder.ToTable("PessoaTelefone");
builder.HasKey(p => p.Id);
builder.Property(p => p.Id).UseNpgsqlSerialColumn();
builder.Property(p => p.Description)
.IsRequired()
.HasMaxLength(100);
builder.Property(p => p.Number)
.IsRequired()
.HasMaxLength(20);
builder.Property(p => p.PersonId);
builder.HasOne(p => p.Person).WithMany(u => u.Phones).HasForeignKey( p=> p.PersonId);
}
}
}
| 26,698
|
https://github.com/lorenzojanrommel/blog-laravel-php/blob/master/resources/views/articles/single_article.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
blog-laravel-php
|
lorenzojanrommel
|
PHP
|
Code
| 18
| 120
|
@extends('applayout')
@section('title')
{{$article->title}}
@endsection
@section('main_content')
<div class="container">
<h3>{{$article->title}}</h3>
<p>{{$article->content}}</p>
<a href='{{url("articles/$article->id/edit")}}'><button class="btn green darken-4">Edit this article</button></a>
</div>
@endsection
| 15,567
|
https://github.com/apache/incubator-pekko/blob/master/remote/src/test/scala/org/apache/pekko/remote/artery/OutboundHandshakeSpec.scala
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, Apache-2.0, LicenseRef-scancode-protobuf, LicenseRef-scancode-public-domain, BSD-2-Clause, Unlicense, CC0-1.0
| 2,023
|
incubator-pekko
|
apache
|
Scala
|
Code
| 436
| 1,882
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/
/*
* Copyright (C) 2016-2022 Lightbend Inc. <https://www.lightbend.com>
*/
package org.apache.pekko.remote.artery
import scala.concurrent.duration._
import org.apache.pekko
import pekko.actor.Address
import pekko.remote.UniqueAddress
import pekko.remote.artery.OutboundHandshake.HandshakeReq
import pekko.remote.artery.OutboundHandshake.HandshakeTimeoutException
import pekko.stream.scaladsl.Keep
import pekko.stream.testkit.TestPublisher
import pekko.stream.testkit.TestSubscriber
import pekko.stream.testkit.scaladsl.TestSink
import pekko.stream.testkit.scaladsl.TestSource
import pekko.testkit.PekkoSpec
import pekko.testkit.ImplicitSender
import pekko.util.OptionVal
class OutboundHandshakeSpec extends PekkoSpec("""
pekko.stream.materializer.debug.fuzzing-mode = on
""") with ImplicitSender {
val addressA = UniqueAddress(Address("pekko", "sysA", "hostA", 1001), 1)
val addressB = UniqueAddress(Address("pekko", "sysB", "hostB", 1002), 2)
private val outboundEnvelopePool = ReusableOutboundEnvelope.createObjectPool(capacity = 16)
private def setupStream(
outboundContext: OutboundContext,
timeout: FiniteDuration = 5.seconds,
retryInterval: FiniteDuration = 10.seconds,
injectHandshakeInterval: FiniteDuration = 10.seconds,
livenessProbeInterval: Duration = Duration.Undefined)
: (TestPublisher.Probe[String], TestSubscriber.Probe[Any]) = {
TestSource
.probe[String]
.map(msg => outboundEnvelopePool.acquire().init(OptionVal.None, msg, OptionVal.None))
.via(
new OutboundHandshake(
system,
outboundContext,
outboundEnvelopePool,
timeout,
retryInterval,
injectHandshakeInterval,
livenessProbeInterval))
.map(env => env.message)
.toMat(TestSink.probe[Any])(Keep.both)
.run()
}
"OutboundHandshake stage" must {
"send HandshakeReq when first pulled" in {
val inboundContext = new TestInboundContext(localAddress = addressA)
val outboundContext = inboundContext.association(addressB.address)
val (_, downstream) = setupStream(outboundContext)
downstream.request(10)
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.cancel()
}
"send HandshakeReq also when uniqueRemoteAddress future completed at startup" in {
val inboundContext = new TestInboundContext(localAddress = addressA)
val outboundContext = inboundContext.association(addressB.address)
inboundContext.completeHandshake(addressB)
val (upstream, downstream) = setupStream(outboundContext)
upstream.sendNext("msg1")
downstream.request(10)
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.expectNext("msg1")
downstream.cancel()
}
"timeout if handshake not completed" in {
val inboundContext = new TestInboundContext(localAddress = addressA)
val outboundContext = inboundContext.association(addressB.address)
val (_, downstream) = setupStream(outboundContext, timeout = 200.millis)
downstream.request(1)
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.expectError().getClass should be(classOf[HandshakeTimeoutException])
}
"retry HandshakeReq" in {
val inboundContext = new TestInboundContext(localAddress = addressA)
val outboundContext = inboundContext.association(addressB.address)
val (_, downstream) = setupStream(outboundContext, retryInterval = 100.millis)
downstream.request(10)
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.cancel()
}
"not deliver messages from upstream until handshake completed" in {
val inboundContext = new TestInboundContext(localAddress = addressA)
val outboundContext = inboundContext.association(addressB.address)
val (upstream, downstream) = setupStream(outboundContext)
downstream.request(10)
downstream.expectNext(HandshakeReq(addressA, addressB.address))
upstream.sendNext("msg1")
downstream.expectNoMessage(200.millis)
// InboundHandshake stage will complete the handshake when receiving HandshakeRsp
inboundContext.completeHandshake(addressB)
downstream.expectNext("msg1")
upstream.sendNext("msg2")
downstream.expectNext("msg2")
downstream.cancel()
}
"inject HandshakeReq" in {
val inboundContext = new TestInboundContext(localAddress = addressA)
val outboundContext = inboundContext.association(addressB.address)
val (upstream, downstream) = setupStream(outboundContext, injectHandshakeInterval = 500.millis)
downstream.request(10)
upstream.sendNext("msg1")
downstream.expectNext(HandshakeReq(addressA, addressB.address))
inboundContext.completeHandshake(addressB)
downstream.expectNext("msg1")
downstream.expectNoMessage(600.millis)
upstream.sendNext("msg2")
upstream.sendNext("msg3")
upstream.sendNext("msg4")
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.expectNext("msg2")
downstream.expectNext("msg3")
downstream.expectNext("msg4")
downstream.expectNoMessage(600.millis)
downstream.cancel()
}
"send HandshakeReq for liveness probing" in {
val inboundContext = new TestInboundContext(localAddress = addressA)
val outboundContext = inboundContext.association(addressB.address)
val (_, downstream) = setupStream(outboundContext, livenessProbeInterval = 200.millis)
downstream.request(10)
// this is from the initial
downstream.expectNext(HandshakeReq(addressA, addressB.address))
inboundContext.completeHandshake(addressB)
// these are from livenessProbeInterval
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.expectNext(HandshakeReq(addressA, addressB.address))
downstream.cancel()
}
}
}
| 2,550
|
https://github.com/deepak-devadiga/cowin/blob/master/src/app/pages/tabs-page/tabs-page-routing.module.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
cowin
|
deepak-devadiga
|
TypeScript
|
Code
| 123
| 393
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TabsPage } from './tabs-page';
import { AnalyticsPage } from '../analytics/analytics';
const routes: Routes = [
{
path: 'tabs',
component: TabsPage,
children: [
{
path: 'analytics',
children: [
{
path: '',
component: AnalyticsPage,
}
]
},
{
path: 'vaccination',
children: [
{
path: '',
loadChildren: () => import('../vaccination/vaccination.module').then(m => m.VaccinationModule)
}
]
},
{
path: 'news',
children: [
{
path: '',
loadChildren: () => import('../news/news.module').then(m => m.NewsModule)
}
]
},
{
path: 'health',
children: [
{
path: '',
loadChildren: () => import('../health/health.module').then(m => m.HealthModule)
}
]
},
{
path: '',
redirectTo: '/app/tabs/analytics',
pathMatch: 'full'
}
]
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class TabsPageRoutingModule { }
| 37,625
|
https://github.com/kerrbrittany9/best-restaurants/blob/master/views/cuisine.html.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
best-restaurants
|
kerrbrittany9
|
Twig
|
Code
| 91
| 398
|
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link href="css/styles.css" rel="stylesheet" type="text/css">
<title>Cuisines</title>
</head>
<body>
<h1>{{ cuisine.getType }}</h1>
{% if restaurants is not empty %}
<p>Here are your restaurants:</p>
<ul>
{% for restaurant in restaurants %}
<li>{{ restaurant.getName }}</li>
<p>{{ restaurant.getDescription }}</p>
{% endfor %}
</ul>
{% endif %}
<p><a href="/cuisines/{{ cuisine.getId }}/edit">Edit this cuisine</a></p>
<p><a href='/'>Home</a></p>
<h4>Add a restaurant</h4>
<form action='/restaurants' method='post'>
<input id="cuisine_id" name="cuisine_id" type="hidden" value="{{ cuisine.getId() }}">
<label for='input_name'>Restaurant name</label>
<input id='input_name' name='input_name' type='text'>
<label for="description">Restaurant description</label>
<input id="description" name="description" type="text">
<button type='submit'>Add restaurant</button>
</form>
<p><a href='/'>Home</a></p>
</body>
</html>
| 50,665
|
https://github.com/pv42/OC/blob/master/wdb/libwdbserver.lua
|
Github Open Source
|
Open Source
|
MIT
| null |
OC
|
pv42
|
Lua
|
Code
| 191
| 562
|
local db = {}
local libudp = require("libudp")
local libwdb = require("libwdb")
local serialization = require("serialization")
local fs = require("filesystem")
local log = require("log")
local event = require("event")
local path = "/usr/wdb/"
local function recivePackage(package)
--package = serialization.unserialize(package_s)
if package.x == nil or package.y == nil or package.z == nil then
return
end
if db[package.x] == nil then
db[package.x] = {}
end
if db[package.x][package.y] == nil then
db[package.x][package.y] = {}
end
db[package.x][package.y][package.z] = package.block
print("block " .. package.x .. "," .. package.y .. "," .. package.z)
end
local function save()
local f, msg = io.open(path, "w")
if not f then
log.e("could not load chunk file " .. msg)
return
else
f:write(serialization.serialize(db))
end
log.i("db saved")
end
local function loadChunk(filename)
-- filename must be chunk_[x]_[z].chk
if not filename:gmatch("chunk_[%-]?[0-9]+_[%-]?[0-9]+.chk") then
log.e("could not load chunk file:" .. "filename does not match")
return
end
local f, msg = io.open(path,"r")
if not f then
log.e("could not load chunk file " .. msg)
return
else
log.i("chunk x,z loaded")
end
end
local function loadDB()
db = {}
for f in fs.list(path) do
loadChunk(filename)
end
end
print("wdb 1.0 SERVER")
load()
libudp.addReceiveHandler(libwdb.PORT, recivePackage)
print("Press 'Ctrl-C' to exit")
event.pull("interrupted")
libudp.addReceiveHandler(libwdb.PORT, nil)
save()
| 29,157
|
https://github.com/fengxiaochuang/jnieasy/blob/master/src/com/innowhere/jnieasy/core/listener/FetchLifecycleEvent.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
jnieasy
|
fengxiaochuang
|
Java
|
Code
| 165
| 335
|
/*
* AttachCopyLifecycleEvent.java
*
* Created on 22 de septiembre de 2005, 18:21
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package com.innowhere.jnieasy.core.listener;
/**
* This is the event class used in fetch life cycle event notifications.
*
* @author Jose M. Arranz Santamaria
* @see com.innowhere.jnieasy.core.mem.NativeManager#fetch(Object,int)
*/
public class FetchLifecycleEvent extends InstanceLifecycleEvent
{
private int mode;
/**
* Creates a new event object with the specified source and fetch mode.
*
* @param source the instance that triggered the event.
* @param mode the mode being used to fetch the source object.
*/
public FetchLifecycleEvent(Object source,int mode)
{
super(source,FETCH);
this.mode = mode;
}
/**
* Returns the mode being used to fetch the source object.
*
* @return the fetch mode.
*/
public int getMode()
{
return mode;
}
}
| 13,858
|
https://github.com/colinmahns/darkweb-everywhere/blob/master/install.sh
|
Github Open Source
|
Open Source
|
Unlicense
| 2,016
|
darkweb-everywhere
|
colinmahns
|
Shell
|
Code
| 7
| 45
|
#!/bin/sh
cp rules/*.xml ~/tor-browser_en-US/Data/Browser/profile.default/HTTPSEverywhereUserRules/
echo "Installation completed."
| 50,076
|
https://github.com/Aghabekyan/ararat/blob/master/sass/_icons.scss
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-public-domain
| 2,017
|
ararat
|
Aghabekyan
|
SCSS
|
Code
| 191
| 842
|
@charset "UTF-8";
@font-face {
font-family: "aricons";
src:url("../fonts/aricons.eot");
src:url("../fonts/aricons.eot?#iefix") format("embedded-opentype"),
url("../fonts/aricons.woff") format("woff"),
url("../fonts/aricons.ttf") format("truetype"),
url("../fonts/aricons.svg#aricons") format("svg");
font-weight: normal;
font-style: normal;
}
[data-icon]:before {
font-family: "aricons" !important;
content: attr(data-icon);
font-style: normal !important;
font-weight: normal !important;
font-variant: normal !important;
text-transform: none !important;
speak: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
[class^="icon-"]:before,
[class*=" icon-"]:before {
font-family: "aricons" !important;
font-style: normal !important;
font-weight: normal !important;
font-variant: normal !important;
text-transform: none !important;
speak: none;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.icon-search:before {
content: "\61";
}
.icon-hamburger:before {
content: "\62";
}
.icon-angle-double-left:before {
content: "\63";
}
.icon-angle-double-right:before {
content: "\64";
}
.icon-angle-double-up:before {
content: "\65";
}
.icon-angle-double-down:before {
content: "\6b";
}
.icon-angle-down:before {
content: "\66";
}
.icon-angle-left:before {
content: "\67";
}
.icon-angle-right:before {
content: "\68";
}
.icon-angle-up:before {
content: "\69";
}
.icon-phone:before {
content: "\6a";
}
.icon-youtube-play:before {
content: "\6c";
}
.icon-facebook:before {
content: "\6d";
}
.icon-social-youtube:before {
content: "\6c";
}
.icon-play:before {
content: "\70";
}
.icon-youtube-square:before {
content: "\71";
}
.icon-youtube:before {
content: "\72";
}
.icon-play-1:before {
content: "\74";
}
.icon-calendar:before {
content: "\73";
}
.icon-location:before {
content: "\75";
}
.icon-twitter:before {
content: "\76";
}
.icon-vkontakte:before {
content: "\77";
}
.icon-social-skype:before {
content: "\78";
}
| 33,480
|
https://github.com/linkedpipes/etl/blob/master/executor/src/main/java/com/linkedpipes/etl/executor/pipeline/model/ConfigurationDescription.java
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
etl
|
linkedpipes
|
Java
|
Code
| 94
| 318
|
package com.linkedpipes.etl.executor.pipeline.model;
import com.linkedpipes.etl.executor.api.v1.vocabulary.LP_OBJECTS;
import com.linkedpipes.etl.rdf.utils.model.BackendRdfValue;
import com.linkedpipes.etl.rdf.utils.pojo.Loadable;
/**
* Represent a configuration description.
*/
public class ConfigurationDescription implements Loadable {
private final String iri;
private String describedType;
public ConfigurationDescription(String iri) {
this.iri = iri;
}
@Override
public Loadable load(String predicate, BackendRdfValue object) {
switch (predicate) {
case LP_OBJECTS.HAS_DESCRIBE:
describedType = object.asString();
return null;
default:
return null;
}
}
void check() throws InvalidPipelineException {
if (describedType == null) {
throw new InvalidPipelineException(
"Missing configuration type: {}", iri);
}
}
public String getIri() {
return iri;
}
public String getDescribedType() {
return describedType;
}
}
| 24,149
|
https://github.com/alipay/alipay-sdk-net-all/blob/master/v2/AlipaySDKNet/Response/AlipayOpenMiniOrderDeliveryReceiveResponse.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
alipay-sdk-net-all
|
alipay
|
C#
|
Code
| 21
| 81
|
using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// AlipayOpenMiniOrderDeliveryReceiveResponse.
/// </summary>
public class AlipayOpenMiniOrderDeliveryReceiveResponse : AopResponse
{
}
}
| 5,605
|
https://github.com/enrico-dgr/personal-site/blob/master/fe/src/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
personal-site
|
enrico-dgr
|
TypeScript
|
Code
| 111
| 330
|
import React, { lazy, Suspense } from 'react';
import * as ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Redirect, Route, Switch } from 'react-router-dom';
import { PersistGate } from 'redux-persist/integration/react';
import store from './store';
const PersonalSite = lazy(() => import("./PersonalSite"));
const Apps = lazy(() => import("./Apps"));
let domContainer = document.getElementById("react");
if (domContainer === null) throw new Error("dom container is null.");
ReactDOM.render(
<Provider store={store.store}>
{/* loading UI ⇣ ⇣ ⇣ ⇣ ⇣ not implemented */}
<PersistGate loading={null} persistor={store.persistor}>
<Router basename="/">
<Suspense fallback={<div>Loading...</div>}>
<Switch>
<Route exact path="/">
<Redirect to="/ps" />
</Route>
<Route path="/ps" component={PersonalSite} />
<Route path="/apps" component={Apps} />
</Switch>
</Suspense>
</Router>
</PersistGate>
</Provider>,
domContainer
);
| 48,541
|
https://github.com/ka2ush19e/play-scala/blob/master/app/dao/DogDAO.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
play-scala
|
ka2ush19e
|
Scala
|
Code
| 117
| 452
|
package dao
import javax.inject.Inject
import scala.concurrent.Future
import models.Dog
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import slick.driver.JdbcProfile
import slick.lifted.ProvenShape
class DogDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)
extends HasDatabaseConfigProvider[JdbcProfile] {
import driver.api._
private val Dogs = TableQuery[DogsTable]
def list(): Future[List[Dog]] = db.run(Dogs.result).map(_.toList)
def get(id: Int): Future[Dog] = db.run(Dogs.filter(d => d.id === id.bind).result.head)
def insert(dog: Dog): Future[Unit] = db.run(Dogs += dog).map(_ => ())
def update(dog: Dog): Future[Unit] = db.run(Dogs.filter(d => d.id === dog.id.get.bind).update(dog)).map(_ => ())
def delete(id: Int): Future[Unit] = db.run(Dogs.filter(d => d.id === id.bind).delete).map(_ => ())
private class DogsTable(tag: Tag) extends Table[Dog](tag, "Dog") {
def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
def name = column[String]("name")
def favoriteFood = column[String]("favorite_food")
override def * : ProvenShape[Dog] = (id.?, name, favoriteFood) <>(Dog.tupled, Dog.unapply)
}
}
| 15,774
|
https://github.com/Mengsen-W/algorithm/blob/master/29_divide/divide.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
algorithm
|
Mengsen-W
|
C++
|
Code
| 179
| 540
|
/*
* @Date: 2021-10-12 21:04:00
* @Author: Mengsen Wang
* @LastEditors: Mengsen Wang
* @LastEditTime: 2021-10-12 21:05:03
*/
#include <cassert>
#include <climits>
#include <vector>
using namespace std;
class Solution {
public:
int divide(int dividend, int divisor) {
// 考虑被除数为最小值的情况
if (dividend == INT_MIN) {
if (divisor == 1) return INT_MIN;
if (divisor == -1) return INT_MAX;
}
// 考虑除数为最小值的情况
if (divisor == INT_MIN) return dividend == INT_MIN ? 1 : 0;
// 考虑被除数为 0 的情况
if (dividend == 0) return 0;
// 一般情况,使用类二分查找
// 将所有的正数取相反数,这样就只需要考虑一种情况
bool rev = false;
if (dividend > 0) {
dividend = -dividend;
rev = !rev;
}
if (divisor > 0) {
divisor = -divisor;
rev = !rev;
}
vector<int> candidates = {divisor};
// 注意溢出
while (candidates.back() >= dividend - candidates.back())
candidates.push_back(candidates.back() + candidates.back());
int ans = 0;
for (int i = candidates.size() - 1; i >= 0; --i) {
if (candidates[i] >= dividend) {
ans += (1 << i);
dividend -= candidates[i];
}
}
return rev ? -ans : ans;
}
};
int main() {
assert(Solution().divide(10, 3) == 3);
assert(Solution().divide(7, -3) == -2);
}
| 49,041
|
https://github.com/varukirie/admgc/blob/master/src/main/resources/templates/inner/structure.ftl
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
admgc
|
varukirie
|
FreeMarker
|
Code
| 50
| 200
|
<#-- 递归 宏定义 -->
<#macro dirTreeBuild curDir>
<#list curDir.nodes as node>
<#if (node.simpleClassName=="LinkNode") >
<link href="${node.href}" name="${node.name}"/>
</#if>
<#if (node.simpleClassName=="DirNode") >
<dir name="${node.name}" >
<@dirTreeBuild curDir = node />
</dir>
</#if>
</#list>
</#macro>
<site logo="${logo}">
<topnav>
<@dirTreeBuild curDir = topnavDir />
</topnav>
<sidebar>
<@dirTreeBuild curDir = sidebarDir />
</sidebar>
</site>
| 30,974
|
https://github.com/maltelenz/ModelicaStandardLibrary/blob/master/Modelica/Thermal/HeatTransfer/UsersGuide/ReleaseNotes.mo
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
ModelicaStandardLibrary
|
maltelenz
|
Modelica
|
Code
| 24
| 140
|
within Modelica.Thermal.HeatTransfer.UsersGuide;
class ReleaseNotes "Release Notes"
extends Modelica.Icons.ReleaseNotes;
annotation (preferredView="info",Documentation(info="<html>
<h5>Version 4.0.0, 2019-10-18</h5>
<ul>
<li>Add User's Guide, see
<a href=\"https://github.com/modelica/ModelicaStandardLibrary/issues/2990\">#2990</a></li>
</ul>
</html>"));
end ReleaseNotes;
| 23,031
|
https://github.com/wanglei339/wms-test/blob/master/wms-rf/src/main/java/com/lsh/wms/rf/service/inhouse/ProcurementRestService.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
wms-test
|
wanglei339
|
Java
|
Code
| 1,547
| 9,220
|
package com.lsh.wms.rf.service.inhouse;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.lsh.base.common.config.PropertyUtils;
import com.lsh.base.common.exception.BizCheckedException;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.utils.BeanMapTransUtils;
import com.lsh.wms.api.service.inhouse.IProcurementProveiderRpcService;
import com.lsh.wms.api.service.inhouse.IProcurementRestService;
import com.lsh.wms.api.service.item.IItemRpcService;
import com.lsh.wms.api.service.location.ILocationRpcService;
import com.lsh.wms.api.service.request.RequestUtils;
import com.lsh.wms.api.service.stock.IStockQuantRpcService;
import com.lsh.wms.api.service.system.ISysUserRpcService;
import com.lsh.wms.api.service.task.ITaskRpcService;
import com.lsh.wms.core.constant.TaskConstant;
import com.lsh.wms.core.constant.WorkZoneConstant;
import com.lsh.wms.core.dao.utils.NsHeadClient;
import com.lsh.wms.core.service.task.BaseTaskService;
import com.lsh.wms.core.service.zone.WorkZoneService;
import com.lsh.wms.model.baseinfo.BaseinfoItem;
import com.lsh.wms.model.stock.StockQuantCondition;
import com.lsh.wms.model.system.SysUser;
import com.lsh.wms.model.task.TaskEntry;
import com.lsh.wms.model.task.TaskInfo;
import com.lsh.wms.model.zone.WorkZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by mali on 16/8/2.
*/
@Service(protocol = "rest")
@Path("inhouse/procurement")
@Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public class ProcurementRestService implements IProcurementRestService {
private static Logger logger = LoggerFactory.getLogger(ProcurementRestService.class);
@Reference
private IProcurementProveiderRpcService iProcurementProveiderRpcService;
@Reference
private ITaskRpcService iTaskRpcService;
@Reference
private IItemRpcService itemRpcService;
@Reference
private ILocationRpcService locationRpcService;
@Reference
private ISysUserRpcService iSysUserRpcService;
@Reference
private IStockQuantRpcService quantRpcService;
@Autowired
private WorkZoneService workZoneService;
@Autowired
private BaseTaskService baseTaskService;
@POST
@Path("getZoneList")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String getZoneList() throws BizCheckedException {
Map<String, Object> query = new HashMap<String, Object>();
query.put("cmd", "getZoneList");
String ip = PropertyUtils.getString("replenish_svr_ip");
int port = PropertyUtils.getInt("replenish_svr_port");
String rstString = NsHeadClient.jsonCall(ip, port, JsonUtils.obj2Json(query));
Map rst = JsonUtils.json2Obj(rstString, Map.class);
if ( rst == null || Long.valueOf(rst.get("ret").toString())!=0){
return JsonUtils.TOKEN_ERROR("服务器错误");
}else{
return JsonUtils.SUCCESS(rst);
}
}
@POST
@Path("loginToZone")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String loginToZone() throws BizCheckedException {
Map<String, Object> query = new HashMap<String, Object>();
query.put("cmd", "loginToZone");
query.put("zone_id", RequestUtils.getRequest().get("zoneId"));
query.put("uid", Long.valueOf(RequestUtils.getHeader("uid")));
String ip = PropertyUtils.getString("replenish_svr_ip");
int port = PropertyUtils.getInt("replenish_svr_port");
String rstString = NsHeadClient.jsonCall(ip, port, JsonUtils.obj2Json(query));
Map rst = JsonUtils.json2Obj(rstString, Map.class);
if ( rst == null || Long.valueOf(rst.get("ret").toString())!=0){
return JsonUtils.TOKEN_ERROR("服务器错误");
}else{
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}
}
@POST
@Path("logoutFromZone")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String logoutFromZone() throws BizCheckedException {
Map<String, Object> query = new HashMap<String, Object>();
query.put("cmd", "logoutFromZone");
query.put("zone_id", RequestUtils.getRequest().get("zoneId"));
query.put("uid", Long.valueOf(RequestUtils.getHeader("uid")));
String ip = PropertyUtils.getString("replenish_svr_ip");
int port = PropertyUtils.getInt("replenish_svr_port");
String rstString = NsHeadClient.jsonCall(ip, port, JsonUtils.obj2Json(query));
Map rst = JsonUtils.json2Obj(rstString, Map.class);
if ( rst == null || Long.valueOf(rst.get("ret").toString())!=0){
return JsonUtils.TOKEN_ERROR("服务器错误");
}else{
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}
}
@POST
@Path("getZoneTaskList")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String getZoneTaskList() throws BizCheckedException {
Map<String, Object> query = new HashMap<String, Object>();
query.put("cmd", "getZoneTaskList");
query.put("zone_id", RequestUtils.getRequest().get("zoneId"));
query.put("uid", Long.valueOf(RequestUtils.getHeader("uid")));
String ip = PropertyUtils.getString("replenish_svr_ip");
int port = PropertyUtils.getInt("replenish_svr_port");
String rstString = NsHeadClient.jsonCall(ip, port, JsonUtils.obj2Json(query));
Map rst = JsonUtils.json2Obj(rstString, Map.class);
if ( rst == null || Long.valueOf(rst.get("ret").toString())!=0){
return JsonUtils.TOKEN_ERROR("服务器错误");
}else{
return JsonUtils.SUCCESS(rst);
}
}
@POST
@Path("scanFromLocation")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String scanFromLocation() throws BizCheckedException {
Map<String, Object> mapQuery = RequestUtils.getRequest();
try {
Long taskId = Long.valueOf(mapQuery.get("taskId").toString());
TaskEntry entry = iTaskRpcService.getTaskEntryById(taskId);
if(entry==null ){
return JsonUtils.TOKEN_ERROR("任务不存在");
}else {
Long fromLocation = Long.valueOf(mapQuery.get("locationId").toString());
if(entry.getTaskInfo().getFromLocationId().compareTo(fromLocation) !=0 ){
return JsonUtils.TOKEN_ERROR("扫描库位和系统库位不一致");
}
}
iProcurementProveiderRpcService.scanFromLocation(mapQuery);
}catch (BizCheckedException ex){
throw ex;
}
// catch (Exception e) {
// logger.error(e.getMessage());
// return JsonUtils.TOKEN_ERROR("系统繁忙");
// }
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}
@POST
@Path("scanToLocation")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String scanToLocation() throws BizCheckedException {
Map<String, Object> params = RequestUtils.getRequest();
try {
Long taskId = Long.valueOf(params.get("taskId").toString());
TaskEntry entry = iTaskRpcService.getTaskEntryById(taskId);
if(entry==null ){
return JsonUtils.TOKEN_ERROR("任务不存在");
}else {
Long toLocation = Long.valueOf(params.get("locationId").toString());
if(entry.getTaskInfo().getToLocationId().compareTo(toLocation) !=0 ){
return JsonUtils.TOKEN_ERROR("扫描库位和系统库位不一致");
}
}
iProcurementProveiderRpcService.scanToLocation(params);
}catch (BizCheckedException ex){
throw ex;
}
// catch (Exception e) {
// logger.error(e.getMessage());
// return JsonUtils.TOKEN_ERROR("系统繁忙");
// }
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}
@POST
@Path("scanLocation")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String scanLocation() throws BizCheckedException {
Map<String, Object> params = RequestUtils.getRequest();
params.put("uid",RequestUtils.getHeader("uid"));
try {
Long taskId = Long.valueOf(params.get("taskId").toString().trim());
final TaskEntry entry = iTaskRpcService.getTaskEntryById(taskId);
Long type = Long.parseLong(params.get("type").toString().trim());
if(type.compareTo(2L)==0) {
if (entry == null) {
return JsonUtils.TOKEN_ERROR("任务不存在");
} else {
String locationCode = params.get("locationCode").toString();
Long toLocationId = locationRpcService.getLocationIdByCode(locationCode);
if (entry.getTaskInfo().getToLocationId().compareTo(toLocationId) != 0) {
return JsonUtils.TOKEN_ERROR("扫描库位和系统库位不一致");
}
}
iProcurementProveiderRpcService.scanToLocation(params);
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}else if(type.compareTo(1L)==0) {
if(entry==null ){
return JsonUtils.TOKEN_ERROR("任务不存在");
}
TaskInfo info = entry.getTaskInfo();
StockQuantCondition condition = new StockQuantCondition();
condition.setItemId(info.getItemId());
condition.setLocationId(info.getFromLocationId());
BigDecimal qty = quantRpcService.getQty(condition);
if(qty.compareTo(BigDecimal.ZERO)==0){
iTaskRpcService.cancel(taskId);
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}
//判断能否整除
final BaseinfoItem item = itemRpcService.getItem(info.getItemId());
iProcurementProveiderRpcService.scanFromLocation(params);
final TaskInfo taskInfo = baseTaskService.getTaskInfoById(taskId);
final BigDecimal [] decimals = taskInfo.getQty().divideAndRemainder(info.getPackUnit());
return JsonUtils.SUCCESS(new HashMap<String, Object>() {
{
put("taskId", taskInfo.getTaskId().toString());
put("type",2);
put("barcode",item.getCode());
put("skuCode",item.getSkuCode());
put("locationId", taskInfo.getToLocationId());
put("locationCode", locationRpcService.getLocation(taskInfo.getToLocationId()).getLocationCode());
put("toLocationId", taskInfo.getToLocationId());
put("toLocationCode", locationRpcService.getLocation(taskInfo.getToLocationId()).getLocationCode());
put("fromLocationId", taskInfo.getFromLocationId());
put("fromLocationCode", locationRpcService.getLocation(taskInfo.getFromLocationId()).getLocationCode());
put("subType",taskInfo.getSubType());
put("itemId", taskInfo.getItemId());
put("itemName", itemRpcService.getItem(taskInfo.getItemId()).getSkuName());
if(decimals[1].compareTo(BigDecimal.ZERO)==0) {
put("qty", decimals[0]);
put("packName", taskInfo.getPackName());
}else {
put("qty", taskInfo.getQty());
put("packName", "EA");
}
}
});
}else {
return JsonUtils.TOKEN_ERROR("任务状态异常");
}
}catch (BizCheckedException ex){
throw ex;
}
// catch (Exception e) {
// logger.error(e.getMessage());
// return JsonUtils.TOKEN_ERROR("系统繁忙");
// }
}
@POST
@Path("fetchTask")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String fetchTask() throws BizCheckedException {
Long uid = 0L;
try {
uid = Long.valueOf(RequestUtils.getHeader("uid"));
}catch (Exception e){
return JsonUtils.TOKEN_ERROR("违法的账户");
}
SysUser user = iSysUserRpcService.getSysUserById(uid);
if(user==null){
return JsonUtils.TOKEN_ERROR("用户不存在");
}
Map<String,Object> queryMap = new HashMap<String, Object>();
queryMap.put("operator",uid);
queryMap.put("status",TaskConstant.Assigned);
List<TaskEntry> entries = iTaskRpcService.getTaskList(TaskConstant.TYPE_PROCUREMENT, queryMap);
if(entries!=null && entries.size()!=0){
TaskEntry entry = entries.get(0);
final TaskInfo info = entry.getTaskInfo();
final BaseinfoItem item = itemRpcService.getItem(info.getItemId());
final BigDecimal [] decimals = info.getQty().divideAndRemainder(info.getPackUnit());
if(info.getStep()==2){
return JsonUtils.SUCCESS(new HashMap<String, Object>() {
{
put("taskId", info.getTaskId().toString());
put("type",2L);
put("isFlashBack", 1);
put("barcode",item.getCode());
put("skuCode",item.getSkuCode());
put("locationId", info.getToLocationId());
put("locationCode", locationRpcService.getLocation(info.getToLocationId()).getLocationCode());
put("toLocationId", info.getToLocationId());
put("toLocationCode", locationRpcService.getLocation(info.getToLocationId()).getLocationCode());
put("fromLocationId", info.getFromLocationId());
put("fromLocationCode", locationRpcService.getLocation(info.getFromLocationId()).getLocationCode()); put("itemId", info.getItemId());
put("itemName", itemRpcService.getItem(info.getItemId()).getSkuName());
put("subType",info.getSubType());
if(decimals[1].compareTo(BigDecimal.ZERO)==0) {
put("qty", decimals[0]);
put("packName", info.getPackName());
}else {
put("qty", info.getQty());
put("packName", "EA");
}
}
});
}else {
return JsonUtils.SUCCESS(new HashMap<String, Object>() {
{
put("taskId", info.getTaskId().toString());
put("type",1L);
put("barcode",item.getCode());
put("skuCode",item.getSkuCode());
put("isFlashBack", 1);
put("locationId", info.getFromLocationId());
put("locationCode", locationRpcService.getLocation(info.getFromLocationId()).getLocationCode());
put("toLocationId", info.getToLocationId());
put("toLocationCode", locationRpcService.getLocation(info.getToLocationId()).getLocationCode());
put("fromLocationId", info.getFromLocationId());
put("fromLocationCode", locationRpcService.getLocation(info.getFromLocationId()).getLocationCode());
put("itemId", info.getItemId());
put("itemName", itemRpcService.getItem(info.getItemId()).getSkuName());
put("subType",info.getSubType());
if(decimals[1].compareTo(BigDecimal.ZERO)==0) {
put("qty", decimals[0]);
put("packName", info.getPackName());
}else {
put("qty", info.getQty());
put("packName", "EA");
}
}
});
}
}
//final Long taskId = iProcurementProveiderRpcService.assign(uid);
Long taskId = null;
{
//改成从补货策略服务上获取任务
//获取到的任务需要立即给指定的人
//如果因为系统异常导致的错误未能assign成功,补货策略服务讲在一个指定的时间(如10秒)后扫描恢复到任务队列中
//另外,如果一个任务长时间未执行(一个指定的时间),补货策略服务也会从新调度到队列中可赋给其他人
Map<String, Object> query = new HashMap<String, Object>();
query.put("uid", uid);
query.put("cmd", "fetchTask");
query.put("zone_id", RequestUtils.getRequest().get("zoneId"));
String ip = PropertyUtils.getString("replenish_svr_ip");
int port = PropertyUtils.getInt("replenish_svr_port");
String rstString = NsHeadClient.jsonCall(ip, port, JsonUtils.obj2Json(query));
Map rst = JsonUtils.json2Obj(rstString, Map.class);
if ( rst == null || Long.valueOf(rst.get("ret").toString())!=0){
return JsonUtils.TOKEN_ERROR("服务器错误");
}else{
taskId = Long.valueOf(rst.get("task_id").toString());
if(taskId == -1){
return JsonUtils.TOKEN_ERROR("无补货任务可领");
}
}
//iTaskRpcService.assign(taskId, uid);
}
if(taskId.compareTo(0L)==0) {
return JsonUtils.TOKEN_ERROR("无补货任务可领");
}
TaskEntry taskEntry = iTaskRpcService.getTaskEntryById(taskId);
if (taskEntry == null) {
throw new BizCheckedException("2040001");
}
final TaskInfo taskInfo = taskEntry.getTaskInfo();
final BaseinfoItem item = itemRpcService.getItem(taskInfo.getItemId());
final BigDecimal [] decimals = taskInfo.getQty().divideAndRemainder(taskInfo.getPackUnit());
final Long fromLocationId = taskInfo.getFromLocationId();
final String fromLocationCode = locationRpcService.getLocation(fromLocationId).getLocationCode();
final String toLocationCode = locationRpcService.getLocation(taskInfo.getToLocationId()).getLocationCode();
return JsonUtils.SUCCESS(new HashMap<String, Object>() {
{
put("taskId", taskInfo.getTaskId().toString());
put("type", 1L);
put("barcode",item.getCode());
put("skuCode",item.getSkuCode());
put("isFlashBack", 0);
put("fromLocationId", fromLocationId);
put("fromLocationCode", fromLocationCode);
put("locationId", fromLocationId);
put("locationCode", fromLocationCode);
put("toLocationId", taskInfo.getToLocationId());
put("toLocationCode", toLocationCode);
put("itemId", taskInfo.getItemId());
put("subType",taskInfo.getSubType());
put("subType",taskInfo.getSubType());
put("itemName", itemRpcService.getItem(taskInfo.getItemId()).getSkuName());
if(decimals[1].compareTo(BigDecimal.ZERO)==0) {
put("qty", decimals[0]);
put("packName", taskInfo.getPackName());
}else {
put("qty", taskInfo.getQty());
put("packName", "EA");
}
}
});
}
@POST
@Path("view")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String taskView() throws BizCheckedException {
Map<String, Object> mapQuery = RequestUtils.getRequest();
Long taskId = Long.valueOf(mapQuery.get("taskId").toString());
try {
TaskEntry taskEntry = iTaskRpcService.getTaskEntryById(taskId);
if (taskEntry == null) {
throw new BizCheckedException("2040001");
}
TaskInfo taskInfo = taskEntry.getTaskInfo();
final BaseinfoItem item = itemRpcService.getItem(taskInfo.getItemId());
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("type",taskInfo.getStep());
if(taskInfo.getStep()==1){
resultMap.put("locationId", taskInfo.getFromLocationId());
resultMap.put("locationCode", locationRpcService.getLocation(taskInfo.getFromLocationId()).getLocationCode());
}else {
resultMap.put("locationId", taskInfo.getToLocationId());
resultMap.put("locationCode", locationRpcService.getLocation(taskInfo.getToLocationId()).getLocationCode());
}
resultMap.put("itemId", taskInfo.getItemId());
resultMap.put("itemName", itemRpcService.getItem(taskInfo.getItemId()).getSkuName());
resultMap.put("fromLocationId", taskInfo.getFromLocationId());
resultMap.put("fromLocationCode", locationRpcService.getLocation(taskInfo.getFromLocationId()).getLocationCode());
resultMap.put("toLocationId", taskInfo.getToLocationId());
resultMap.put("toLocationCode", locationRpcService.getLocation(taskInfo.getToLocationId()).getLocationCode());
resultMap.put("packName", taskInfo.getPackName());
resultMap.put("uomQty", taskInfo.getQty().divide(taskInfo.getPackUnit(), 0, BigDecimal.ROUND_HALF_DOWN));
resultMap.put("barcode", item.getCode());
resultMap.put("skuCode", item.getSkuCode());
return JsonUtils.SUCCESS(resultMap);
}catch (BizCheckedException ex){
throw ex;
} catch (Exception e) {
logger.error(e.getMessage());
return JsonUtils.TOKEN_ERROR("系统繁忙");
}
}
@POST
@Path("bindTask")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String bindTask() throws BizCheckedException {
Map<String, Object> mapQuery = RequestUtils.getRequest();
Long taskId = Long.valueOf(mapQuery.get("taskId").toString());
try {
TaskEntry taskEntry = iTaskRpcService.getTaskEntryById(taskId);
if (taskEntry == null) {
throw new BizCheckedException("2040001");
}
Long uid = 0L;
try {
uid = Long.valueOf(RequestUtils.getHeader("uid"));
}catch (Exception e){
return JsonUtils.TOKEN_ERROR("违法的账户");
}
SysUser user = iSysUserRpcService.getSysUserById(uid);
if(user==null){
return JsonUtils.TOKEN_ERROR("用户不存在");
}
TaskInfo info = taskEntry.getTaskInfo();
if(info.getStatus().equals(2L)){
if(!info.getOperator().equals(uid)){
return JsonUtils.TOKEN_ERROR("该任务已被人领取");
}
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}
if(info.getStatus().equals(1L)){
iTaskRpcService.assign(taskId,uid);
return JsonUtils.SUCCESS(new HashMap<String, Boolean>() {
{
put("response", true);
}
});
}
return JsonUtils.TOKEN_ERROR("任务已完成或已取消");
}catch (BizCheckedException ex){
throw ex;
} catch (Exception e) {
logger.error(e.getMessage());
return JsonUtils.TOKEN_ERROR("系统繁忙");
}
}
@POST
@Path("assign")
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8})
public String assign() throws BizCheckedException {
Map<String, Object> mapQuery = RequestUtils.getRequest();
Long uid = 0L;
try {
uid = Long.valueOf(RequestUtils.getHeader("uid"));
}catch (Exception e){
return JsonUtils.TOKEN_ERROR("违法的账户");
}
SysUser user = iSysUserRpcService.getSysUserById(uid);
if(user==null){
return JsonUtils.TOKEN_ERROR("用户不存在");
}
Map<String,Object> queryMap = new HashMap<String, Object>();
queryMap.put("operator",uid);
queryMap.put("status",TaskConstant.Assigned);
List<TaskEntry> entries = iTaskRpcService.getTaskList(TaskConstant.TYPE_PROCUREMENT, queryMap);
if(entries!=null && entries.size()!=0){
TaskEntry entry = entries.get(0);
final TaskInfo info = entry.getTaskInfo();
final BaseinfoItem item = itemRpcService.getItem(info.getItemId());
final BigDecimal [] decimals = info.getQty().divideAndRemainder(info.getPackUnit());
if(info.getStep()==2){
return JsonUtils.SUCCESS(new HashMap<String, Object>() {
{
put("taskId", info.getTaskId().toString());
put("type",2L);
put("isFlashBack", 1);
put("barcode",item.getCode());
put("skuCode",item.getSkuCode());
put("locationId", info.getToLocationId());
put("locationCode", locationRpcService.getLocation(info.getToLocationId()).getLocationCode());
put("toLocationId", info.getToLocationId());
put("toLocationCode", locationRpcService.getLocation(info.getToLocationId()).getLocationCode());
put("fromLocationId", info.getFromLocationId());
put("fromLocationCode", locationRpcService.getLocation(info.getFromLocationId()).getLocationCode()); put("itemId", info.getItemId());
put("itemName", itemRpcService.getItem(info.getItemId()).getSkuName());
put("subType",info.getSubType());
if(decimals[1].compareTo(BigDecimal.ZERO)==0) {
put("qty", decimals[0]);
put("packName", info.getPackName());
}else {
put("qty", info.getQty());
put("packName", "EA");
}
}
});
}else {
return JsonUtils.SUCCESS(new HashMap<String, Object>() {
{
put("taskId", info.getTaskId().toString());
put("type",1L);
put("isFlashBack", 1);
put("barcode",item.getCode());
put("skuCode",item.getSkuCode());
put("locationId", info.getFromLocationId());
put("locationCode", locationRpcService.getLocation(info.getFromLocationId()).getLocationCode());
put("toLocationId", info.getToLocationId());
put("toLocationCode", locationRpcService.getLocation(info.getToLocationId()).getLocationCode());
put("fromLocationId", info.getFromLocationId());
put("fromLocationCode", locationRpcService.getLocation(info.getFromLocationId()).getLocationCode());
put("itemId", info.getItemId());
put("itemName", itemRpcService.getItem(info.getItemId()).getSkuName());
put("subType",info.getSubType());
if(decimals[1].compareTo(BigDecimal.ZERO)==0) {
put("qty", decimals[0]);
put("packName", info.getPackName());
}else {
put("qty", info.getQty());
put("packName", "EA");
}
}
});
}
}
Long taskId = Long.valueOf(mapQuery.get("taskId").toString());
try {
TaskEntry taskEntry = iTaskRpcService.getTaskEntryById(taskId);
//iTaskRpcService.assign(taskId,uid);
if (taskEntry == null) {
throw new BizCheckedException("2040001");
}
TaskInfo taskInfo = taskEntry.getTaskInfo();
final BigDecimal [] decimals = taskInfo.getQty().divideAndRemainder(taskInfo.getPackUnit());
final BaseinfoItem item = itemRpcService.getItem(taskInfo.getItemId());
Map<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("type",taskInfo.getStep());
resultMap.put("taskId",taskInfo.getTaskId().toString());
if(taskInfo.getStep()==1){
resultMap.put("locationId", taskInfo.getFromLocationId());
resultMap.put("locationCode", locationRpcService.getLocation(taskInfo.getFromLocationId()).getLocationCode());
}else {
resultMap.put("locationId", taskInfo.getToLocationId());
resultMap.put("locationCode", locationRpcService.getLocation(taskInfo.getToLocationId()).getLocationCode());
}
resultMap.put("itemId", taskInfo.getItemId());
resultMap.put("isFlashBack", 0);
resultMap.put("itemName", itemRpcService.getItem(taskInfo.getItemId()).getSkuName());
resultMap.put("fromLocationId", taskInfo.getFromLocationId());
resultMap.put("fromLocationCode", locationRpcService.getLocation(taskInfo.getFromLocationId()).getLocationCode());
resultMap.put("toLocationId", taskInfo.getToLocationId());
resultMap.put("toLocationCode", locationRpcService.getLocation(taskInfo.getToLocationId()).getLocationCode());
if(decimals[1].compareTo(BigDecimal.ZERO)==0) {
resultMap.put("qty", decimals[0]);
resultMap.put("packName", taskInfo.getPackName());
}else {
resultMap.put("qty", taskInfo.getQty());
resultMap.put("packName", "EA");
}
resultMap.put("barcode", item.getCode());
resultMap.put("skuCode", item.getSkuCode());
resultMap.put("subType", taskInfo.getSubType());
return JsonUtils.SUCCESS(resultMap);
}catch (BizCheckedException ex){
throw ex;
} catch (Exception e) {
logger.error(e.getMessage());
return JsonUtils.TOKEN_ERROR("系统繁忙");
}
}
}
| 50,931
|
https://github.com/Punkline/Melee-Code-Manager/blob/master/.include/punkpc/all.s
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Melee-Code-Manager
|
Punkline
|
GAS
|
Code
| 18
| 107
|
.include "punkpc\\blaba.s"
.include "punkpc\\dbg.s"
.include "punkpc\\enum.s"
.include "punkpc\\idxr.s"
.include "punkpc\\ifalt.s"
.include "punkpc\\ld.s"
.include "punkpc\\smallints.s"
.include "punkpc\\xem.s"
.include "punkpc\\xev.s"
| 45,473
|
https://github.com/amartyniuk/Citrus/blob/master/Tangerine/Tangerine.Core/Operations/ClearRowSelection.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Citrus
|
amartyniuk
|
C#
|
Code
| 54
| 156
|
using System;
using System.Collections.Generic;
using System.Linq;
using Lime;
using Tangerine.Core;
namespace Tangerine.Core.Operations
{
public static class ClearRowSelection
{
public static void Perform()
{
var rows = Document.Current.Rows.ToList();
// Use temporary row list to avoid 'Collection was modified' exception
foreach (var row in rows) {
if (row.GetTimelineItemState().Selected) {
SelectRow.Perform(row, false);
}
}
}
}
}
| 7,029
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.