language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
533
2.921875
3
[]
no_license
using Node.Interfaces; using System; namespace Node { class Program { static string configFile = "Node.ini"; static void Main(string[] args) { IConfig config = new Config(configFile); Node node = new Node(config); while (true) { Console.Write("> "); string input = Console.ReadLine(); string write = node.HandleInput(input); Console.WriteLine(write); } } } }
PHP
UTF-8
3,216
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\DataTables\FAQDataTable; use App\Http\Requests; use App\Http\Requests\CreateFAQRequest; use App\Http\Requests\UpdateFAQRequest; use App\Repositories\FAQRepository; use Flash; use App\Http\Controllers\AppBaseController; use Response; class FAQController extends AppBaseController { /** @var FAQRepository */ private $fAQRepository; public function __construct(FAQRepository $fAQRepo) { $this->fAQRepository = $fAQRepo; } /** * Display a listing of the FAQ. * * @param FAQDataTable $fAQDataTable * @return Response */ public function index(FAQDataTable $fAQDataTable) { return $fAQDataTable->render('f_a_q_s.index'); } /** * Show the form for creating a new FAQ. * * @return Response */ public function create() { return view('f_a_q_s.create'); } /** * Store a newly created FAQ in storage. * * @param CreateFAQRequest $request * * @return Response */ public function store(CreateFAQRequest $request) { $input = $request->all(); $fAQ = $this->fAQRepository->create($input); Flash::success('F A Q saved successfully.'); return redirect(route('fAQS.index')); } /** * Display the specified FAQ. * * @param int $id * * @return Response */ public function show($id) { $fAQ = $this->fAQRepository->find($id); if (empty($fAQ)) { Flash::error('F A Q not found'); return redirect(route('fAQS.index')); } return view('f_a_q_s.show')->with('fAQ', $fAQ); } /** * Show the form for editing the specified FAQ. * * @param int $id * * @return Response */ public function edit($id) { $fAQ = $this->fAQRepository->find($id); if (empty($fAQ)) { Flash::error('F A Q not found'); return redirect(route('fAQS.index')); } return view('f_a_q_s.edit')->with('fAQ', $fAQ); } /** * Update the specified FAQ in storage. * * @param int $id * @param UpdateFAQRequest $request * * @return Response */ public function update($id, UpdateFAQRequest $request) { $fAQ = $this->fAQRepository->find($id); if (empty($fAQ)) { Flash::error('F A Q not found'); return redirect(route('fAQS.index')); } $fAQ = $this->fAQRepository->update($request->all(), $id); Flash::success('F A Q updated successfully.'); return redirect(route('fAQS.index')); } /** * Remove the specified FAQ from storage. * * @param int $id * * @return Response */ public function destroy($id) { $fAQ = $this->fAQRepository->find($id); if (empty($fAQ)) { Flash::error('F A Q not found'); return redirect(route('fAQS.index')); } $this->fAQRepository->delete($id); Flash::success('F A Q deleted successfully.'); return redirect(route('fAQS.index')); } }
Markdown
UTF-8
14,497
2.59375
3
[]
no_license
# 【Boost】boost库asio详解3——io_service作为work pool - DoubleLi - 博客园 无论如何使用,都能感觉到使用boost.asio实现服务器,不仅是一件非常轻松的事,而且代码很漂亮,逻辑也相当清晰,这点上很不同于ACE。 使用io_service作为处理工作的work pool,可以看到,就是通过io_service.post投递一个Handler到io_service的队列,Handler在这个io_service.run内部得到执行,有可能你会发现,io_services.dispatch的接口也和io_service.post一样,但不同的是它是直接调用而不是经过push到队列然后在io_services.run中执行,而在这个示例当中,显然我们需要把工作交到另一个线程去完成,这样才不会影响网络接收线程池的工作以达到高效率的接收数据,这种设计与前面的netsever其实相同,这就是典型的Half Sync/Half Async。二者的区别就是netsever自己实现了工作队列,而不是直接使用io_service,这种设计实际上在win下是使用了iocp作为工作队列。 不过我更倾向于前一种设计,因为那样做,代码一切都在自己的掌握中,而io_service则是经过许多封装代码,并且本身设计只是用于处理网络完成事件的。 无论如何使用,都能感觉到使用boost.asio实现服务器,不仅是一件非常轻松的事,而且代码很漂亮,逻辑也相当清晰,这点上很不同于ACE。 **[cpp]**[view plain](http://blog.csdn.net/huang_xw/article/details/8475050#)[copy](http://blog.csdn.net/huang_xw/article/details/8475050#) [print](http://blog.csdn.net/huang_xw/article/details/8475050#)[?](http://blog.csdn.net/huang_xw/article/details/8475050#) - #include <stdio.h>    - #include <cstdlib>    - #include <iostream>    - #include <boost/thread.hpp>    - #include <boost/aligned_storage.hpp>    - #include <boost/array.hpp>    - #include <boost/bind.hpp>    - #include <boost/enable_shared_from_this.hpp>    - #include <boost/noncopyable.hpp>    - #include <boost/shared_ptr.hpp>    - #include <boost/asio.hpp>    - - using boost::asio::ip::tcp;    - - class handler_allocator    -     : private boost::noncopyable    - {    - public:    -     handler_allocator()    -         : in_use_(false)    -     {    -     }    - - void* allocate(std::size_t size)    -     {    - if (!in_use_ && size < storage_.size)    -         {    -             in_use_ = true;    - return storage_.address();    -         }    - else    -         {    - return ::operator new(size);    -         }    -     }    - - void deallocate(void* pointer)    -     {    - if (pointer == storage_.address())    -         {    -             in_use_ = false;    -         }    - else    -         {    -             ::operator delete(pointer);    -         }    -     }    - - private:    - // Storage space used for handler-based custom memory allocation.    -     boost::aligned_storage<1024> storage_;    - - // Whether the handler-based custom allocation storage has been used.    - bool in_use_;    - };    - - template <typename Handler>    - class custom_alloc_handler    - {    - public:    -     custom_alloc_handler(handler_allocator& a, Handler h)    -         : allocator_(a),    -         handler_(h)    -     {    -     }    - - template <typename Arg1>    - void operator()(Arg1 arg1)    -     {    -         handler_(arg1);    -     }    - - template <typename Arg1, typename Arg2>    - void operator()(Arg1 arg1, Arg2 arg2)    -     {    -         handler_(arg1, arg2);    -     }    - - friend void* asio_handler_allocate(std::size_t size,    -         custom_alloc_handler<Handler>* this_handler)    -     {    - return this_handler->allocator_.allocate(size);    -     }    - - friend void asio_handler_deallocate(void* pointer, std::size_t /*size*/,    -         custom_alloc_handler<Handler>* this_handler)    -     {    -         this_handler->allocator_.deallocate(pointer);    -     }    - - private:    -     handler_allocator& allocator_;    -     Handler handler_;    - };    - - // Helper function to wrap a handler object to add custom allocation.    - template <typename Handler>    - inline custom_alloc_handler<Handler> make_custom_alloc_handler(    -     handler_allocator& a, Handler h)    - {    - return custom_alloc_handler<Handler>(a, h);    - }    - - /// A pool of io_service objects.    - class io_service_pool    -     : private boost::noncopyable    - {    - public:    - /// Construct the io_service pool.    - explicit io_service_pool(std::size_t pool_size) : next_io_service_(0)    -     {    - if (pool_size == 0)    - throw std::runtime_error("io_service_pool size is 0");    - - // Give all the io_services work to do so that their run() functions will not    - // exit until they are explicitly stopped.    - for (std::size_t i = 0; i < pool_size; ++i)    -         {    -             io_service_ptr io_service(new boost::asio::io_service);    -             work_ptr work(new boost::asio::io_service::work(*io_service));    -             io_services_.push_back(io_service);    -             work_.push_back(work);    -         }    -     }    - - // Run all io_service objects in the pool.    - void run()    -     {    - // Create a pool of threads to run all of the io_services.    -         std::vector<boost::shared_ptr<boost::thread> > threads;    - for (std::size_t i = 0; i < io_services_.size(); ++i)    -         {    -             boost::shared_ptr<boost::thread> thread(new boost::thread(    -                 boost::bind(&boost::asio::io_service::run, io_services_[i])));    -             threads.push_back(thread);    -         }    - - // Wait for all threads in the pool to exit.    - for (std::size_t i = 0; i < threads.size(); ++i)    -             threads[i]->join();    -     }    - - // Stop all io_service objects in the pool.    - void stop()    -     {    - // Explicitly stop all io_services.    - for (std::size_t i = 0; i < io_services_.size(); ++i)    -             io_services_[i]->stop();    -     }    - - // Get an io_service to use.    -     boost::asio::io_service& get_io_service()    -     {    - // Use a round-robin scheme to choose the next io_service to use.    -         boost::asio::io_service& io_service = *io_services_[next_io_service_];    -         ++next_io_service_;    - if (next_io_service_ == io_services_.size())    -             next_io_service_ = 0;    - return io_service;    -     }    - - private:    - typedef boost::shared_ptr<boost::asio::io_service> io_service_ptr;    - typedef boost::shared_ptr<boost::asio::io_service::work> work_ptr;    - - /// The pool of io_services.    -     std::vector<io_service_ptr> io_services_;    - - /// The work that keeps the io_services running.    -     std::vector<work_ptr> work_;    - - /// The next io_service to use for a connection.    -     std::size_t next_io_service_;    - };    - - class session    -     : public boost::enable_shared_from_this<session>    - {    - public:    -     session(boost::asio::io_service& work_service   -         , boost::asio::io_service& io_service)    -         : socket_(io_service)    -         , io_work_service(work_service)    -     {    -     }    - -     tcp::socket& socket()    -     {    - return socket_;    -     }    - - void start()    -     {    -         socket_.async_read_some(boost::asio::buffer(data_),    -             make_custom_alloc_handler(allocator_,    -             boost::bind(&session::handle_read,    -             shared_from_this(),    -             boost::asio::placeholders::error,    -             boost::asio::placeholders::bytes_transferred)));    -     }    - - void handle_read(const boost::system::error_code& error,    - size_t bytes_transferred)    -     {    - if (!error)    -         {    -             boost::shared_ptr<std::vector<char> > buf(new std::vector<char>);    - -             buf->resize(bytes_transferred);    -             std::copy(data_.begin(), data_.begin() + bytes_transferred, buf->begin());    -             io_work_service.post(boost::bind(&session::on_receive   -                 , shared_from_this(), buf, bytes_transferred));    - -             socket_.async_read_some(boost::asio::buffer(data_),    -                 make_custom_alloc_handler(allocator_,    -                 boost::bind(&session::handle_read,    -                 shared_from_this(),    -                 boost::asio::placeholders::error,    -                 boost::asio::placeholders::bytes_transferred)));    -         }    -     }    - - void handle_write(const boost::system::error_code& error)    -     {    - if (!error)    -         {    -         }    -     }    - - void on_receive(boost::shared_ptr<std::vector<char> > buffers   -         , size_t bytes_transferred)    -     {    - char* data_stream = &(*buffers->begin());    - // in here finish the work.    -         std::cout << "receive :" << bytes_transferred << " bytes." <<    - "message :" << data_stream << std::endl;    -     }    - - private:    - // The io_service used to finish the work.    -     boost::asio::io_service& io_work_service;    - - // The socket used to communicate with the client.    -     tcp::socket socket_;    - - // Buffer used to store data received from the client.    -     boost::array<char, 1024> data_;    - - // The allocator to use for handler-based custom memory allocation.    -     handler_allocator allocator_;    - };    - - typedef boost::shared_ptr<session> session_ptr;    - - class server    - {    - public:    -     server(short port, std::size_t io_service_pool_size)    -         : io_service_pool_(io_service_pool_size)    -         , io_service_work_pool_(io_service_pool_size)    -         , acceptor_(io_service_pool_.get_io_service(), tcp::endpoint(tcp::v4(), port))    -     {    -         session_ptr new_session(new session(io_service_work_pool_.get_io_service()   -             , io_service_pool_.get_io_service()));    -         acceptor_.async_accept(new_session->socket(),    -             boost::bind(&server::handle_accept, this, new_session,    -             boost::asio::placeholders::error));    -     }    - - void handle_accept(session_ptr new_session,    - const boost::system::error_code& error)    -     {    - if (!error)    -         {    -             new_session->start();    -             new_session.reset(new session(io_service_work_pool_.get_io_service()   -                 , io_service_pool_.get_io_service()));    -             acceptor_.async_accept(new_session->socket(),    -                 boost::bind(&server::handle_accept, this, new_session,    -                 boost::asio::placeholders::error));    -         }    -     }    - - void run()    -     {    -         io_thread_.reset(new boost::thread(boost::bind(&io_service_pool::run   -             , &io_service_pool_)));    -         work_thread_.reset(new boost::thread(boost::bind(&io_service_pool::run   -             , &io_service_work_pool_)));    -     }    - - void stop()    -     {    -         io_service_pool_.stop();    -         io_service_work_pool_.stop();    - -         io_thread_->join();    -         work_thread_->join();    -     }    - - private:    -     boost::shared_ptr<boost::thread> io_thread_;    -     boost::shared_ptr<boost::thread> work_thread_;    -     io_service_pool io_service_pool_;    -     io_service_pool io_service_work_pool_;    -     tcp::acceptor acceptor_;    - };    - - int main(int argc, char* argv[])    - {    - try    -     {    - if (argc != 2)    -         {    -             std::cerr << "Usage: server <port>/n";    - return 1;    -         }    - - using namespace std; // For atoi.    -         server s(atoi(argv[1]), 10);    - -         s.run();    - -         getchar();    - -         s.stop();    -     }    - catch (std::exception& e)    -     {    -         std::cerr << "Exception: " << e.what() << "/n";    -     }    - - return 0;    - }    -
TypeScript
UTF-8
324
4.0625
4
[]
no_license
/** * 数组中每一项都应该是输入的 value 的类型 * @param length * @param value * @returns */ function createArray<T>(length: number, value: T): Array<T> { let result: T[] = []; for (let i = 0; i < length; i++) { result[i] = value; } return result; } createArray<string>(3, "x");
Java
UTF-8
1,735
2.859375
3
[]
no_license
package models; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Objects; public class Cohort { private int cohort_id; private String name; private String module; private Timestamp startDate; private Timestamp endDate; public Cohort( String name, String module, Timestamp startDate, Timestamp endDate) { this.cohort_id = cohort_id; this.name = name; this.module = module; this.startDate = startDate; this.endDate = endDate; } public void setId(int id) { this.cohort_id = cohort_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getModule() { return module; } public void setModule(String module) { this.module = module; } public Timestamp getStartDate() { return startDate; } public void setStartDate(Timestamp startDate) { this.startDate = startDate; } public Timestamp getEndDate() { return endDate; } public void setEndDate(Timestamp endDate) { this.endDate = endDate; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Cohort)) return false; Cohort cohort = (Cohort) o; return getName().equals(cohort.getName()) && getModule().equals(cohort.getModule()) && getStartDate().equals(cohort.getStartDate()) && getEndDate().equals(cohort.getEndDate()); } @Override public int hashCode() { return Objects.hash(getName(), getModule(), getStartDate(), getEndDate()); } }
C++
UTF-8
8,562
2.546875
3
[]
no_license
#include "Light.h" #include "Cube.h" #include <glm/gtc/matrix_transform.inl> //BAD!! NEVER statically INITIALIZE GLEW STUFF!!! GLEW INIT WILL NOT BE CALLED AT THIS TIME!!! //Shader* Light::defaultShader = new Shader("src/Shaders/Light_And_Shadow/VertexLight.vs", "src/Shaders/Light_And_Shadow/FragmentLight.fs"); void Light::apply_to(Shader* s) const { glUniform3f(glGetUniformLocation(s->Program, "lightColor"), lightColor.x, lightColor.y, lightColor.z); glm::vec3 o_pos = object->getPosition(); glUniform3f(glGetUniformLocation(s->Program, "lightPosition"), o_pos.x, o_pos.y, o_pos.z); glUniform1f(glGetUniformLocation(s->Program, "farPlane"), far); } Shader* Light::renderShadow(std::vector<Shape*> shapes, GLFWwindow* window) { GLfloat aspect = (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT; GLfloat near = 0.1f; glm::mat4 shadowProj = glm::perspective(glm::radians(90.f), aspect, near, far); std::vector<glm::mat4> shadowTransforms; shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3(-1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, 1.0, 0.0), glm::vec3(0.0, 0.0, 1.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, -1.0, 0.0), glm::vec3(0.0, 0.0, -1.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, 0.0, 1.0), glm::vec3(0.0, -1.0, 0.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, 0.0, -1.0), glm::vec3(0.0, -1.0, 0.0))); // 1. Render scene to depth cubemap glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); glClear(GL_DEPTH_BUFFER_BIT); depthShader->Use(); for (GLuint i = 0; i < 6; ++i) glUniformMatrix4fv(glGetUniformLocation(depthShader->Program, ("shadowMatrices[" + std::to_string(i) + "]").c_str()), 1, GL_FALSE, glm::value_ptr(shadowTransforms[i])); glUniform1f(glGetUniformLocation(depthShader->Program, "farPlane"), far); glUniform3fv(glGetUniformLocation(depthShader->Program, "lightPos"), 1, &getPosition()[0]); for (auto& s : shapes) { glm::mat4 model; model = glm::translate(model, s->getPosition()); model = glm::rotate(model, s->rotation_angle, s->rotation_axis); //TODO scale glUniformMatrix4fv(glGetUniformLocation(depthShader->Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glBindVertexArray(s->VAO); glDrawArrays(GL_TRIANGLES, 0, s->getVertices()->size()); glBindVertexArray(0); } glBindFramebuffer(GL_FRAMEBUFFER, 0); //glfwgetwindowsize access violation -> why?! glViewport(0, 0, 800, 600); return depthShader; } GLuint Light::renderShadowVSM(std::vector<Shape*> shapes, GLFWwindow* window) { GLfloat aspect = (GLfloat)SHADOW_WIDTH / (GLfloat)SHADOW_HEIGHT; GLfloat near = 0.1f; glm::mat4 shadowProj = glm::perspective(glm::radians(90.f), aspect, near, far); std::vector<glm::mat4> shadowTransforms; shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3(-1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, 1.0, 0.0), glm::vec3(0.0, 0.0, 1.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, -1.0, 0.0), glm::vec3(0.0, 0.0, -1.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, 0.0, 1.0), glm::vec3(0.0, -1.0, 0.0))); shadowTransforms.push_back(shadowProj * glm::lookAt(getPosition(), getPosition() + glm::vec3( 0.0, 0.0, -1.0), glm::vec3(0.0, -1.0, 0.0))); // 1. Render scene to depth cubemap glViewport(0, 0, SHADOW_WIDTH, SHADOW_HEIGHT); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBOVSM); glClearColor(1.f, 0.f, 0.f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); depthShaderVSM->Use(); for (GLuint i = 0; i < 6; ++i) glUniformMatrix4fv(glGetUniformLocation(depthShaderVSM->Program, ("shadowMatrices[" + std::to_string(i) + "]").c_str()), 1, GL_FALSE, glm::value_ptr(shadowTransforms[i])); glUniform1f(glGetUniformLocation(depthShaderVSM->Program, "farPlane"), far); glUniform3fv(glGetUniformLocation(depthShaderVSM->Program, "lightPos"), 1, &getPosition()[0]); for (auto& s : shapes) { glm::mat4 model; model = glm::translate(model, s->getPosition()); model = glm::rotate(model, s->rotation_angle, s->rotation_axis); //TODO scale glUniformMatrix4fv(glGetUniformLocation(depthShaderVSM->Program, "model"), 1, GL_FALSE, glm::value_ptr(model)); glBindVertexArray(s->VAO); glDrawArrays(GL_TRIANGLES, 0, s->getVertices()->size()); glBindVertexArray(0); } glBindFramebuffer(GL_FRAMEBUFFER, 0); glViewport(0, 0, 800, 600); return depthCubeMapVSM; } void Light::update(GLfloat deltaTime) { } void Light::render() { // Don't forget to 'use' the corresponding shader program first (to set the uniform) shader->Use(); glUniform3f(glGetUniformLocation(shader->Program, "lightColor"), lightColor.x, lightColor.y, lightColor.z); // Also set light's color (white) object->render(); } Light::Light(Shader* s, glm::vec3 position, GLfloat width, GLfloat height, GLfloat depth) { lightColor = glm::vec3(1.f, 1.f, 1.f); shader = s; depthShader = new Shader( "src/Shaders/Light_And_Shadow/pointShadow.vs", "src/Shaders/Light_And_Shadow/pointShadow.fs", "src/Shaders/Light_And_Shadow/pointShadow.gs"); depthShaderVSM = new Shader( "src/Shaders/Light_And_Shadow/pointShadow.vs", "src/Shaders/Light_And_Shadow/pointShadowVSM.fs", "src/Shaders/Light_And_Shadow/pointShadow.gs"); object = new Cube(shader, position, width, height, depth); //stuff for shadow glGenTextures(1, &depthCubeMap); glGenTextures(1, &depthCubeMapVSM); glGenFramebuffers(1, &depthMapFBO); glGenFramebuffers(1, &depthMapFBOVSM); //-------------------------------------------------------VSM shadow glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubeMapVSM); for (int i = 0; i < 6; ++i) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RG32F, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, nullptr); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBOVSM); //attach depthCubeMap (texture) to the framebuffer so it gets written glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, depthCubeMapVSM, 0); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Framebuffer not complete!" << std::endl; //glDrawBuffer(GL_COLOR_ATTACHMENT0); //glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0); //-------------------------------------------------------normal shadow glBindTexture(GL_TEXTURE_CUBE_MAP, depthCubeMap); for (int i = 0; i < 6; ++i) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT, SHADOW_WIDTH, SHADOW_HEIGHT, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO); //attach depthCubeMap (texture) to the framebuffer so it gets written glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, depthCubeMap, 0); //tell opengl to not render to a color buffer! (we only need the depth values) glDrawBuffer(GL_NONE); glReadBuffer(GL_NONE); glBindFramebuffer(GL_FRAMEBUFFER, 0); } Light::~Light() { //delete object; }
C++
UTF-8
3,101
2.546875
3
[]
no_license
/** * @file Plugin.hpp * @author Ludvig Arlebrink * @date 9/27/2018 */ #pragma once #include "BaseTypes.hpp" #include "CoreAPI.hpp" #include "Status.hpp" #include <string> #ifdef _WIN32 #include <Windows.h> #elif __linux__ // @todo Linux implementation. #endif // _WIN32 namespace gdt { namespace core { /** * @brief Wrapper for dll plugin. */ class CORE_API CPlugin final { public: /** * @brief Default constructor. */ CPlugin(); CPlugin(const CPlugin&) = delete; /** * @brief Move constructor. * @other Source. */ CPlugin(CPlugin&& other) noexcept; /** * @brief Load a plugin. * @pluginFilepath Filepath to plugin. */ explicit CPlugin(const std::string& pluginFilepath); /** * @brief Destructor. */ ~CPlugin(); void operator=(const CPlugin&) = delete; /** * @brief Call a c function in the plugin without no params or return type. * @param functionName Name of the function to call. */ void callFunction(const std::string& functionName); /** * @brief Call a c function in the plugin without no params or return type. * @param functionName Name of the function to call. * @param param User pointer. */ void callFunction(const std::string& functionName, void* param); /** * @brief Get a string of errors. * @return String of errors. * @note Only works in debug mode. * * Check 'EStatus' by calling 'getStatus'. If EStatus is equals to 'Failure', call this class to get more information. */ std::string getErrorString() const; /** * @brief Check if everything regarding shader compelation went right. * @return 'Success' if everything went right. * * Call 'getErrorString' to get more information about the errors. */ EStatus getStatus() const; /** * @brief Load a plugin. * @pluginFilepath Filepath to plugin. */ void loadPlugin(const std::string& pluginFilepath); /** * @brief Reload the plugin. */ void reloadPlugin(); /** * @brief Unload the plugin. */ void unloadPlugin(); private: bool m_pluginIsLoaded; EStatus m_status; #ifdef GDT_DEBUG || GDT_EDITOR std::string m_errorString; #endif // GDT_DEBUG || GDT_EDITOR std::string m_pluginFilepath; #ifdef _WIN32 HINSTANCE m_pPlugin; #elif __linux__ void* m_pPlugin; #endif // _WIN32 }; } }
Python
UTF-8
4,926
3.515625
4
[]
no_license
""" EXTERNAL LIBRARIES """ import sys import numpy as np import random import matplotlib.pyplot as plt import math """ INTERNAL UTIL LIBRARIES """ # Add parent directory to the sys path sys.path.append('../') # Import any python modules from parent directory from utils.auxfunctions import plot_decision_boundary """ One-hidden-layer networks can represent nonconvex, disjoint regions. Weiland and Leighton provided an example of a nonconvex region that can be recognized by a single-hidden-layer ntwork. The example creates a "C" shaped region, which is a nonconvex decision region. """ class SingleHiddenLayerNetwork: def __init__(self, numInputs, hiddenLayerSize, randomize=True, bias=True): """ Create the single hidden network with the above specifications to test capability of a single hidden layer network. """ # Set parameters self.numInputs = numInputs self.hiddenLayerSize = hiddenLayerSize self.bias = bias # Set up weights for the initial hidden layer if bias: inputSize = numInputs + 1 else: inputsize = numInputs if randomize: self.w1 = np.random.rand(hiddenLayerSize, inputSize) * 2.0 - 1.0 else: self.w1 = np.zeros((hiddenLayerSize, inputSize)) # Set up weights for final layer if bias: inputSize = hiddenLayerSize + 1 else: inputsize = hiddenLayerSize if randomize: self.w2 = np.random.rand(1, inputSize) * 2.0 - 10 else: self.w3 = np.zeros((1, inputSize)) def evaluateHidden(self, inputs): """ Evaluate the output of the hidden layer in the network given the inputs. """ if self.bias: inputs = np.concatenate((inputs, np.ones((inputs.shape[0], 1))), axis=1) output = np.dot(inputs, self.w1.T) # Linear thresholding activation output[output <= 0] = 0 output[output > 0] = 1 return output def evaluateFinal(self, inputs): """ Evaluate the output of the final layer in the network given the inputs. """ # Get hidden layer output if self.bias: inputs = np.concatenate((inputs, np.ones((inputs.shape[0], 1))), axis=1) hidden_output = np.dot(inputs, self.w1.T) # Linear thresholding activation hidden_output[hidden_output <= 0] = 0 hidden_output[hidden_output > 0] = 1 # Get final output if self.bias: hidden_output = np.concatenate((hidden_output, np.ones((hidden_output.shape[0], 1))), axis=1) output = np.dot(hidden_output, self.w2.T) # Linear thresholding activation output[output <= 0] = 0 output[output > 0] = 1 return output if __name__ == '__main__': """ Testing the decision boundaries for the 'C' shaped region example network. """ shln = SingleHiddenLayerNetwork(2, 10, randomize=False, bias=True) # Create pyplot fig, ax = plt.subplots(1, 1) fig.suptitle('One-Hidden-Layer Networks Can Represent Nonconvex Regions', fontsize=18) # Set hard-coded weights to form the example decision boundary shln.w1 = np.array([ [1, 0, -0.2], [-1, 0, 0.4], [1, 0, -0.6], [-1, 0, 0.8], [0, 1, -0.1], [0, -1, 0.3], [0, -1, 0.4], [0, 1, -0.6], [0, 1, -0.7], [0, -1, 0.9] ]) shln.w2 = np.array([ [2, 1, 0.5, 2, 2, 1, 0.3, 0.3, 1, 2, -8.7] ]) # Plot final layer output plot_decision_boundary(shln.evaluateFinal, 0, [0.0, 1.0, 0.0, 1.0], ax, steppingSize=0.01) # Add title to ax ax.set_title('C-Shaped Region Formed by One-Hidden Layer Net') # Plot the graph figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.show() """ Testing if a one-hidden-layer network can define disjoint regions. """ shln = SingleHiddenLayerNetwork(2, 3, randomize=False, bias=True) # Create pyplot fix, ax = plt.subplots(1, 1) fig.suptitle('One-Hidden-Layer Networks Can Represent Disjoint Regions', fontsize=18) # Set hard-coded weights to form the example decision boundary shln.w1 = np.array([ [0, -1, 0], [1, 1, -1], [-1, 1, 0] ]) shln.w2 = np.array([ [1, 1, 1, -1.9] ]) # Plot final layer output plot_decision_boundary(shln.evaluateFinal, 0, [0.0, 1.0, 0.0, 1.0], ax, steppingSize=0.01) # Add title to ax ax.set_title('Disjoint Region Formed by One-Hidden Layer Net') # Plot the graph figManager = plt.get_current_fig_manager() figManager.window.showMaximized() plt.show()
C++
UTF-8
1,271
2.5625
3
[]
no_license
#ifndef motion_h #define motion_h #include <Servo.h> #include <Octosnake.h> class Motion{ public: Motion (int hip1, int knee1, int hip2, int knee2, int hip3, int knee3, int hip4, int knee4); void init(); void runs(float steps, int period); void walk(float steps, int period); void back(float steps, int period); void turnL(float steps, int period); void turnR(float steps, int period); void dance(float steps, int period); void upDown(float steps, int period); void pushUp(float steps, int period); void hello(); void home(); void zero(); void setServo(int id, float target); void reverseServo(int id); float getServo(int id); void moveServos(int time, float target[8]); private: Oscillator oscillator[8]; Servo servo[8]; int board_pins[8]; int trim[8]; bool reverse[8]; unsigned long _init_time; unsigned long _final_time; unsigned long _partial_time; float _increment[8]; float _servo_position[8]; int angToUsec(float value); void execute(float steps, int period[8], int amplitude[8], int offset[8], int phase[8]); protected: int pin0; int pin1; int pin2; int pin3; int pin4; int pin5; int pin6; int pin7; }; #endif
Python
UTF-8
1,551
2.96875
3
[ "MIT" ]
permissive
# coding: utf-8 # In[6]: import os import string import nltk from nltk import word_tokenize,WordNetLemmatizer,PorterStemmer,RegexpTokenizer from collections import defaultdict from nltk.util import ngrams # In[5]: topic_path = '' ref_path = '' regex= RegexpTokenizer(r'\w+') # In[14]: def abstract(topic,summary): sentences = [] for i in topic: doc_string = i doc_sentences = doc_string.split('.') for d in range(len(doc_sentences)): doc_sentences[d] = doc_sentences[d].lower() sentences.extend(doc_sentences) doc_ngrams = [] for i in sentences: tokens = regex.tokenize(i) ngram = list(ngrams(tokens, 1)) doc_ngrams.extend(ngram) summary = summary[0:len(summary)] reference_sentences = summary.split(".") reference_ngrams = [] for i in reference_sentences: tokens = regex.tokenize(i) ngram = list(ngrams(tokens, 1)) reference_ngrams.extend(ngram) count = 0 for i in reference_ngrams: if i in doc_ngrams: count += 1 abstract_val.append(count/len(reference_ngrams)) # In[15]: doc_files = os.listdir(topic_path) abstract_val = [] for f in doc_files: doc_file = open(topic_path + '/'+ f, 'r', encoding='utf-8') ref_file = open(ref_path + '/'+ f, 'r', encoding='utf-8') doc_string = doc_file.read() docs = doc_string.split("\n\n") ref_string = ref_file.read() abstract(docs,ref_string) print(sum(abstract_val)/len(abstract_val))
Python
UTF-8
1,117
2.625
3
[]
no_license
""" # 字符串整理 通过 `cat /etc/services` , 我们可以列举 linux 常见的网络端口 但是这个文件里的内容, 对于机器是易读, 但对于人而言却排版有点乱 现在, 我们需要把该文件内容重新整理, 使其整整齐齐, 一目了然 整理的需求如下: 1. 对齐所有的行列 2. 不使用 tab, 全使用空格 3. 两列之间的空格至少为4个 eg: 整理前[L193,L199] klogin 543/tcp # Kerberized `rlogin' (v5) kshell 544/tcp krcmd # Kerberized `rsh' (v5) dhcpv6-client 546/tcp klogin 543/tcp # Kerberized `rlogin' (v5) dhcpv6-client 546/udp dhcpv6-server 547/tcp dhcpv6-server 547/udp afpovertcp 548/tcp # AFP over TCP ==> 整理后 klogin 543/tcp # Kerberized `rlogin' (v5) kshell 544/tcp krcmd # Kerberized `rsh' (v5) dhcpv6-client 546/tcp dhcpv6-client 546/udp dhcpv6-server 547/tcp dhcpv6-server 547/udp afpovertcp 548/tcp # AFP over TCP # refer: level-0初级/t12_linux_常用网络端口.md # 请在下方实现你的代码, 并且提出pull-request """
Swift
UTF-8
7,050
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "Swift-exception" ]
permissive
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import ArgumentParser import Foundation #if os(Windows) import WinSDK #endif fileprivate func withTemporaryFile<T>(contents: [UInt8], body: (URL) throws -> T) throws -> T { var tempFileURL = FileManager.default.temporaryDirectory tempFileURL.appendPathComponent("swift-parser-cli-\(UUID().uuidString).swift") try Data(contents).write(to: tempFileURL) defer { try? FileManager.default.removeItem(at: tempFileURL) } return try body(tempFileURL) } struct Reduce: ParsableCommand { static var configuration = CommandConfiguration( commandName: "reduce", abstract: "Reduce a test case that crashes the parser or fails to round-trip to a smaller test case that still reproduces the issue" ) @Argument(help: "The test case that should be reduced; if omitted, use stdin") var sourceFile: String? @Flag(name: .long, help: "Perform sequence folding with the standard operators") var foldSequences: Bool = false @Flag(help: "Print status updates while reducing the test case") var verbose: Bool = false enum Error: Swift.Error, CustomStringConvertible { case testDoesNotFail public var description: String { switch self { case .testDoesNotFail: return "Source file passed to reduce subcommand does not fail to roundtrip" } } } enum ProcessExit { /// The process finished successfully. case success /// The process finished with an exit code of 1, indicating that it failed but did not crash case failure /// Running the process didn't finish in a specified timeout case timeout /// The process exited with an exit code that was neither 0 nor 1 and might have been a crash. case potentialCrash } /// Invoke `swift-parser-cli verify-round-trip` with the same arguments as this `reduce` subcommand. /// Returns the exit code of the invocation. private func runVerifyRoundTripInSeparateProcess(source: [UInt8]) throws -> ProcessExit { #if os(iOS) || os(tvOS) || os(watchOS) // We cannot launch a new process on iOS-like platforms. // Default to running verification in-process. // Honestly, this isn't very important because you can't launch swift-parser-cli // on iOS anyway but this fixes a compilation error of the pacakge on iOS. return try runVerifyRoundTripInCurrentProcess(source: source) ? ProcessExit.success : ProcessExit.potentialCrash #else return try withTemporaryFile(contents: source) { tempFileURL in let process = Process() process.executableURL = URL(fileURLWithPath: ProcessInfo.processInfo.arguments[0]) process.arguments = [ "verify-round-trip", tempFileURL.path, ] if foldSequences { process.arguments! += ["--fold-sequences"] } let sema = DispatchSemaphore(value: 0) process.standardOutput = FileHandle.nullDevice process.standardError = FileHandle.nullDevice process.terminationHandler = { process in sema.signal() } try process.run() if sema.wait(timeout: DispatchTime.now() + .seconds(2)) == .timedOut { #if os(Windows) _ = TerminateProcess(process.processHandle, 0) #else kill(pid_t(process.processIdentifier), SIGKILL) #endif return .timeout } switch process.terminationStatus { case 0: return .success case 1: return .potentialCrash default: return .potentialCrash } } #endif } /// Runs the `verify-round-trip` subcommand in process. /// Returns `true` if `source` round-tripped successfully, `false` otherwise. private func runVerifyRoundTripInCurrentProcess(source: [UInt8]) throws -> Bool { do { try source.withUnsafeBufferPointer { sourceBuffer in try VerifyRoundTrip.run( source: sourceBuffer, foldSequences: foldSequences ) } } catch { return false } return true } private func reduce(source: [UInt8], testPasses: ([UInt8]) throws -> Bool) throws -> [UInt8] { var reduced = source var chunkSize = source.count / 4 while chunkSize > 0 { if chunkSize < reduced.count / 20 { // The chunk sizes are really tiny compared to the source file. Looks like we aren't making any progress reducing. Abort. break } if verbose { printerr("Current source size \(reduced.count), reducing with chunk size \(chunkSize)") } reduced = try reduceImpl(source: reduced, chunkSize: chunkSize, testPasses: testPasses) chunkSize = min( reduced.count / 2, chunkSize / 2 ) } return reduced } /// Reduces a test case with `source` by iteratively attempting to remove `chunkSize` characters - ie. removing the chunk if `testPasses` returns `false`. private func reduceImpl(source: [UInt8], chunkSize: Int, testPasses: ([UInt8]) throws -> Bool) rethrows -> [UInt8] { var reduced: [UInt8] = [] // Characters that stil need to be checked whether they can be removed. var remaining = source while !remaining.isEmpty { let index = remaining.index(remaining.startIndex, offsetBy: chunkSize, limitedBy: remaining.endIndex) ?? remaining.endIndex let testChunk = [UInt8](remaining[..<index]) remaining = [UInt8](remaining[index...]) if try testPasses(reduced + remaining) { // The test doesn't fail anymore if we remove testChunk. Add it again. reduced.append(contentsOf: testChunk) } } return reduced } func run() throws { let source = try getContentsOfSourceFile(at: sourceFile) let testPasses: ([UInt8]) throws -> Bool switch try runVerifyRoundTripInSeparateProcess(source: source) { case .success: throw Error.testDoesNotFail case .failure: // Round-tripping did not crash. We can run the checks in-process testPasses = self.runVerifyRoundTripInCurrentProcess case .potentialCrash, .timeout: // Invoking verify-round-trip might have crashed. We don’t want to crash this process, so run in a separate process. testPasses = { try self.runVerifyRoundTripInSeparateProcess(source: $0) == .success } } var checks = 0 let reduced = try reduce(source: source) { reducedSource in checks += 1 return try testPasses(reducedSource) } if verbose { printerr("Reduced from \(source.count) to \(reduced.count) characters in \(checks) iterations") } FileHandle.standardOutput.write(Data(reduced)) } }
C++
UTF-8
688
2.78125
3
[]
no_license
#include <iostream> #include <string> #include <queue> #include <vector> #include <fstream> #include <cmath> #include <sstream> #include <bits/stdc++.h> #include <climits> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); string instr; int four = 0,seven = 0; cin >> instr; int len = instr.size(); for(int i = 0; i<len ;i++) { if(instr[i] == '4') { four++; } else if(instr[i]== '7') { seven++; } } if(four == 0 && seven == 0) { cout << -1 << endl; } else if(four >= seven) { cout << 4 << endl; } else { cout << 7 << endl; } }
Java
UTF-8
387
2.796875
3
[]
no_license
class ManejoDeVariables{ public static void main(String[] args) { int a=0; int b=20; double c=30.3; //realizamos alguna modificación en el archivo para que se suba el branch double d=40.3; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } }
JavaScript
UTF-8
804
2.734375
3
[]
no_license
function buscar() { var nombre = $("#txtId").val(); $.ajax({ type: 'POST', url: 'buscadordistributor.do', data: { dato: nombre }, success: function (result) { $("#resultado").html(result); } }); } function validateFormIndex(){ var inputIdDistributor = document.getElementById("txtId").value; var selectMarket = document.getElementById("FormControlMarket").value; var checkedTerms = document.getElementById("CheckTermsAndConditions").checked; if (inputIdDistributor=="" || selectMarket == "") { alert("Debes completar todos los campos."); return false; }else if(checkedTerms==false ){ alert("Debes aceptar los términos y condiciones."); return false; } }
Markdown
UTF-8
2,618
2.859375
3
[ "MIT" ]
permissive
# PHYS220 CW 5 **Author(s):** Aaron Grisez, Preston Kamada_ [![Build Status](https://travis-ci.org/chapman-phys220-2016f/cw-05-YOURNAME.svg?branch=master)](https://travis-ci.org/chapman-phys220-2016f/cw-05-YOURNAME) **Due date:** 2016/10/04 ## Specification **Note: As of this assignment, we will be switching to Python3 officially.** 1. Using a PocketLab in class, take the following set of data: * Turn on 2 graphs: 3-axis acceleration, and altitude * By holding the device with a rigid orientation (z-axis aligned with vertical - why is this advisable?), take a recorded set of data while moving the device along an interesting path. As a suggestion, try a vertical helix. Be sure to keep your motions smooth, and changing slowly enough that the data points are being sampled fast enough to resolve the acceleration data. * Email yourself the dataset, which will arrive as a ```.csv``` file. 1. Read up on the ```pandas``` extension to ```numpy``` [here](http://slides.com/profdressel/numpy-and-pandas-overview). Try out everything in an ```ipython``` interpreter to make sure you understand what is going on. Discuss with your teammates. 1. Write a python module ```kinematics.py``` that integrates your acceleration data to produce a 3D position trajectory of the device during your experiment. Remember that $\vec{v}(t) = \int \vec{a}(t)dt$ and $\vec{x}(t) = \int \vec{v}(t)dt$ analytically. Explain what you have to do numerically to perform these integrations with the actual collected data. 1. Create a Jupyter notebook ```cw5.ipynb``` that uses ```pandas``` to plot the data sets you have taken using ```matplotlib```. Import ```kinematics.py``` and plot your reconstructed trajectory for the device. Compare the z-component of this trajectory to the collected altitude data. Do they agree? Discuss your findings and conclusions in your notebook. Pro-tip: using git to manage conflicts on Jupyter notebooks is a pain. I recommend delegating one person from your group to edit the notebook, to avoid merge conflicts. ## Assessment Analyze in this section what you found useful about this assignment in your own words. Include any lingering questions or comments that you may have. I really enjoyed using the PocketLab device in class. I understood what was asked of me more because it was experimental. ## Honor Pledge I pledge that all the work in this repository is my own with only the following exceptions: * Content of starter files supplied by the instructor; * Code borrowed from another source, documented with correct attribution in the code and summarized here. Signed, Aaron Grisez, Preston S Kamada
Markdown
UTF-8
9,252
2.609375
3
[]
permissive
# SNMP How-To ## Simulate SNMP devices SNMP is a protocol for gathering metrics from network devices, but automated testing of the integration would not be practical nor reliable if we used actual devices. Our approach is to use a simulated SNMP device that responds to SNMP queries using [simulation data](./sim-format.md). This simulated device is brought up as a Docker container when starting the SNMP test environment using: ```bash ddev env start snmp [...] ``` ## Test SNMP profiles locally Once the environment is up and running, you can modify the instance configuration to test profiles that support simulated metrics. The following is an example of an instance configured to use the Cisco Nexus profile. ```yaml init_config: profiles: cisco_nexus: definition_file: cisco-nexus.yaml instances: - community_string: cisco_nexus # (1.) ip_address: <IP_ADDRESS_OF_SNMP_CONTAINER> # (2.) profile: cisco_nexus name: localhost port: 1161 ``` 1. The `community_string` must match the corresponding device `.snmprec` file name. 2. To find the IP address of the SNMP container, run: ```bash docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' dd-snmp ``` ## Run SNMP queries With the test environment is up and running, we can issue SNMP queries to the simulated device using a command line SNMP client. ### Prerequisites Make sure you have the Net-SNMP tools installed on your machine. These should come pre-installed by default on Linux and macOS. If necessary, you can download them on the [Net-SNMP website](http://net-snmp.sourceforge.net/download.html). ### Available commands The Net-SNMP tools provide a number of commands to interact with SNMP devices. The most commonly used commands are: - `snmpget`: to issue an SNMP GET query. - `snmpgetnext`: to issue an SNMP GETNEXT query. - `snmpwalk`: to query an entire OID sub-tree at once. - `snmptable`: to query rows in an SNMP table. ### Examples #### GET query To query a specific OID from a device, we can use the `snmpget` command. For example, the following command will query `sysDescr` OID of an SNMP device, which returns its human-readable description: ```console $ snmpget -v 2c -c public -IR 127.0.0.1:1161 system.sysDescr.0 SNMPv2-MIB::sysDescr.0 = STRING: Linux 41ba948911b9 4.9.87-linuxkit-aufs #1 SMP Wed Mar 14 15:12:16 UTC 2018 x86_64 SNMPv2-MIB::sysORUpTime.1 = Timeticks: (9) 0:00:00.09 ``` Let's break this command down: - `snmpget`: this command sends an SNMP GET request, and can be used to query the value of an OID. Here, we are requesting the `system.sysDescr.0` OID. - `-v 2c`: instructs your SNMP client to send the request using SNMP version 2c. See [SNMP Versions](#snmp-versions). - `-c public`: instructs the SNMP client to send the community string `public` along with our request. (This is a form of authentication provided by SNMP v2. See [SNMP Versions](#snmp-versions).) - `127.0.0.1:1161`: this is the host and port where the simulated SNMP agent is available at. (Confirm the port used by the ddev environment by inspecting the Docker port mapping via `$ docker ps`.) - `system.sysDescr.0`: this is the OID that the client should request. In practice this can refer to either a fully-resolved OID (e.g. `1.3.6.1.4.1[...]`), or a label (e.g. `sysDescr.0`). - `-IR`: this option allows us to use labels for OIDs that aren't in the generic `1.3.6.1.2.1.*` sub-tree (see: [The OID tree](./introduction.md#the-oid-tree)). TL;DR: always use this option when working with OIDs coming from vendor-specific MIBs. !!! tip If the above command fails, try using the explicit OID like so: ```console $ snmpget -v 2c -c public -IR 127.0.0.1:1161 iso.3.6.1.2.1.1.1.0 ``` #### Table query For tables, use the `snmptable` command, which will output the rows in the table in a tabular format. Its arguments and options are similar to `snmpget`. ```console $ snmptable -v 2c -c public -IR -Os 127.0.0.1:1161 hrStorageTable SNMP table: hrStorageTable hrStorageIndex hrStorageType hrStorageDescr hrStorageAllocationUnits hrStorageSize hrStorageUsed hrStorageAllocationFailures 1 hrStorageRam Physical memory 1024 Bytes 2046940 1969964 ? 3 hrStorageVirtualMemory Virtual memory 1024 Bytes 3095512 1969964 ? 6 hrStorageOther Memory buffers 1024 Bytes 2046940 73580 ? 7 hrStorageOther Cached memory 1024 Bytes 1577648 1577648 ? 8 hrStorageOther Shared memory 1024 Bytes 2940 2940 ? 10 hrStorageVirtualMemory Swap space 1024 Bytes 1048572 0 ? 33 hrStorageFixedDisk /dev 4096 Bytes 16384 0 ? 36 hrStorageFixedDisk /sys/fs/cgroup 4096 Bytes 255867 0 ? 52 hrStorageFixedDisk /etc/resolv.conf 4096 Bytes 16448139 6493059 ? 53 hrStorageFixedDisk /etc/hostname 4096 Bytes 16448139 6493059 ? 54 hrStorageFixedDisk /etc/hosts 4096 Bytes 16448139 6493059 ? 55 hrStorageFixedDisk /dev/shm 4096 Bytes 16384 0 ? 61 hrStorageFixedDisk /proc/kcore 4096 Bytes 16384 0 ? 62 hrStorageFixedDisk /proc/keys 4096 Bytes 16384 0 ? 63 hrStorageFixedDisk /proc/timer_list 4096 Bytes 16384 0 ? 64 hrStorageFixedDisk /proc/sched_debug 4096 Bytes 16384 0 ? 65 hrStorageFixedDisk /sys/firmware 4096 Bytes 255867 0 ? ``` (In this case, we added the `-Os` option which prints only the last symbolic element and reduces the output of `hrStorageTypes`.) ## Generate table simulation data If you'd like to generate [simulation data for tables](./sim-format.md#tables) automatically, you can use the [`mib2dev.py`](http://snmplabs.com/snmpsim/documentation/building-simulation-data.html?highlight=snmpsim-record-mibs#examples) tool shipped with `snmpsim`. (This tool will be renamed as `snmpsim-record-mibs` in the upcoming 1.0 release of the library.) First, install snmpsim: ```bash pip install snmpsim ``` Then run the tool, specifying the MIB with the start and stop OIDs (which can correspond to .e.g the first and last columns in the table respectively). For example: ```bash mib2dev.py --mib-module=<MIB> --start-oid=1.3.6.1.4.1.674.10892.1.400.20 --stop-oid=1.3.6.1.4.1.674.10892.1.600.12 > /path/to/mytable.snmprec ``` ## Find where MIBs are installed on your machine See the [Using and loading MIBs](http://net-snmp.sourceforge.net/wiki/index.php/TUT:Using_and_loading_MIBS) Net-SNMP tutorial. ## Browse locally installed MIBs Since [community resources](./introduction.md#tools-and-resources) that list MIBs and OIDs are best effort, the MIB you are investigating may not be present or may not be available in its the latest version. In that case, you can use the [`snmptranslate`](http://net-snmp.sourceforge.net/tutorial/tutorial-5/commands/snmptranslate.html) CLI tool to output similar information for MIBs installed on your system. This tool is part of Net-SNMP - see [SNMP queries prerequisites](#prerequisites). **Steps** 1. Run `$ snmptranslate -m <MIBNAME> -Tz -On` to get a complete list of OIDs in the `<MIBNAME>` MIB along with their labels. 2. Redirect to a file for nicer formatting as needed. Example: ```console $ snmptranslate -m IF-MIB -Tz -On > out.log $ cat out.log "org" "1.3" "dod" "1.3.6" "internet" "1.3.6.1" "directory" "1.3.6.1.1" "mgmt" "1.3.6.1.2" "mib-2" "1.3.6.1.2.1" "system" "1.3.6.1.2.1.1" "sysDescr" "1.3.6.1.2.1.1.1" "sysObjectID" "1.3.6.1.2.1.1.2" "sysUpTime" "1.3.6.1.2.1.1.3" "sysContact" "1.3.6.1.2.1.1.4" "sysName" "1.3.6.1.2.1.1.5" "sysLocation" "1.3.6.1.2.1.1.6" [...] ``` !!! tip Use the `-M <DIR>` option to specify the directory where `snmptranslate` should look for MIBs. Useful if you want to inspect a MIB you've just downloaded but not moved to the default MIB directory. !!! tip Use `-Tp` for an alternative tree-like formatting.
Shell
UTF-8
902
2.8125
3
[ "Apache-2.0" ]
permissive
# Copyright 2016, Google, Inc. # 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. # include options.sh for all the variables source ./options.sh echo "Deleting Manager(s)" for i in `seq 1 $NUM_MANAGERS` do docker-machine rm -f $PREFIX-manager-$i & done echo "Deleting Workers(s)" for i in `seq 1 $NUM_WORKERS` do docker-machine rm -f $PREFIX-worker-$i & done wait echo "Cluster Deleted"
Markdown
UTF-8
3,031
3.03125
3
[]
no_license
--- title: "Reproducible Data assignment 1" output: html_document: keep_md: yes keep_md: true --- ## Loading and Processing Data ```r Act_Data <- read.csv("activity.csv") Act_Data$date <- as.Date(as.character(Act_Data$date)) library(knitr) ``` ## What is mean total number of steps taken per day? ```r SPD <- aggregate(steps ~ date,data = Act_Data, FUN=sum, na.rm=TRUE) hist(SPD$steps, xlab = "Steps", main = "Total steps per day", col= "red") ``` ![](Reproducible_Data_PA_1_files/figure-html/Histogram of total steps per day-1.png)<!-- --> ```r mean_steps <- mean(SPD$steps) median_steps <- median(SPD$steps) mean_steps ``` ``` ## [1] 10766.19 ``` ```r median_steps ``` ``` ## [1] 10765 ``` ## What is the daily activity pattern ```r SPD_Mean <- aggregate(steps ~ interval,data = Act_Data, FUN=sum, na.rm=TRUE) plot(SPD_Mean$interval, SPD_Mean$steps, type ="l", col = "blue", xlab= "Intervals", ylab= "Total Steps per Interval", main = "Number of Steps per Interval") ``` ![](Reproducible_Data_PA_1_files/figure-html/Number of Steps per Interval-1.png)<!-- --> ```r SPD_Max <- max(SPD_Mean$steps) SPD_Highest <- SPD_Mean$interval[which(SPD_Mean$steps == SPD_Max)] SPD_Highest ``` ``` ## [1] 835 ``` ## Inputing Missing Values ```r SPD_Missing <- sum(is.na(Act_Data)) SPD_Missing ``` ``` ## [1] 2304 ``` ```r SPD_GetMean <- function(interval){ SPD_Mean[SPD_Mean$interval == interval, ]$steps } ``` ```r SPD_New <- Act_Data for (i in 1:nrow(SPD_New)){ if(is.na(SPD_New[i,]$steps)){ SPD_New[i,]$steps <- SPD_GetMean(SPD_New[i,]$interval) } } ``` ```r SPD_Total <- aggregate(steps ~ date,data = Act_Data, sum) hist(SPD_Total$steps,xlab = "Steps", main = "New Total Steps", col= "green") ``` ![](Reproducible_Data_PA_1_files/figure-html/Make a histogramof the total number of steps per day-1.png)<!-- --> ```r SPD_Total_Mean <- mean(SPD_Total$steps) SPD_Total_Meadian <- median(SPD_Total$steps) SPD_Total_Mean ``` ``` ## [1] 10766.19 ``` ```r SPD_Total_Meadian ``` ``` ## [1] 10765 ``` ## Are there any differences in activity patterns between weekdays and weekends? ```r SPD_New$date <- as.Date(strptime(SPD_New$date, format="%Y-%m-%d")) SPD_New$day <- weekdays(SPD_New$date) for (i in 1:nrow(SPD_New)) { if (SPD_New[i,]$day %in% c("Saturday", "Sunday")) { SPD_New[i,]$day <- "weekend" } else{ SPD_New[i,]$day <- "weekday" } } SPD_WW <- aggregate(SPD_New$steps ~ SPD_New$interval + SPD_New$day, SPD_New, mean) ``` ```r names(SPD_WW) <- c("interval", "day", "steps") library(lattice) xyplot(steps ~ interval | day, SPD_WW, type = "l", layout= c(1,2), xlab= "Interval", ylab= "Number of Steps") ``` ![](Reproducible_Data_PA_1_files/figure-html/Make a panal line plot of the 5-minute interval and average steps across all weekdays or weekends-1.png)<!-- -->
Java
UTF-8
243
1.835938
2
[]
no_license
package service1.service; import service1.domain.Message; import service1.domain.MessageAcknowledgement; import rx.Observable; public interface MessageHandlerService { Observable<MessageAcknowledgement> handleMessage(Message message); }
C
UTF-8
5,340
3.203125
3
[ "MIT" ]
permissive
#include <stdlib.h> #include <string.h> #include <homekit/tlv.h> tlv_values_t *tlv_new() { tlv_values_t *values = malloc(sizeof(tlv_values_t)); values->head = NULL; return values; } void tlv_free(tlv_values_t *values) { tlv_t *t = values->head; while (t) { tlv_t *t2 = t; t = t->next; if (t2->value) free(t2->value); free(t2); } free(values); } int tlv_add_value_(tlv_values_t *values, byte type, byte *value, size_t size) { tlv_t *tlv = malloc(sizeof(tlv_t)); tlv->type = type; tlv->size = size; tlv->value = value; tlv->next = NULL; if (!values->head) { values->head = tlv; } else { tlv_t *t = values->head; while (t->next) { t = t->next; } t->next = tlv; } return 0; } int tlv_add_value(tlv_values_t *values, byte type, const byte *value, size_t size) { byte *data = NULL; if (size) { data = malloc(size); memcpy(data, value, size); } return tlv_add_value_(values, type, data, size); } int tlv_add_string_value(tlv_values_t *values, byte type, const char *value) { return tlv_add_value(values, type, (const byte *)value, strlen(value)); } int tlv_add_integer_value(tlv_values_t *values, byte type, size_t size, int value) { byte data[8]; for (size_t i=0; i<size; i++) { data[i] = value & 0xff; value >>= 8; } return tlv_add_value(values, type, data, size); } int tlv_add_tlv_value(tlv_values_t *values, byte type, tlv_values_t *value) { size_t tlv_size = 0; tlv_format(value, NULL, &tlv_size); byte *tlv_data = malloc(tlv_size); int r = tlv_format(value, tlv_data, &tlv_size); if (r) { free(tlv_data); return r; } r = tlv_add_value_(values, type, tlv_data, tlv_size); return r; } tlv_t *tlv_get_value(const tlv_values_t *values, byte type) { tlv_t *t = values->head; while (t) { if (t->type == type) return t; t = t->next; } return NULL; } int tlv_get_integer_value(const tlv_values_t *values, byte type, int def) { tlv_t *t = tlv_get_value(values, type); if (!t) return def; int x = 0; for (int i=t->size-1; i>=0; i--) { x = (x << 8) + t->value[i]; } return x; } // Return a string value. Returns NULL if value does not exist. // Caller is responsible for freeing returned value. char *tlv_get_string_value(const tlv_values_t *values, byte type) { tlv_t *t = tlv_get_value(values, type); if (!t) return NULL; return strndup((char*)t->value, t->size); } // Deserializes a TLV value and returns it. Returns NULL if value does not exist // or incorrect. Caller is responsible for freeing returned value. tlv_values_t *tlv_get_tlv_value(const tlv_values_t *values, byte type) { tlv_t *t = tlv_get_value(values, type); if (!t) return NULL; tlv_values_t *value = tlv_new(); int r = tlv_parse(t->value, t->size, value); if (r) { tlv_free(value); return NULL; } return value; } int tlv_format(const tlv_values_t *values, byte *buffer, size_t *size) { size_t required_size = 0; tlv_t *t = values->head; while (t) { required_size += t->size + 2 * ((t->size + 254) / 255); t = t->next; } if (*size < required_size) { *size = required_size; return -1; } *size = required_size; t = values->head; while (t) { byte *data = t->value; if (!t->size) { buffer[0] = t->type; buffer[1] = 0; buffer += 2; t = t->next; continue; } size_t remaining = t->size; while (remaining) { buffer[0] = t->type; size_t chunk_size = (remaining > 255) ? 255 : remaining; buffer[1] = chunk_size; memcpy(&buffer[2], data, chunk_size); remaining -= chunk_size; buffer += chunk_size + 2; data += chunk_size; } t = t->next; } return 0; } int tlv_parse(const byte *buffer, size_t length, tlv_values_t *values) { size_t i = 0; while (i < length) { byte type = buffer[i]; size_t size = 0; byte *data = NULL; // scan TLVs to accumulate total size of subsequent TLVs with same type (chunked data) size_t j = i; while (j < length && buffer[j] == type && buffer[j+1] == 255) { size_t chunk_size = buffer[j+1]; size += chunk_size; j += chunk_size + 2; } if (j < length && buffer[j] == type) { size_t chunk_size = buffer[j+1]; size += chunk_size; } // allocate memory to hold all pieces of chunked data and copy data there if (size != 0) { data = malloc(size); byte *p = data; size_t remaining = size; while (remaining) { size_t chunk_size = buffer[i+1]; memcpy(p, &buffer[i+2], chunk_size); p += chunk_size; i += chunk_size + 2; remaining -= chunk_size; } } tlv_add_value_(values, type, data, size); } return 0; }
TypeScript
UTF-8
2,798
2.5625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import { I18NContext, I18NSystem, I18NSystemStorageOperations, I18NSystemStorageOperationsCreate, I18NSystemStorageOperationsUpdate } from "@webiny/api-i18n/types"; import { Entity } from "dynamodb-toolbox"; import WebinyError from "@webiny/error"; import defineSystemEntity from "~/definitions/systemEntity"; import defineTable from "~/definitions/table"; import { cleanupItem } from "@webiny/db-dynamodb/utils/cleanup"; interface ConstructorParams { context: I18NContext; } const SORT_KEY = "I18N"; export class SystemStorageOperations implements I18NSystemStorageOperations { private readonly _context: I18NContext; private readonly _entity: Entity<any>; private get partitionKey(): string { const tenant = this._context.tenancy.getCurrentTenant(); if (!tenant) { throw new WebinyError("Tenant missing.", "TENANT_NOT_FOUND"); } return `T#${tenant.id}#SYSTEM`; } public constructor({ context }: ConstructorParams) { this._context = context; const table = defineTable({ context }); this._entity = defineSystemEntity({ context, table }); } public async get(): Promise<I18NSystem> { const keys = { PK: this.partitionKey, SK: SORT_KEY }; try { const result = await this._entity.get(keys); return cleanupItem(this._entity, result?.Item); } catch (ex) { throw new WebinyError( "Could not load system data from the database.", "GET_SYSTEM_ERROR", keys ); } } public async create({ system }: I18NSystemStorageOperationsCreate): Promise<I18NSystem> { const keys = { PK: this.partitionKey, SK: SORT_KEY }; try { await this._entity.put({ ...keys, ...system }); return system; } catch (ex) { throw new WebinyError( "Could not create system data in the database.", "CREATE_SYSTEM_ERROR", keys ); } } public async update({ system }: I18NSystemStorageOperationsUpdate): Promise<I18NSystem> { const keys = { PK: this.partitionKey, SK: SORT_KEY }; try { await this._entity.put({ ...keys, ...system }); return system; } catch (ex) { throw new WebinyError( "Could not update system data in the database.", "UPDATE_VERSION_ERROR", keys ); } } }
PHP
UTF-8
3,154
3.140625
3
[ "MIT" ]
permissive
<?php // Second year Project Artificial Intelligence 2014 // Gerben van der Huizen - 10460748 // Vincent Erich - 10384081 // Michiel Boswijk - 10332553 // Michael Chen - 10411941 /** * Creates a list with random numbers from a list with chars. * * The function 'randomObjects' replaces the old representation of objects, * a string of chars, with the the new representation of objects, a string * of random numbers. The random number represent the objects. * Random objects are needed in 'createScale.php', so that the objects are * not always represented by the same image. The function uses the * the variables $numberArray and $stringArray to remember which chars and * numbers have already been handled so the same random number (between 1 * and 7) can not be selected again (unless it is assigned to the same * object). The for loop skips the non-object strings. * There are different cases for the array $scaleObjects for when a side * contains two objects instead of one. * The function returns a similar array as $scaleObjects but with random * numbers assigned to the objects instead of chars. * * @var scaleObjects */ function randomObjects($scaleObjects) { $numberObjects = count($scaleObjects); $numberArray = array(); $stringArray = array(); $counter = 1; for ($i = 0; $i <= ($numberObjects - 1); $i++) { if(($counter % 3) != 0) { if(strlen($scaleObjects[$i]) == 2) { $assignedNumbers = array(); $objects = str_split($scaleObjects[$i]); foreach($objects as $x) { if(in_array($x, $stringArray)) { $index = array_search($x, $stringArray); array_push($numberArray, $numberArray[$index]); array_push($stringArray, $x); array_push($assignedNumbers, $numberArray[$index]); }else { array_push($stringArray, $x); $number = checkRandom($numberArray); array_push($numberArray, $number); array_push($assignedNumbers, $number); } } $assignedNumber1 = strval($assignedNumbers[0]); $assignedNumber2 = strval($assignedNumbers[1]); $assignedNumbersString = "$assignedNumber1$assignedNumber2"; $scaleObjects[$i] = $assignedNumbersString; } else { if(in_array($scaleObjects[$i], $stringArray)) { $index = array_search($scaleObjects[$i], $stringArray); array_push($numberArray, $numberArray[$index]); array_push($stringArray, $scaleObjects[$i]); $number = $numberArray[$index]; } else { array_push($stringArray, $scaleObjects[$i]); $number = checkRandom($numberArray); array_push($numberArray, $number); } $assignedNumber = strval($number); $scaleObjects[$i] = $assignedNumber; } } $counter++; } return $scaleObjects; } /** * This function returns a random number * * This function returns a random number (between 1 and 7) that does not appear * in the numberArray. * * @var numberArray */ function checkRandom($numberArray) { $number = mt_rand(1,7); while(in_array($number, $numberArray)) { $number = mt_rand(1,7); } return $number; } ?>
Java
UTF-8
511
2.265625
2
[]
no_license
package com.spring.interview.SpringBeanLifeCycleAwareInterfaces; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { System.out.println( "Hello *Aware ---" ); ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("appcon.xml"); context.getBean("myawareservice",MyAwareService.class); context.close(); } }
Python
UTF-8
2,491
3.046875
3
[]
no_license
KAPASITEETTI = 5 OLETUSKASVATUS = 5 class IntJoukko: def __init__(self, kapasiteetti=None, kasvatuskoko=None): if kapasiteetti is None: self.kapasiteetti = KAPASITEETTI elif not isinstance(kapasiteetti, int) or kapasiteetti < 0: raise Exception("Väärä kapasiteetti") # heitin vaan jotain :D else: self.kapasiteetti = kapasiteetti if kasvatuskoko is None: self.kasvatuskoko = OLETUSKASVATUS elif not isinstance(kasvatuskoko, int) or kasvatuskoko < 0: raise Exception("Virheellinen kasvatuskoko") # heitin vaan jotain :D else: self.kasvatuskoko = kasvatuskoko self.ljono = [] self.alkioiden_lkm = 0 def kuuluu(self, luku): if luku in self.ljono: return True else: return False def lisaa(self, luku): if len(self.ljono) == self.kapasiteetti: self.kapasiteetti += self.kasvatuskoko if self.kuuluu(luku): return False else: self.ljono.insert(0,luku) self.alkioiden_lkm += 1 return True def poista(self, luku): if luku in self.ljono: self.ljono.remove(luku) self.alkioiden_lkm -= 1 return True return False def mahtavuus(self): return self.alkioiden_lkm def to_int_list(self): return self.ljono @staticmethod def yhdiste(joukko_a, joukko_b): taulu_x = IntJoukko() taulu_a = joukko_a.to_int_list() taulu_b = joukko_b.to_int_list() for luku in taulu_a: taulu_x.lisaa(luku) for luku in taulu_b: taulu_x.lisaa(luku) return taulu_x @staticmethod def leikkaus(joukko_a, joukko_b): taulu_y = IntJoukko() taulu_a = joukko_a.to_int_list() taulu_b = joukko_b.to_int_list() for luku in taulu_a: if luku in taulu_b: taulu_y.lisaa(luku) return taulu_y @staticmethod def erotus(joukko_a, joukko_b): taulu_z = IntJoukko() taulu_a = joukko_a.to_int_list() taulu_b = joukko_b.to_int_list() for luku in taulu_a: if luku not in taulu_b: taulu_z.lisaa(luku) return taulu_z def __str__(self): lista = sorted(self.ljono, reverse=True) tuloste = str(lista)[1:-1] return "{"f"{tuloste}""}"
JavaScript
UTF-8
2,658
2.796875
3
[]
no_license
var graph=[]; var finder=document.getElementById("row1"); var mapper = document.getElementById("mapelements"); var nodes= []; for (var i = 0; i <=1500; i++) { nodes[i] = []; } nodeconnection(); create(); function create(){ var cellno=1; for(i=1;i<=25;i++){ for(j=1;j<=60;j++){ rowidentity="row"+i; var finder=document.getElementById(rowidentity); var div = document.createElement("td"); div.id= cellno; div.style.width = 0.9 +"vw"; div.style.height = 1.5+"vw"; div.style.backgroundColor="white" div.setAttribute("draggable","true;"); div.setAttribute("onclick","clicky('"+cellno+"');"); div.setAttribute("ondragover","clicky('"+cellno+"');"); div.setAttribute("ondragstart","clicky('"+cellno+"');"); div.setAttribute("ondragenter","clicky('"+cellno+"');"); finder.appendChild(div); cellno++; } } } array=[] var temp; function clicky(x){ var cell=document.getElementById(x); if(temp==x){ return; } switch(cell.style.backgroundColor) { case "white": cell.style.backgroundColor="rgb(47, 49, 128)"; for(let i=1;i<=1500;i++){ nodes[i][x]=0; nodes[x][i]=0; } temp=x; break; case "rgb(47, 49, 128)": cell.style.backgroundColor="white" for(let i=1;i<=1500;i++){ nodes[i][x]=1; nodes[x][i]=1; temp=x; break; } } return; } function clearvisualizer(){ let y=1; nodeconnection(); while(y<=1500){ let cells=document.getElementById(y); cells.style.backgroundColor="white"; console.log("waddup") y++; } } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function maze(){ clearvisualizer(); for(let i=1;i<=1500;i++){ if(i<=60 || i%60==0 || i>=1440) { if(i!=1 && i%60!=0){ clicky(i-1); } if(i!=1 && i%60==0 && i<1440){ clicky(i+1); } clicky(i); } } } function nodeconnection(){ for(i=1;i<=1500;i++){ for(j=1;j<=1500;j++){ if(i+1 == j || i-1 ==j || i-j ==10|| j-i==10|| i==j){ nodes[i][j]=1; } else{ nodes[i][j]=0; } } } }
Python
UTF-8
12,845
2.90625
3
[]
no_license
""" Script to convert the Media-Frames-Corpus, provided as json, in a format which fits the Webis-format (csv) media_frames = {"Economic", "Capacity and resources", "Morality", "Fairness and equality", "Legality, constitutionality and jurisprudence", "Policy prescription and evaluation", "Crime and punishment", "Security and defense", "Health and safety", "Quality of life", "Cultural identity", "Public opinion", "Political", "External regulation and reputation", "Other"} """ import csv import json import pathlib from typing import List, Tuple import nltk from regex import regex nltk.download("punkt") def fetch_sentences_of_span(whole_text, start, end) -> Tuple[List[str], List[int]]: f_sentences = whole_text.split("\n\n", 3) if len(f_sentences) <= 2: return f_sentences, [] else: sentences_nltk = f_sentences[-1] f_sentences = f_sentences[:-1] f_sentences.extend(nltk.sent_tokenize(text=sentences_nltk, language="english")) return f_sentences, [fi for fi, s_fi in enumerate(f_sentences) if (whole_text.index(s_fi) <= start < whole_text.index(s_fi) + len(s_fi)) or (whole_text.index(s_fi) < end <= whole_text.index(s_fi) + len(s_fi))] if __name__ == "__main__": codes = pathlib.Path("codes.json") data_files = [ pathlib.Path("immigration.json"), #pathlib.Path("samesex.json"), pathlib.Path("smoking.json") ] use_only_gold_labels = False # Naderi and Hirst tried it with True filter_not_media_frames = True # Naderi and Hirst said False exact_frames = True # Naderi and Hirst set True extract_sentences = True # Naderi and Hirst set True # - True: indicates the broad context regarding to our paper # - False: indicates the narrow context regarding to our paper no_premise = False # Naderi and Hirst set True - was not their problem ignore_article_frames = True # Naderi and Hirst set True csv_output = pathlib.Path("converted").joinpath("Media-{}-framing_{}_{}{}{}{}{}.csv".format( "".join(map(lambda df: df.stem, data_files)), "gold" if use_only_gold_labels else "dirty", "pure" if filter_not_media_frames else "all", "+" if ignore_article_frames else "_", "sent" if extract_sentences else "", "noprem" if no_premise else "", "exact" if exact_frames else "") ) decoder = json.JSONDecoder() decoder.parse_float = False decoder.parse_int = True decoder.parse_constant = False decoder.strict = False frame_encodings = decoder.decode(codes.read_text(encoding="utf-8")) print("Got {} media frames encodings".format(len(frame_encodings))) article_dict = dict() for data_file in data_files: decoded = decoder.decode(data_file.read_text(encoding="utf-8")) print(type(decoded)) article_dict.update(decoded) print("Collected {} articles".format(len(article_dict))) dict_collector = dict() for article_id, content in article_dict.items(): text = content["text"] for name, annotations in content["annotations"]["framing"].items(): for annotation in annotations: if ignore_article_frames and str(annotation["code"]).endswith(".2"): # it's a frame annotation over the whole article continue spanned_text = text[annotation["start"]-1:annotation["end"]+1] #ignore the spanned text. Sometimes, it's one character to much or missing - the annotations are not quite correct :\ if (66 <= ord(spanned_text[0]) <= 90 or 98 <= ord(spanned_text[0]) <= 122) and ord(spanned_text[0]) != 73: spanned_text = spanned_text[1:] if 65 <= ord(spanned_text[-1]) <= 90 or 98 <= ord(spanned_text[-1]) <= 122: spanned_text = spanned_text[:-1] spanned_text = spanned_text.strip(" \n-',").lstrip(".)]").rstrip("[(") annotation["start"] = text.index(spanned_text, annotation["start"]-1) annotation["end"] = annotation["start"]+len(spanned_text) if spanned_text == "PRIMARY": spanned_text = text entry_id = "{}_{}_{}".format(article_id, annotation["start"], annotation["end"]) annotation["code"] = str(annotation["code"]) frame = frame_encodings.get(annotation["code"], None) if filter_not_media_frames else frame_encodings.get( annotation["code"], "Irrelevant") if frame is not None: if not exact_frames: if frame.endswith(" headline"): frame = frame[:-9] elif frame.endswith(" primary"): frame = frame[:-8] frame_id = [annotation["code"] if exact_frames else str(annotation["code"]).split(".", 2)[0]] if entry_id in dict_collector.keys(): dict_collector[entry_id]["frame_id"] += frame_id dict_collector[entry_id]["frame"] += [frame] else: index_of_text_body = text.index(content["title"]) + len(content["title"]) + 2 paragraph_split = spanned_text.split("\n\n") if len(paragraph_split) >= 2: premise = "" if no_premise else paragraph_split[-2] conclusion = paragraph_split[-1] else: all_sentences, candidate_sentences_index = \ fetch_sentences_of_span(whole_text=text, start=annotation["start"], end=annotation["end"]) if len(candidate_sentences_index) >= 2: if no_premise: premise = "" conclusion = "" for i in candidate_sentences_index: conclusion += all_sentences[i] + " " elif extract_sentences: premise = "" for i in candidate_sentences_index[:-1]: premise += all_sentences[i] + " " conclusion = all_sentences[candidate_sentences_index[-1]] else: conclusion = all_sentences[candidate_sentences_index[-1]] len_conclusion = annotation["end"] - text.rindex(conclusion, annotation["start"]) if len_conclusion <= 3: conclusion = all_sentences[candidate_sentences_index[-1]] if len(candidate_sentences_index) >= 3: premise = "" for i in candidate_sentences_index[:-2]: premise += all_sentences[i] + " " else: premise = "" else: conclusion = conclusion[:len_conclusion].strip() premise = "" for i in candidate_sentences_index[:-1]: premise += all_sentences[i] + " " else: if extract_sentences: if len(candidate_sentences_index) >= 1: candidate_sentence_index = candidate_sentences_index[0] premise = all_sentences[candidate_sentence_index - 1] \ if candidate_sentence_index > 1 else "" conclusion = all_sentences[candidate_sentence_index] else: premise = "" conclusion = spanned_text else: try: premise = "" if no_premise else\ text[text.rindex(".", 0, annotation["start"]) + 1:annotation["start"]] except ValueError: if "\n" in text[:annotation["start"]]: premise = text[ text.rindex("\n", 0, annotation["start"]) + 1:annotation["start"] ] else: premise = text[:annotation["start"]] conclusion = spanned_text dict_collector[entry_id] = { "argument_id": "{}_{}-{}".format(article_id, annotation["start"], annotation["end"]), "frame_id": frame_id, "frame": [frame], "topic_id": content["csi"], "topic": "{}: {}".format(article_id[:article_id.index("1.0")], content["title"]), "premise": premise.replace("\t", " ").replace("\n", " ").strip(), "conclusion": conclusion.replace("\t", " ").replace("\n", " ").strip() } print("Went through data and found {} samples.".format(len(dict_collector))) ret = [] for sample in dict_collector.values(): ret_line = [sample["argument_id"]] frame_dict = dict() for f in zip(sample["frame_id"], sample["frame"]): frame_dict[f] = frame_dict.get(f, 0) + 1 if max(frame_dict.values()) <= 1 and use_only_gold_labels: # only one annotator for this text piece or no majority - unsure! continue elif sum(frame_dict.values()) > 1 >= max(frame_dict.values()): # To create our dataset, we first gathered the annotations that at least two annotators agreed upon; # however, that process resulted in a small corpus # because a majority of the articles on smoking were # annotated only once. Therefore, we kept the cases # that were annotated only once, and for the more # controversial cases, where multiple frame dimensions were assigned, we kept only the annotations # that were agreed upon by at least two annotators. continue if len(frame_dict) == 0 and filter_not_media_frames: continue elif len(frame_dict) == 0: ret_line.append("16.2" if exact_frames else "16") ret_line.append("Irrelevant") else: flat_frame_dict = [(k, v) for k, v in frame_dict.items()] flat_frame_dict.sort(key=lambda k: k[1], reverse=True) ret_line.extend(flat_frame_dict[0][0]) ret_line.append(sample["topic_id"]) ret_line.append(sample["topic"]) # The sentences were further lower-cased and all # numeric tokens were converted to <NUM>. ret_line.append(regex.sub("\d+", "<num>", sample["premise"])) ret_line.append(regex.sub("\d+", "<num>", sample["conclusion"])) ret.append(ret_line) print("Will write {} samples to {}".format(len(ret), csv_output.absolute())) class ExcelPipe(csv.Dialect): """Describe the usual properties of Excel-generated CSV files.""" delimiter = '|' quotechar = '"' doublequote = True skipinitialspace = False lineterminator = '\n' quoting = csv.QUOTE_MINIMAL csv_output.parent.mkdir(parents=True, exist_ok=True) writer = csv.writer(csv_output.open(mode="w", encoding="utf-8", buffering=True), ExcelPipe) writer.writerow(["argument_id", "frame_id", "frame", "topic_id", "topic", "premise", "conclusion"]) writer.writerows(ret)
Markdown
UTF-8
1,175
2.6875
3
[]
no_license
## Master, The Tempest Is Raging! Master the tempest is raging! The billows are tossing high! The sky is o’er shadowed with blackness; No shelter or help is nigh; Carest Thou not that we perish? How canst Thou lie asleep, When each moment so madly is threatening, A grave in the angry deep. Chorus “The winds and the waves shall obey My will, Peace be still! Whether the wrath of the storm-tossed sea, Or demons, or men, or whatever it be, No water can swallow the ship where lies, The Master of ocean and earth and skies; They all shall sweetly obey my will, Peace, be still! Peace be still! They all shall sweetly obey My will, Peace, peace be still!” Master with anguish of spirit, I bow in my grief today; The depths of sad hearts are troubled; O, waken and save I pray! Torrents of sin and of anguish, Sweep o’er my sinking soul; And I perish! I perish dear Master; O hasten, and take control. Master, the terror is over, The element sweetly rest; Earth’s sun is in the calm lake is mirrored, And heaven’s within my breast; Linger O blessed Redeemer, Leave me alone no more; And with joy I shall make the blest harbor, And rest on the blissful shore.
Java
UTF-8
325
1.609375
2
[]
no_license
package com.test.login; import org.testng.annotations.Test; import com.vetty.actions.BaseClass; import com.vetty.actions.SSNTraceSubmission; public class LoginTest extends BaseClass{ SSNTraceSubmission obj = new SSNTraceSubmission(); @Test public void test() throws InterruptedException { obj.Login(); } }
JavaScript
UTF-8
1,469
4.125
4
[]
no_license
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var addTwoNumbers = function(l1, l2) { const a1 = list2array(l1); const a2 = list2array(l2); const a3 = add(a1, a2); return array2list(a3); }; const list2array = (list) => { const arr = []; let n = list; while(n){ arr.push(n.val); n = n.next; } return arr; }; const array2list = (arr) => { const list = new ListNode(arr[0]); let lastNode = list; for(let i = 1, len = arr.length; i < len; i += 1) { const node = new ListNode(arr[i]); lastNode.next = node; lastNode = node; } return list; }; const add = (arr1, arr2) => { const result = []; let carry = 0; let i = 0; for(let i = 0, l = Math.max(arr1.length, arr2.length); i < l; i += 1) { const sum = (arr1[i] || 0) + (arr2[i] || 0) + carry; result.push(sum % 10); carry = Math.floor(sum / 10); } if (carry) { result.push(carry); } return result; } // 测试代码 function ListNode(val) { this.val = val; this.next = null; } (() => { // (2 -> 4 -> 3) + (5 -> 6 -> 4) const l1 = new ListNode(2); l1.next = new ListNode(4); l1.next.next = new ListNode(3); let l2 = new ListNode(5); l2.next = new ListNode(6); l2.next.next = new ListNode(4); debugger; const l3 = addTwoNumbers(l1, l2); debugger; })();
Java
UTF-8
347
2.140625
2
[ "MIT" ]
permissive
package com.zalivka.sregex.matcher; import junit.framework.TestCase; public class CharTest extends TestCase { public void testChar() { assertTrue(Matcher.match(new Char('a'), "a").success()); assertFalse(Matcher.match(new Char('a'), "b").success()); assertFalse(Matcher.match(new Char('a'), "ab").success()); } }
Python
UTF-8
2,333
3.453125
3
[]
no_license
# _*_ coding: utf-8 _*_ # ---------------example 1------------------- import functools import time def log(func): @functools.wraps(func) # make the name attribute of original function not change def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper @log def now(): print('2020-8-18') now() # ---------------example 2------------------- def log2(text): def decorator(func): @functools.wraps(func) # make the name attribute of original function not change def wrapper2(*arg, **kw): print('%s %s():' % (text, func.__name__)) return func(*arg, **kw) return wrapper2 return decorator @log2('execute') def now(): print('2020-8-18') now() # ---------------exercise 1------------------- def metric(fn): @functools.wraps(fn) def wrapper3(*arg, **kw): start = time.time() tmp = fn(*arg, **kw) end = time.time() print('%s executed in %s ms' % (fn.__name__, end-start)) return tmp return wrapper3 # test @metric def fast(x, y): time.sleep(0.0012) return x + y @metric def slow(x, y, z): time.sleep(0.1234) return x * y * z f = fast(11, 22) s = slow(11, 22, 33) if f != 33: print('测试失败!') elif s != 7986: print('测试失败!') else: print('测试成功!') # ---------------exercise 2------------------- def log3(func): @functools.wraps(func) def wrapper4(*arg, **kw): print('begin call %s()' % func.__name__) func(*arg, **kw) print('end call %s()' % func.__name__) return return wrapper4 @log3 def now(): print('2020-8-18') now() # ---------------exercise 2------------------- def log5(text): if isinstance(text, str): def decorator2(func): @functools.wraps(func) def wrapper5(*arg, **kw): print('%s %s:' % (text, func.__name__)) return func(*arg, **kw) return wrapper5 return decorator2 else: def wrapper6(*arg, **kw): print('call %s():' % text.__name__) return text(*arg, **kw) return wrapper6 @log5 def now(): print('2020-8-18') now() @log5('execute') def now(): print('2020-8-18') now()
C#
UTF-8
1,150
3.171875
3
[ "MIT" ]
permissive
using UnityEngine; namespace mechanics.nutrients { public abstract class Nutrient : MonoBehaviour { protected virtual int ResourceStore { get; set; } protected virtual int ResourceMaximum => 10; /// <summary> /// The percentage of nutrient available mapped between (0,1) /// </summary> public float FiledAmount => Mathf.Clamp01((float) ResourceStore / ResourceMaximum); /// <summary> /// This returns the maximum resource available /// </summary> /// <param name="amountDemanded">A consumer can request an amount</param> public abstract int Consume(int amountDemanded); /// <summary> /// This can be used by a donor to fill the _resourceStore /// </summary> /// <param name="amountGiven">A donor can give as specified amount. /// This can be more than the maximum. In that case the store will not fill more</param> public void Replenish(int amountGiven) { ResourceStore = Mathf.Clamp(ResourceStore + amountGiven, 0, ResourceMaximum); } } }
Python
UTF-8
2,514
2.734375
3
[ "MIT", "Apache-2.0" ]
permissive
import unittest from typing import Iterator from context import comedian # pylint: disable=W0611 from comedian.traits import DebugMixin, EqMixin class X(DebugMixin, EqMixin): def __init__(self, x: int, y: int, z: int): self.x = x self.y = y self.z = z def __fields__(self) -> Iterator[str]: yield from ("x") class XY(DebugMixin, EqMixin): def __init__(self, x: int, y: int, z: int): self.x = x self.y = y self.z = z def __fields__(self) -> Iterator[str]: yield from ("x", "y") class XYZ(DebugMixin, EqMixin): def __init__(self, x: int, y: int, z: int): self.x = x self.y = y self.z = z def __fields__(self) -> Iterator[str]: yield from ("x", "y", "z") class Default(DebugMixin, EqMixin): def __init__(self, x: int, y: int, z: int): self.x = x self.y = y self.z = z class FieldsTest(unittest.TestCase): def test_x(self): self.assertSetEqual({"x"}, set(X(1, 2, 3).__fields__())) self.assertEqual("X(x=1)", X(1, 2, 3).__str__()) self.assertEqual(X(1, 2, 3), X(1, 2, 3)) self.assertEqual(X(1, 2, 3), X(1, 2, 6)) self.assertEqual(X(1, 2, 3), X(1, 5, 6)) self.assertNotEqual(X(1, 2, 3), X(4, 5, 6)) def test_xy(self): self.assertSetEqual({"x", "y"}, set(XY(1, 2, 3).__fields__())) self.assertEqual("XY(x=1, y=2)", XY(1, 2, 3).__str__()) self.assertEqual(XY(1, 2, 3), XY(1, 2, 3)) self.assertEqual(XY(1, 2, 3), XY(1, 2, 6)) self.assertNotEqual(XY(1, 2, 3), XY(1, 5, 6)) self.assertNotEqual(XY(1, 2, 3), XY(4, 5, 6)) def test_xyz(self): self.assertSetEqual({"x", "y", "z"}, set(XYZ(1, 2, 3).__fields__())) self.assertEqual("XYZ(x=1, y=2, z=3)", XYZ(1, 2, 3).__str__()) self.assertEqual(XYZ(1, 2, 3), XYZ(1, 2, 3)) self.assertNotEqual(XYZ(1, 2, 3), XYZ(1, 2, 6)) self.assertNotEqual(XYZ(1, 2, 3), XYZ(1, 5, 6)) self.assertNotEqual(XYZ(1, 2, 3), XYZ(4, 5, 6)) def test_default(self): self.assertSetEqual({"x", "y", "z"}, set(Default(1, 2, 3).__fields__())) self.assertEqual("Default(x=1, y=2, z=3)", Default(1, 2, 3).__str__()) self.assertEqual(Default(1, 2, 3), Default(1, 2, 3)) self.assertNotEqual(Default(1, 2, 3), Default(1, 2, 6)) self.assertNotEqual(Default(1, 2, 3), Default(1, 5, 6)) self.assertNotEqual(Default(1, 2, 3), Default(4, 5, 6))
Java
UTF-8
6,500
2.65625
3
[]
no_license
package db.dao; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import db.ConnectionPool; import db.DAOUtil; import db.models.EmergencyCall; import db.models.EmergencyCategory; public class EmergencyDAO { private static ConnectionPool connectionPool = ConnectionPool.getConnectionPool(); private static final String SQL_SELECT_ALL_CALLS = "select * from emergency_call;"; private static final String SQL_SELECT_CALL_BY_ID = "select * from emergency_call where id=?;"; private static final String SQL_INSERT_CALL = "insert into emergency_call (title,description,date, location,image_src, is_deleted, emergency_category_id) values(?,?,?,?,?,?,?);"; private static final String SQL_DELETE_CALL = "update emergency_call set is_deleted = true where id = ?;"; private static final String SQL_SELECT_EMER_CATEGORIES = "select * from emergency_category;"; private static final String SQL_SELECT_CATEGORY_BY_ID = "select * from emergency_category where id = ?;"; private static final String SQL_INSERT_CATEGORY = "insert into emergency_category (name,is_deleted) values(?,?);"; public static ArrayList<EmergencyCall> selectAllCalls(){ ArrayList<EmergencyCall> retVal = new ArrayList<EmergencyCall>(); Connection connection = null; ResultSet rs = null; Object values[] = {}; try { connection = connectionPool.checkOut(); PreparedStatement pstmt = DAOUtil.prepareStatement(connection, SQL_SELECT_ALL_CALLS, false, values); rs = pstmt.executeQuery(); while (rs.next()){ retVal.add(new EmergencyCall(rs.getInt("id"), rs.getString("title"), rs.getString("description"), new Date(rs.getTimestamp("date").getTime()), rs.getString("location"),rs.getString("image_src"), rs.getBoolean("is_deleted"), rs.getInt("emergency_category_id"))); } pstmt.close(); } catch (SQLException exp) { exp.printStackTrace(); } finally { connectionPool.checkIn(connection); } return retVal; } public static EmergencyCall selectCallById(int id){ EmergencyCall retVal = null; Connection connection = null; ResultSet rs = null; Object values[] = {id}; try { connection = connectionPool.checkOut(); PreparedStatement pstmt = DAOUtil.prepareStatement(connection, SQL_SELECT_CALL_BY_ID, false, values); rs = pstmt.executeQuery(); while (rs.next()){ retVal = new EmergencyCall(rs.getInt("id"), rs.getString("title"), rs.getString("description"), new Date(rs.getTimestamp("date").getTime()), rs.getString("location"),rs.getString("image_src"), rs.getBoolean("is_deleted"), rs.getInt("emergency_category_id")); } pstmt.close(); } catch (SQLException exp) { exp.printStackTrace(); } finally { connectionPool.checkIn(connection); } return retVal; } public static boolean insertEmergencyCall(EmergencyCall call) { boolean retVal = false; Connection connection = null; ResultSet generatedKeys = null; Object values[] = { call.getTitle(),call.getDescription(),new Timestamp(call.getDate().getTime()), call.getLocation(), call.getImageSource(), call.isDeleted(), call.getEmergencyCategoryId() }; try { connection = connectionPool.checkOut(); PreparedStatement pstmt = DAOUtil.prepareStatement(connection, SQL_INSERT_CALL, true, values); int affectedRows = pstmt.executeUpdate(); if (affectedRows == 0) retVal = false; else retVal = true; generatedKeys = pstmt.getGeneratedKeys(); if (generatedKeys.next()) { call.setId(generatedKeys.getInt(1)); } pstmt.close(); } catch (SQLException e) { retVal = false; } finally { connectionPool.checkIn(connection); } return retVal; } public static boolean deleteCall(int id) { boolean retVal = false; Connection connection = null; Object values[] = { id }; try { connection = connectionPool.checkOut(); PreparedStatement pstmt = DAOUtil.prepareStatement(connection, SQL_DELETE_CALL, false, values); int affectedRows = pstmt.executeUpdate(); if (affectedRows == 0) retVal = false; else retVal = true; pstmt.close(); } catch (SQLException e) { retVal = false; } finally { connectionPool.checkIn(connection); } return retVal; } public static ArrayList<EmergencyCategory> selectEmergencyCategories(){ ArrayList<EmergencyCategory> retVal = new ArrayList<EmergencyCategory>(); Connection connection = null; ResultSet rs = null; Object values[] = {}; try { connection = connectionPool.checkOut(); PreparedStatement pstmt = DAOUtil.prepareStatement(connection, SQL_SELECT_EMER_CATEGORIES, false, values); rs = pstmt.executeQuery(); while (rs.next()){ retVal.add(new EmergencyCategory(rs.getInt("id"), rs.getString("name"), rs.getBoolean("is_deleted"))); } pstmt.close(); } catch (SQLException exp) { exp.printStackTrace(); } finally { connectionPool.checkIn(connection); } return retVal; } public static EmergencyCategory selectCategoryById(int id){ EmergencyCategory retVal = null; Connection connection = null; ResultSet rs = null; Object values[] = {id}; try { connection = connectionPool.checkOut(); PreparedStatement pstmt = DAOUtil.prepareStatement(connection, SQL_SELECT_CATEGORY_BY_ID, false, values); rs = pstmt.executeQuery(); while (rs.next()){ retVal = new EmergencyCategory(rs.getInt("id"), rs.getString("name"), rs.getBoolean("is_deleted")); } pstmt.close(); } catch (SQLException exp) { exp.printStackTrace(); } finally { connectionPool.checkIn(connection); } return retVal; } public static boolean insertEmergencyCategory(EmergencyCategory category) { boolean retVal = false; Connection connection = null; ResultSet generatedKeys = null; Object values[] = { category.getName(), category.isDeleted() }; try { connection = connectionPool.checkOut(); PreparedStatement pstmt = DAOUtil.prepareStatement(connection, SQL_INSERT_CATEGORY, true, values); int affectedRows = pstmt.executeUpdate(); if (affectedRows == 0) retVal = false; else retVal = true; generatedKeys = pstmt.getGeneratedKeys(); if (generatedKeys.next()) { category.setId(generatedKeys.getInt(1)); } pstmt.close(); } catch (SQLException e) { retVal = false; } finally { connectionPool.checkIn(connection); } return retVal; } }
Shell
UTF-8
656
3.40625
3
[]
no_license
#!/bin/bash PS3="Enter your choice :" select choice in "Create Database" "List Database" "Connect to DataBase" "Drop Database" "Exit" do case $choice in "Create Database" ) . ./CreateDatabase.sh break ;; "List Database" ) . ./listdatabases.sh break ;; "Connect to DataBase" ) . ./connectDB.sh break ;; "Drop Database" ) . ./DropDatabase.sh break ;; "Exit" ) exit ;; * ) echo "Invalid Choice" ;; esac done
Markdown
UTF-8
29,389
2.984375
3
[]
no_license
--- jupytext: text_representation: extension: .md format_name: myst format_version: '0.9' jupytext_version: 1.5.2 kernelspec: display_name: Python 3 language: python name: python3 --- # Wavefield Imaging In many applications, acoustic or electromagnetic waves are harnessed to *see* things; under-water acoustics, radar, sonar, medical ultrasound, ground penetrating radar, seismic imaging, global seismology. In some of these applications the measurements are *passive*; we record waves that are emitted by the object of investigation and we try to infer its location, size, etc. In *active* measurements, waves are generated and the response of the object is recorded. An example of such an application is shown in {numref}`seismic`. ```{figure} images/wavefield_imaging/seismic.png --- height: 150px name: seismic --- Acquisition setup of a bat and an active marine seismic survey. ``` In order to treat the inverse problem, we must first understand the *forward problem*. In its most rudimentary form, the wave-equation is given by ```{math} :label: waveequation L[c]v(t,x) = q(t,x), ``` with $$ L[c] = \left[\frac{1}{c(x)^2}\frac{\partial^2}{\partial t^2} - \nabla^2 \right], $$ and where $v : \mathbb{R} \times \mathbb{R}^n \rightarrow \mathbb{R}$ denotes the wavefield, $c : \mathbb{R}^n \rightarrow \mathbb{R}$ is the speed of propagation and $q : \mathbb{R} \times \mathbb{R}^n \rightarrow \mathbb{R}$ is a source term. We will assume that the source has compact support in both space and time and is square integrable. To define a unique solution of {eq}`waveequation` we need to supply boundary and initial conditions. In the applications discussed above one typically considers an unbounded domain ($x \in \mathbb{R}^n$) and Cauchy initial conditions $v(0,x) = 0$, $\frac{\partial v}{\partial t}(0,x) = 0$. In scattering experiments it is common to rewrite the wave-equation in terms of an incoming and a scattered wavefield, $v = v_i + v_s$, and a scattering potential, $u(x) = c(x)^{-2} - c_0^{-2}$: ```{math} :label: scattering L[c_0]v_i(t,x) = q(t,x), \quad L[c_0]v_s(t,x) = -u(x)\frac{\partial^2 v}{\partial t^2}(t,x). ``` Under a *weak scattering* assumption, we may ignore the interaction of $u$ and $v_s$ and replace $v$ in {eq}`scattering` by $v_i$. The measurements are typically taken to be the (scattered) wavefield restricted to $[0,T] \times \Delta$ where $\Delta \subset \mathbb{R}^n$ may be a manifold or a set of points. The data may then be denoted by $f(t,r)$. In active experiments, it is common practice to consider measurements for a collection of source terms. The sources may be point-sources, in which case $q(t,x) = w(t)\delta(x - s)$ with $s \in \Sigma$. Alternatively, the incident field $v_i$ may be given and parametrized by $s \in \Sigma$. We may then denote the data by $f(t,s,r)$ with $s\in \Sigma$, $r\in \Delta$ and $t\in [0,T]$. Based on this basic setup, we will discuss three possible inverse problems: * **Inverse source problem:** Recover the source $q$ from the measurements for known (and constant) $c(x)\equiv c_0$. * **Inverse scattering:** Recover the scattering potential $u(x)$ from measurements of the scattered field for multiple (known) sources, assuming that $c_0$ is known. * **Waveform tomography:** Recover $c(x)$ from measurements of the total wavefield for multiple (known) sources. Below you will find some typical examples of inverse problems that come up in practice. * **Earth-quake localization:** An earthquake described by a source term $w(t)q(x)$ is recorded by multiple seimosgraphs at locations $\Delta = \{r_k\}_{k=1}^n$. The goal is to recover $q$ in order to determine the location of the earthquake. * **Passive sonar:** Soundwaves emitted from an unidentified target are recorded using an array $\Delta = \{x_0 + rp \, | \, r\in[-h,h] \}$, where $p\in\mathbb{S}^2$ denotes the orientation of the array and $h$ its width. The goal is to recover the source term $w(t)q(x)$ to determine the origin and nature of the source. * **Radar imaging:** Incident plane waves, parametrized by direction $s \in \Sigma \subset \mathbb{S}^{2}$, are send into the medium and their reflected response is recorded by an array. The goal is retreive the scattering potential. * **Full waveform inversion:** In exploration seismology, the goal is to recover $c$ from measurements of the total wavefield on the surface: $\Sigma = \Delta = \{x \,|\, n\cdot x = 0\}$. * **Ultrasound tomography:** The goal is to recover $c$ from the total wavefield for sources and receivers surrounding the object. A few prominent examples of acquisition setups we will consider here are the following: * **Point-sources:** $q(t,x) = w(t)\delta(x - s)$. \item Incoming plane waves with frequency $\omega$ and direction $\xi$: $v_i(t,x) = \sin(\omega(t - \xi\cdot x/c))$ * **Point-measurements along a hyperplane:** $\Delta = \{x \in \mathbb{R}^n\, |\, n\cdot x = x_0\}$. * **Point-measurements on the sphere:** $\Delta = \{x \in \mathbb{R}^n \, | \, \|x\| = \rho\}$. We will further assume that the quantities of interest are compactly supported in both space and time and that the measurement time $T$ is large enough to capture all the required information. This situation is sketched in {numref}`assumption`. ```{figure} images/wavefield_imaging/assumption.png --- height: 150px name: assumption --- All information on the compactly supported source term is captured in the light cone defined by $t = c\cdot x$. We assume that $T$ is large enough to capture the complete intersection of the light cone with $\Delta$. ``` ## Forward modelling ### Analytic solution For a general source term we may express the solution as a convolution $$ v(t,x) = \int\!\!\int g(t-t',x,x') q(t',x')\mathrm{d}t'\mathrm{d}x', $$ where $g$ is the Green function, obeying $$ L[c]g(t,t',x,x') = \delta(t-t')\delta(x-x'). $$ For $c(x) \equiv c$ we have $g(t,t',x,x')\equiv g(t-t',x-x')$ and the Green functions are given by: $$ g(t,x) = \frac{1}{2c}H(t - |x|/c), $$ for $n=1$, $$ g(t,x) = \frac{1}{2\pi c\sqrt{c^2t^2 - |x|^2}}H(t - |x|/c), $$ for $n=2$, and $$ g(t,x) = \frac{1}{4\pi |x|} \delta(t - |x|/c), $$ for $n=3$. Note that these are the *causal* Green functions; they propagate information forward in time. The \*a-causal* or *time-reversed* Green functions also satisfy the wave-equation. The solution for non-constant $c$ can be constructed by solving an integral equation $$ v = g_0*q - g_0*\left(u\cdot \frac{\partial^2 v}{\partial t^2}\right), $$ where $*$ denotes convolution, $g$ is the Green function for $c(x) \equiv c_0$ and $u = c^{-2} - c_0^{-2}$. ### Numerical modelling For non-constant $c$, such closed-form expression are generally not available. The most basic method for solving the wave equation numerically is the Leap-Frog method. For $n=1$, the method may be expressed as follows. Introducing $v_{ij} \equiv v(i\Delta t, j\Delta x)$ we have $$ \frac{v_{i+1,j} - 2v_{i,j} + v_{i-1,j}}{c_{ij}^2\Delta t^2} - \frac{v_{i,j+1} - 2v_{i,j} + v_{i,j-1}}{\Delta x^2} = q_{ij} + \mathcal{O}(\Delta x^2) + \mathcal{O}(\Delta t^2). $$ We need to truncate the spatial domain to $[-L,L]$ in order to compute solutions. We need boundary conditions that will let waves leave the domain with reflecting of the artificial boundary. The simplest are so-called radiation boundary conditions, that impose a one-way wave equation in the direction normal to the boundary: $$ \frac{\partial v}{\partial t}(t,\pm L) = \pm c(\pm L)\frac{\partial v}{\partial x}(t,\pm L), $$ which can be discretized using finite-differences as well. Ignoring the higher order terms leads to $$ \widetilde v_{i+1,j} = 2\widetilde v_{i,j} - \widetilde v_{i-1,j} + \frac{c_{ij}^2\Delta t^2}{\Delta x^2}\left(\widetilde v_{i,j+1} - 2\widetilde v_{i,j} + \widetilde v_{i,j-1} + \widetilde q_{i,j}\right),\quad j=-J+1, \ldots, J-1, $$ and $$ \widetilde{v}_{i+1,-J} = \widetilde{v}_{i,-J} + \frac{c_{i,-J}\Delta t}{\Delta x}\left(\widetilde v_{i,-J+1} - \widetilde v_{i,-J}\right), $$ $$ \widetilde{v}_{i+1,J} = \widetilde{v}_{i,J} + \frac{c_{i,J}\Delta t}{\Delta x}\left(\widetilde v_{i,J} - \widetilde v_{i,J-1}\right), $$ with $\widetilde v_{0,j} = \widetilde v_{1,j} = 0$ and $\widetilde q_{i,j} = \Delta x^2 q(i\Delta t, j \Delta x)$. The *accuracy* of the approximation follows directly from the higher order terms we left out. Another important aspect is *stability*, which tells us how errors propagate. Since the equations are all linear, errors will propagate according to the same recursion relation. One way of studying this is *von Neumann stability analysis*, where we study the behaviour of individual components of the error: $e_{ij} = g^i\exp(\imath j\theta)$. This yields to following quadratic equation for $g$: $$ g^2 - 2g + 1 = 2\gamma g(\cos(\theta\Delta x)-1), $$ with $\gamma = \frac{c\Delta t}{\Delta x}$. To ensure stability, we need $|g|\leq 1$ for all $\theta$, which requires that $\gamma\leq 1$. ## Analysis ### Source localization Define forward map $$ f = Kq, $$ with $$ Kq(t,x) = \int\int g(t-t',x-x')q(t',x')\mathrm{d}x'\mathrm{d}t'. $$ Data are measured at locations $x \in \Delta$ and $t\in[0,T]$. * **Uniqueness.** Can we find sources $r_0$ for which $\|Kr_0\| = 0$? Yes! First define $w_0(t,x)$ compactly supported in $[0,T] \times \Omega$ so that $w_0(t,x) = 0$ for $x\in P$ and set $$ r_0(t,x) = L[c]w_0(t,x), $$ then $Kr_0 = w_0$, which is zero for $x\in \Delta$ and $t\in[0,T]$. * **Stability.** We can also construct sources that radiate an arbitraliy small amount of energy by picking $w_{\epsilon}$ such that $\|w_{\epsilon}\| = \mathcal{O}(\epsilon)$ and $\|Lw_{\epsilon}\| = \mathcal{O}(1)$ as $\epsilon\downarrow 0$. Then $K(q + r_{\epsilon}) = d + w_{\epsilon}$ and small perturbation in data leads to large perturbation in the solution. This will be explored in more detail in the assignments. ### Inverse scattering Under the weak scatterin assumption, the scattered field is given by $$ v_s(t,x) = \int\int u(x')\frac{\partial^2 v_i}{\partial t^2}(t',x')g(t-t',x,x')\mathrm{d}t'\mathrm{d}x', $$ which we measure at $x \in \Delta$ and $t\in [0,T]$. Can we construct $u$ such that $u(x')\frac{\partial^2 v_i}{\partial t^2}(t',x')$ is a non-radiating source? Following the approach described earlier, we start with $w_0(t,x)$ which is zero for $x \in \Delta$. Then, we want to decompose the resulting non-radiating source in two components: $u \cdot \frac{\partial^2 v_i}{\partial t^2}$. We can probably manage this for one incoming wavefield, but can we find a potential that is non-scattering for multiple incoming waves? In the assignments we will explore non-radiating sources in more detail. ## Reconstruction ### Inverse source problem We study a variant of the inverse source problem in which $q(t,x) = \delta(t)u(x)$ and $u$ is compactly supported on $\Omega \subset \mathbb{R}^n$. The foward operator for constant $c$ is given by $$ Ku(t,x) = \int_{\Omega} u(x')g(t,x-x') \mathrm{d}x', $$ with measurements on the sphere with radius $\rho$. A popular techique to solve the inverse problem is *backpropagation*, which is based on applying the adjoint of the forward operator to the data. The adjoint operator in this case is given by $$ K^* f(x) = \int_{\Delta}\int_0^T g(t',x'-x)f(t',x') \mathrm{d}x'\mathrm{d}t'. $$ We see that $p = K^* f$ can be obtained by solving $$ L[c]w(t,x) = \int_{\Delta}f(t,x')\delta(x-x')\mathrm{d}x', $$ using the time-reversed Green function and evaluating at $t=0$, i.e. $p(x) = w(0,x)$. To see why this works, we study the normal operator $K^*K$. In the temporal Fourier domain, for $c = 1$, the operator becomes $$ \widehat{f}(\omega,x) = \int_{\Omega} u(x') \frac{\exp(\imath\omega|x-x'|)}{|x-x'|}\mathrm{d}x', $$ and $$ u(x) = \int \int_{\Delta} \widehat{f}(\omega,x') \frac{\exp(-\imath\omega|x'-x|)}{|x'-x|} \mathrm{d}x'\mathrm{d}\omega. $$ so $$ K^* Ku(x) = \int \int_{\Delta}\int_{\Omega} f(x') \frac{\exp(\imath\omega|x''-x'|)}{|x''-x'|} \frac{\exp(-\imath\omega|x''-x|)}{|x''-x|} \mathrm{d}x'\mathrm{d}x''\mathrm{d}\omega. $$ For $|x''| \gg |x|$ we can approximate it as $|x'' - x| \approx |x''| + x\cdot x''/|x''|$ and likewise for $|x'' - x'|$. This is called the *far-field approximation*. Introducing $\xi'' = x''/|x''| = x''/\rho$ on the unit sphere, we find $$ K^* {K}u(x) = \rho\int_{\Omega} u(x') \int\int\exp(\imath\omega \xi''\cdot(x'-x)) \mathrm{d}\xi''\mathrm{d}\omega\mathrm{d}x'. $$ The kernel $$ k(x-x') = \int\int \exp(\imath\omega \xi''\cdot(x'-x)) \mathrm{d}\xi''\mathrm{d}\omega, $$ is sometimes refered to as the *point-spread function*. Under ideal conditions, i.e, measurements are available for *all* frequencies $\omega\in\mathbb{R}$, integration over $\omega$ yields $$ k(x) = \int \delta(\xi\cdot x) \mathrm{d}\xi. $$ We only get contributions to the integral for directions orthogonal to $x$, because $\delta(\xi\cdot x)=0$ whenever $\xi\cdot x \not=0$. We thus integrate over a circle only. Substituting $\xi \cdot x = |\xi| |x| \cos \theta = |x|\cos \theta$ we obtain $$ k(x) = \frac{1}{|x|}\int_0^{2\pi} \delta(|x|\cos\theta) \mathrm{d}\theta = \frac{1}{|x|}. $$ Thus with a perfect acquisition we have $k(x' - x) = \frac{1}{|x - x'|}$. Since this corresponds to the Green function of the Poisson equation, it suggests that we may retrieve $u$ by applying a filter to the backprojected data: $$ u = \nabla^2 (K^*f). $$ This filtering can also be implemented in the Fourier domain by multiplying by $|\xi|^2$. An example is shown below. ```{code-cell} ipython3 :tags: [hide-input] import numpy as np import matplotlib.pyplot as plt import scipy.sparse as sp from scipy.ndimage import laplace def solve(q,c,dt,dx,T=1.0,L=1.0,n=1): '''Solve n-dim wave equation using Leap-Frog scheme: u_{n+1} = Au_n + Bu_{n-1} + Cq_n''' # define some quantities gamma = dt*c/dx nt = int(T/dt + 1) nx = int(2*L/dx + 2) # q = np.resize(q,(nx**n,nt)) # define matrices A,B,C,L = getMatrices(gamma,nx,n) # main loop u = np.zeros((nx**n,nt)) for k in range(1,nt-1): u[:,k+1] = A@u[:,k] + L@u[:,k] + B@u[:,k-1] + (dx**2)*C@q[:,k] return u def getMatrices(gamma,nx,n): # setup matrices l = (gamma**2)*np.ones((3,nx)) l[1,:] = -2*(gamma**2) l[1,0] = -gamma l[2,0] = gamma l[0,nx-2] = gamma l[1,nx-1] = -gamma if n == 1: a = 2*np.ones(nx) a[0] = 1 a[nx-1] = 1 b = -np.ones(nx) b[0] = 0 b[nx-1] = 0 c = (gamma)**2*np.ones(nx) c[0] = 0 c[nx-1] = 0 L = sp.diags(l,[-1, 0, 1],shape=(nx,nx)) else: a = 2*np.ones((nx,nx)) a[0,:] = 1 a[nx-1,:] = 1 a[:,0] = 1 a[:,nx-1] = 1 a.resize(nx**2) b = -np.ones((nx,nx)) b[0,:] = 0 b[nx-1,:] = 0 b[:,0] = 0 b[:,nx-1] = 0 b.resize(nx**2) c = (gamma)**2*np.ones((nx,nx)) c[0,:] = 0 c[nx-1,:] = 0 c[:,0] = 0 c[:,nx-1] = 0 c.resize(nx**2) L = sp.kron(sp.diags(l,[-1, 0, 1],shape=(nx,nx)),sp.eye(nx)) + sp.kron(sp.eye(nx),sp.diags(l,[-1, 0, 1],shape=(nx,nx))) A = sp.diags(a) B = sp.diags(b) C = sp.diags(c) return A,B,C,L ``` ```{code-cell} ipython3 :tags: [hide-input] # parameters L = 1.0 T = 1.0 dx = 1e-2 dt = .5e-2 nt = int(T/dt + 1) nx = int(2*L/dx + 2) c = 1 # define source term u = np.zeros((nx,nx)) u[nx//2 - 10:nx//2+10,nx//2 - 10:nx//2+10] = 1 q = np.zeros((nx*nx,nt)) q[:,1] = u.flatten() # forward solve w_forward = solve(q,c,dt,dx,T=T,L=L,n=2) # sample wavefield theta = np.linspace(0,2*np.pi,20,endpoint=False) xs = 0.8*np.cos(theta) ys = 0.8*np.sin(theta) I = np.ravel_multi_index(np.array([[xs/dx + nx//2],[ys//dx + nx//2]],dtype=np.int), (nx,nx)) d = w_forward[I,:] # define adjoint source r = np.zeros((nx*nx,nt)) r[I,:] = d r = np.flip(r,axis=1) # adjoint solve w_adjoint = solve(r,c,dt,dx,T=T,L=L,n=2) # plot fig, ax = plt.subplots(nrows=2, ncols=3, figsize=(8, 5), sharey=True) plt.gray() ax[0,0].plot(xs,ys,'r*') ax[0,0].imshow(w_forward[:,2].reshape((nx,nx)), extent=(-L,L,-L,L)) ax[0,0].set_title('t = 0') ax[0,1].plot(xs,ys,'r*') ax[0,1].imshow(w_forward[:,101].reshape((nx,nx)), extent=(-L,L,-L,L)) ax[0,1].set_title('t = 0.5') ax[0,2].plot(xs,ys,'r*') ax[0,2].imshow(w_forward[:,200].reshape((nx,nx)), extent=(-L,L,-L,L)) ax[0,2].set_title('t = 1') ax[1,0].plot(xs,ys,'r*') ax[1,0].imshow(w_adjoint[:,200].reshape((nx,nx)), extent=(-L,L,-L,L)) ax[1,1].plot(xs,ys,'r*') ax[1,1].imshow(w_adjoint[:,101].reshape((nx,nx)), extent=(-L,L,-L,L)) ax[1,2].plot(xs,ys,'r*') ax[1,2].imshow(w_adjoint[:,2].reshape((nx,nx)), extent=(-L,L,-L,L)) plt.show() ``` ### Inverse scattering Assuming point sources for the incident field, $c = 1$, and a compactly supported $u$, we can express the forward operator as $$ Ku(t,r,s) = \int_{\Omega} u(x) \frac{\delta''(t - |x - r| - |x - s|))}{|x - r||x - s|}\mathrm{d}x, $$ so the data $f(t,s,r)$ is the integral of the scattering potential, $u$, along an ellips. Conversely, we can think of the response of a single scattering point $x'$ as a hyperbola in $(t,s,r)$. This is illustrated in {numref}`ellips`. The adjoint operator here is given by $$ K^* f(x) = \int_\Delta \int_\Sigma \int_{0}^T f(t,r,s)\frac{\delta''(t - |x - r| - |x - s|))}{|x - r||x - s|} \mathrm{d}t\mathrm{d}s\mathrm{d}r. $$ As with the inverse source problem, applying the adjoint already yields an image. This is called *migration* in practice. The foward operator has a nice expression in the Fourier domain when using far field measurements. The derivation is left as an excersise. ```{figure} images/wavefield_imaging/scattering.png --- height: 150px name: ellips --- A single data point $f(t,s,r)$ is the integral of the scattering potential along an ellips: $|x - s| + |x - r| = t$. Likewise, a single point of $f(x)$ contributes to $d$ along a hyperola $t = |x - s| + |x - r|$. ``` ### Waveform tomography Here, we aim to recover $c$ directly from a non-linear equation $$ K(c) = f, $$ where $K$ solves $L[c]v = \delta(\cdot - s)w$ and samples the solution. i.e., $$ f(t,s,r) = \int g(t-t',r,s)w(t')\mathrm{d}t' $$ for $t\in [0,T]$, $s\in \Sigma$ and $r\in\Delta$. We can solve such a non-linear equation using Newton's method: $$ c_{k+1} = c_k - D{K}(c_k)^{-1}({K}(c_k) - d), $$ where $DK(c_k)$ denotes the *Fréchet derivative* which generalizes the notion of a derivative and obeys $$ \lim_{\|h\|\rightarrow 0} \frac{\|K(c + h) - {K}(c) - DK(c)h\|}{\|h\|} = 0. $$ We find $$ DK(c)\delta c = -\int\int \frac{\delta c (x')}{2c(x')}\frac{\partial^2 v}{\partial t^2}(t',x')g(t-t',x-x')\mathrm{d}t'\mathrm{d}x', $$ where the incident field, $v$, satisfies $L[c]v = \delta(\cdot - s)w$. In a finite-dimensional setting, $DK$ would be the Jacobian of $K$. Approximating the inverse using backprojection we obtain $$ c_{k+1} = c_k - \alpha_k DK(c_k)^{\dagger}(K(c_k) - d), $$ where $\alpha_k$ is a scaling factor. Again, we see that backprojection plays a prominant role. It turns out that this iteration is equivalent to a steepest descent method applied to $J(c) = \|K(c) - d\|^2$. +++ ## Exercises +++ ### Inverse source problem * Take $n=1$, $c=1$ and source term $\delta(t)u(x)$ with $u$ square integrable and supported on $[-\frac{1}{2},\frac{1}{2}]$ and measurements at $x = 1$ for $t\in [0,T]$. Show that the forward operator can be expressed as $$ f(t) = Ku(t) = \int_{1-t}^{\frac{1}{2}} u(x')\mathrm{d}x', $$ and that the operator is bounded. ```{admonition} Answer :class: tip, dropdown For $n = 1$ the solution to the wave equation with the given source term is given by $$v(t,x) = \frac{1}{2}\int_{-1/2}^{1/2} \int \delta(t')u(x') H(t - t' - |x - x'|)\mathrm{d}t'\mathrm{d}x' = \frac{1}{2}\int u(x) H(t - |x - x'|) \mathrm{d}x'.$$ For measurements at $x = 1$ this simplifies to $$f(t) = v(t,1) = \frac{1}{2}\int_{-1/2}^{1/2} u(x') H(t - |1 - x'|) \mathrm{d}x'.$$ This leads to the desired expression becuase we need $t \geq (1-x')$. To show that this a bounded operator consider $$\|f\|^2 = \int_0^T \left(\frac{1}{2}\int_{\max(\min(1-t,1/2),0)}^{1/2} u(x')\mathrm{d}x'\right)^2 \mathrm{d}t \leq \frac{1}{4}\int_0^T (1/2-\max(\min(1-t,1/2),0))\int_{-1/2}^{1/2} u(x')^2 \mathrm{d}x\mathrm{d}t = C \|u\|_2^2,$$ where we have used the Cauchy-Schwarz inequality to bound $\left(\int_a^b u(x) \mathrm{d}x\right)^2 \leq \left(\int_a^b 1 \mathrm{d}x \right)\left(\int_a^b u(x)^2 \mathrm{d}x \right).$ ``` * Show that $u$ can *in principle* be reconstructed from $f(t)$ with $T = \frac{3}{2}$ with the following reconstruction formula: $$ \widetilde{u}(x) = f'(1 - x). $$ ```{admonition} Answer :class: tip, dropdown For $1/2 \leq t \leq 3/2$ we have $f(t) = (1/2)\int_{1-t}^{1/2} u(x) \mathrm{d}x$, so $f'(t) = u(1-t)/2$. ``` * Show that $v_{\epsilon}(x) = \sin(2\pi\epsilon x)$ is an almost non-radiating source in the sense that $\|K v_{\epsilon}\|/\|v_{\epsilon}\| = \mathcal{O}(\epsilon^{-1})$ as $\epsilon \rightarrow \infty$. ```{admonition} Answer :class: tip, dropdown Integration brings out a factor $\epsilon^{-1}$, whereas the norm of $v_{\epsilon}$ is $\mathcal{O}(1)$ as $\epsilon \rightarrow \infty$. ``` * Now consider noisy measurements $f^{\delta}(t) = K u(t) + \delta \sin(t/\delta)$ and show that the error in the reconstruction is of order 1, i.e., $$ \|\widetilde{u} - u\| = \mathcal{O}(1), $$ as $\delta\downarrow 0$. ```{admonition} Answer :class: tip, dropdown Using the reconstruction formula we derived before we see that the particular noise term leads to a constant factor. ``` * In conclusion, is this inverse source problem well-posed? Why (not)? ```{admonition} Answer :class: tip, dropdown We conclude that the problem is not well-posed as we cannot uniquely and stably reconstruct the solution. ``` +++ ### Inverse scattering Consider the inverse scattering problem for $n=3$, $c=1$, with the incident field resulting from point-sources on the sphere with radius $\rho$ and measurements on the same sphere. The scattering potential is supported on the unit sphere. * Show that for $\rho \gg 1$, the measurements are given by $$ \widehat f(\omega,\xi,\eta) \propto \omega^2\widehat{u}(\omega (\xi - \eta)), $$ where $\widehat{u}$ is the spatial Fourier transform of the scattering potential, $u$, and $\xi,\eta$ are points on the unit sphere. ```{admonition} Answer :class: tip, dropdown We start from the forward operator $$f(t,r,s) = Ku(t,r,s) = \int_{\Omega} u(x) \frac{\delta''(t - |x - r| - |x - s|)}{|x-r||x-s|}\mathrm{d}x.$$ After Fourier transform in $t$ we get $$\widehat{f}(\omega,r,s) = \omega^2\int_{\Omega}u(x)\frac{\exp(\imath\omega(|x-r|+|x-s|))}{|x-r||x-s|}.$$ With the far-field approximation ($\rho = |r| = |s| \gg |x|$) $|x-s| \approx |s| + x\cdot s / |s|$ and $|x-r| \approx |r| + x\cdot r / |r|$ and introducing $\xi = s/|s|$, $\eta = r/|r|$ we get $$\widehat{f}(\omega,\xi,\eta) \approx \frac{\omega^2 e^{2\imath\omega \rho}}{\rho^2}\int_{\Omega} \frac{\exp(\imath\omega x\cdot(\xi + \eta))}{\rho^2} u(x)\mathrm{d}x,$$ which can be interpreted as a Fourier transform of $u$ evaluated at wavenumber $\omega (\xi + \eta)$. ``` * Assuming that measurements are available for $\omega \in [\omega_0,\omega_1]$, sketch which wavenumbers of $u$ can be stably reconstructed. In what sense is the problem ill-posed? ```{admonition} Answer :class: tip, dropdown We can retrieve $u$ from $\widehat{u}$ if we have samples of its Fourier transform everywhere. However, the data only gives us samples $\omega (\xi + \eta)$, where $\xi,\eta \in \mathbb{S}^2$. We can thus recover all samples in the unit sphere with radius $2\omega_1$. ``` ## Assignments ### Non-scattering potentials For $n=2$, $L=1$, $c=1$, with a single incident plane wave, $v_i(t,x) = \sin(\omega(t - \xi\cdot x))$, with direction $\xi$ and measurements parallel to the direction of propagation at the opposite end of the scattering potential. Use the Python code shown below to generate data for a given scattering potential, $r$. * Determine suitable $\Delta t$, $\Delta x$ and $T$ and generate data for scattering potential $u(x) = \exp(-200|x|^2)$ and an incident plane wave with $\xi = (1,0)$ and $\omega = 10\pi$. * Construct a non-scattering potential for this incident field and measurements by using the result you obtained in the previous exercise. * Can you construct a non-scattering potential that is invisible from multiple directions? ```{code-cell} ipython3 :tags: [hide-cell] import numpy as np import scipy.sparse as sp import matplotlib.pyplot as plt def solve(q,c,dt,dx,T=1.0,L=1.0,n=1): '''Solve n-dim wave equation using Leap-Frog scheme: u_{n+1} = Au_n + Bu_{n-1} + Cq_n''' # define some quantities gamma = dt*c/dx nt = int(T/dt + 1) nx = int(2*L/dx + 2) # q.resize((nx**n,nt)) # define matrices A,B,C,L = getMatrices(gamma,nx,n) # main loop u = np.zeros((nx**n,nt)) for k in range(1,nt-1): u[:,k+1] = A@u[:,k] + L@u[:,k] + B@u[:,k-1] + (dx**2)*C@q[:,k] return u def multiply(u,c,dt,dx,T=1.0,L=1.0,n=1): # define some quantities gamma = dt*c/dx nt = int(T/dt + 1) nx = int(2*L/dx + 2) # u.resize((nx**2,nt)) # define matrices A,B,C,L = getMatrices(gamma,nx,n) # main loop q = np.zeros((nx**n,nt)) for k in range(1,nt-1): q[k] = (u[:,k+1] - 2*u[:,k] + u[:,k-1] - L@u[:,k])/(dt*c)**2 return u def sample(xin,xout1,xout2=[]): '''Spatial sampling by simple interpolation''' if len(xout2): n = 2 else: n = 1 m = len(xout1) nx = len(xin) rw = [] cl = [] nz = [] if n == 1: for k in range(m): i = 0 while xin[i] < xout1[k]: i = i + 1 if i < nx - 1: a = (xout1[k] - xin[i+1])/(xin[i] - xin[i+1]) b = (xout1[k] - xin[i])/(xin[i+1] - xin[i]) rw.append(k) cl.append(i) nz.append(a) rw.append(k) cl.append(i+1) nz.append(b) P = sp.coo_matrix((nz,(rw,cl)),shape=(m,nx)) else: for k in range(m): i = 0 j = 0 while xin[i] < xout1[k]: i = i + 1 while xin[j] < xout2[k]: j = j + 1 if i < nx - 1 and j < nx - 1: a = (xout1[k] - xin[i+1])*(xout2[k] - xin[j+1])/(xin[i] - xin[i+1])/(xin[j] - xin[j+1]) b = (xout1[k] - xin[i])*(xout2[k] - xin[j+1])/(xin[i+1] - xin[i])/(xin[j] - xin[j+1]) c = (xout1[k] - xin[i+1])*(xout2[k] - xin[j])/(xin[i] - xin[i+1])/(xin[j+1] - xin[j]) d = (xout1[k] - xin[i])*(xout2[k] - xin[j])/(xin[i+1] - xin[i])/(xin[j+1] - xin[j]) rw.append(k) cl.append(i+nx*j) nz.append(a) rw.append(k) cl.append(i+1+nx*j) nz.append(b) rw.append(k) cl.append(i+nx*(j+1)) nz.append(c) rw.append(k) cl.append(i+1+nx*(j+1)) nz.append(d) P = sp.coo_matrix((nz,(rw,cl)),shape=(m,nx*nx)) return P def getMatrices(gamma,nx,n): # setup matrices l = (gamma**2)*np.ones((3,nx)) l[1,:] = -2*(gamma**2) l[1,0] = -gamma l[2,0] = gamma l[0,nx-2] = gamma l[1,nx-1] = -gamma if n == 1: a = 2*np.ones(nx) a[0] = 1 a[nx-1] = 1 b = -np.ones(nx) b[0] = 0 b[nx-1] = 0 c = (gamma)**2*np.ones(nx) c[0] = 0 c[nx-1] = 0 L = sp.diags(l,[-1, 0, 1],shape=(nx,nx)) else: a = 2*np.ones((nx,nx)) a[0,:] = 1 a[nx-1,:] = 1 a[:,0] = 1 a[:,nx-1] = 1 a.resize(nx**2) b = -np.ones((nx,nx)) b[0,:] = 0 b[nx-1,:] = 0 b[:,0] = 0 b[:,nx-1] = 0 b.resize(nx**2) c = (gamma)**2*np.ones((nx,nx)) c[0,:] = 0 c[nx-1,:] = 0 c[:,0] = 0 c[:,nx-1] = 0 c.resize(nx**2) L = sp.kron(sp.diags(l,[-1, 0, 1],shape=(nx,nx)),sp.eye(nx)) + sp.kron(sp.eye(nx),sp.diags(l,[-1, 0, 1],shape=(nx,nx))) A = sp.diags(a) B = sp.diags(b) C = sp.diags(c) return A,B,C,L ``` ```{code-cell} ipython3 :tags: [hide-cell] # grid nt = 201 nx = 101 x = np.linspace(-1,1,nx) y = np.linspace(-1,1,nx) t = np.linspace(0,1,nt) xx,yy,tt = np.meshgrid(x,y,t) # velocity c = 1.0 # scattering potential a = 200; r = np.exp(-a*xx**2)*np.exp(-a*yy**2); # incident field, plane wave at 10 Hz. omega = 2*np.pi*5 ui = np.sin(omega*(tt - (xx + 1)/c)) # solve us = solve(r*ui,c,t[1]-t[0],x[1]-x[0],n=2) # sample xr = 0.8*np.ones(101) yr = np.linspace(-1,1,101) P = sample(x,xr,yr) d = P@us # plot ui.resize((nx,nx,nt)) us.resize((nx,nx,nt)) plt.subplot(241) plt.imshow(ui[:,:,1]) plt.clim((-1,1)) plt.subplot(242) plt.imshow(ui[:,:,51]) plt.clim((-1,1)) plt.subplot(243) plt.imshow(ui[:,:,101]) plt.clim((-1,1)) plt.subplot(244) plt.imshow(ui[:,:,151]) plt.clim((-1,1)) plt.subplot(245) plt.imshow(us[:,:,1]) plt.clim((-.001,.001)) plt.subplot(246) plt.imshow(us[:,:,51]) plt.clim((-.001,.001)) plt.subplot(247) plt.imshow(us[:,:,101]) plt.clim((-.001,.001)) plt.subplot(248) plt.imshow(us[:,:,151]) plt.clim((-.001,.001)) plt.show() ``` ### Parameter estimation For $n=1$, $c=1$, $L=1$, $q(t,x) = w''(t - t_0)\delta(x - x_0)$, with $t_0 = 0.2$, $x_0 = -0.5$ and where $w$ is given by $$ w(t) = \exp(-(t/\sigma)^2/2). $$ * Express the solution $v(t,x)$ by using the Green function The measurements are given by $f(t) = K(c) \equiv v(t,0.5)$. Consider retrieving the soundspeed $c$ by minimizing $$ J(c) = \|K(c) - f\|^2. $$ * Plot the objective as a function of $c$ for various values of $\sigma$. * Do you think Newton's method will be successful in retrieving the correct $c$?
JavaScript
UTF-8
1,347
3.09375
3
[]
no_license
/** * Created by bilibili_ on 2016/6/15. */ "use strict" function demo (msg) { console.log("test"); } demo('Hi Hello World!'); let Test = require('./Test.js'); let t = new Test(); t.logTest(); var handler = { id: '123456', init: function() { document.addEventListener('click', event => this.doSomething(event.type), false); }, doSomething: function(type) { console.log('Handling ' + type + ' for ' + this.id); } }; handler.init(); // 假定某段buffer包含如下字节 [0x02, 0x01, 0x03, 0x07] var buffer = new ArrayBuffer(4); var v1 = new Uint8Array(buffer); v1[0] = 2; v1[1] = 1; v1[2] = 3; v1[3] = 7; var uInt32View = new Uint32Array(buffer); var a = uInt32View[0]; console.log(a.toString()); var uInt16View = new Uint16Array(buffer); console.log(uInt16View[0],uInt16View[1]); // 计算机采用小端字节序 // 所以头两个字节等于258 if (uInt16View[0] === 258) { console.log('OK'); // "OK" } // 赋值运算 uInt16View[0] = 255; // 字节变为[0xFF, 0x00, 0x03, 0x07] uInt16View[0] = 0xff05; // 字节变为[0x05, 0xFF, 0x03, 0x07] uInt16View[1] = 0x0210; // 字节变为[0x05, 0xFF, 0x10, 0x02] console.log(1e3, 5e3); import $ from 'jquery'; $(document).ready(function(){ $(document).on("click", function(e){ console.log("==>"+e) }) })
C++
UTF-8
2,679
3
3
[]
no_license
// // Created by rutger on 11/7/20. // #include "DistanceTableCollection.h" DistanceTableCollection::DistanceTableCollection(GL& gl, unsigned int numberOfSeedPoints) : smallestDistanceScore(std::numeric_limits<double>::max()), largestDistanceScore(std::numeric_limits<double>::min()) { distanceTables.reserve(numberOfSeedPoints); for(unsigned int i = 0; i < numberOfSeedPoints; i++) { distanceTables.emplace_back(DistanceTable(i)); } gl.glGenBuffers(1, &distance_scores_ssbo_id); } bool comparisonDistanceScorePtrs(double* score_ptr, double* score2_ptr) { return *score_ptr < *score2_ptr; } void DistanceTableCollection::InsertFiber(unsigned int seedPointId, Fiber* fiber) { DistanceTable& distanceTable = distanceTables.at(seedPointId); mtx.lock(); DistanceEntry* newDistanceEntry = distanceTable.InsertNewFiber(*fiber); distanceScores.resize( fiber->GetId() + 1, nullptr); distanceScores.at(fiber->GetId()) = &(newDistanceEntry->distance); sortedDistanceScores.push_back(&(newDistanceEntry->distance)); std::sort(sortedDistanceScores.begin(), sortedDistanceScores.end(), comparisonDistanceScorePtrs); if(newDistanceEntry->distance < smallestDistanceScore) { smallestDistanceScore = newDistanceEntry->distance; } else if(newDistanceEntry->distance > largestDistanceScore) { largestDistanceScore = newDistanceEntry->distance; } mtx.unlock(); } const DistanceTable& DistanceTableCollection::GetDistanceTable(unsigned int seedPointId) const { return distanceTables.at(seedPointId); } unsigned int DistanceTableCollection::GetNumberOfSeedPoints() const { return distanceTables.size(); } std::vector<double> DistanceTableCollection::GetDistanceScoreCopy() const { unsigned int numberOfScores = distanceScores.size(); std::vector<double> distanceScoresCopy; distanceScoresCopy.reserve(numberOfScores); for(int i = 0; i < numberOfScores; i++) { double* distanceScorePtr = distanceScores[i]; if(distanceScorePtr == nullptr) { distanceScoresCopy.push_back(std::numeric_limits<double>::max()); } else { distanceScoresCopy.push_back(*distanceScorePtr); } } return distanceScoresCopy; } double DistanceTableCollection::GetDistanceScoreForPercentage(float percentage) const { unsigned int numberOfFibers = sortedDistanceScores.size(); if(numberOfFibers == 0) { return 0; } int index = percentage * numberOfFibers - 1; if(index < 0) { return 0; } return *sortedDistanceScores[index]; }
SQL
UTF-8
5,735
3.375
3
[ "MIT" ]
permissive
-- -------------------------------------------------------- -- Host: localhost -- Server version: 10.1.21-MariaDB - mariadb.org binary distribution -- Server OS: Win32 -- HeidiSQL Version: 9.4.0.5125 -- -------------------------------------------------------- /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET NAMES utf8 */; /*!50503 SET NAMES utf8mb4 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; -- Dumping database structure for prod CREATE DATABASE IF NOT EXISTS `prod` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `prod`; -- Dumping structure for table prod.issue CREATE TABLE IF NOT EXISTS `issue` ( `Id_Issue` int(11) NOT NULL AUTO_INCREMENT, `Nom` varchar(50) NOT NULL DEFAULT '0', PRIMARY KEY (`Id_Issue`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- Dumping data for table prod.issue: ~4 rows (approximately) /*!40000 ALTER TABLE `issue` DISABLE KEYS */; INSERT INTO `issue` (`Id_Issue`, `Nom`) VALUES (1, 'Etiquetado'), (2, 'Firmado'), (3, 'Prueba'), (4, 'Ninguno'); /*!40000 ALTER TABLE `issue` ENABLE KEYS */; -- Dumping structure for table prod.migrations CREATE TABLE IF NOT EXISTS `migrations` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table prod.migrations: ~0 rows (approximately) /*!40000 ALTER TABLE `migrations` DISABLE KEYS */; /*!40000 ALTER TABLE `migrations` ENABLE KEYS */; -- Dumping structure for table prod.proceso CREATE TABLE IF NOT EXISTS `proceso` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `Serie` varchar(50) NOT NULL, `Mac` varchar(50) NOT NULL, `Lote` int(11) NOT NULL, `Id_Proceso` int(11) NOT NULL, `Fecha` date NOT NULL, `Id_Issue` int(11) NOT NULL, `P1` enum('on','off') NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- Dumping data for table prod.proceso: ~3 rows (approximately) /*!40000 ALTER TABLE `proceso` DISABLE KEYS */; INSERT INTO `proceso` (`Id`, `Serie`, `Mac`, `Lote`, `Id_Proceso`, `Fecha`, `Id_Issue`, `P1`) VALUES (2, '201604180399', '78:A3:51:12:9E:73', 21, 1, '2017-05-05', 1, ''), (3, '201604180405', '78:A3:51:12:93:AB', 21, 2, '2017-05-12', 3, ''), (4, '201604180416', '78:A3:51:12:9E:2B', 21, 1, '2017-05-08', 2, ''); /*!40000 ALTER TABLE `proceso` ENABLE KEYS */; -- Dumping structure for table prod.procesos CREATE TABLE IF NOT EXISTS `procesos` ( `Id_Proceso` int(11) NOT NULL AUTO_INCREMENT, `Nom` varchar(50) DEFAULT NULL, PRIMARY KEY (`Id_Proceso`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -- Dumping data for table prod.procesos: ~4 rows (approximately) /*!40000 ALTER TABLE `procesos` DISABLE KEYS */; INSERT INTO `procesos` (`Id_Proceso`, `Nom`) VALUES (1, 'Etiquetado'), (2, 'Maquinado'), (3, 'Firmado'), (4, 'Prueba'); /*!40000 ALTER TABLE `procesos` ENABLE KEYS */; -- Dumping structure for table prod.rol CREATE TABLE IF NOT EXISTS `rol` ( `Id_Rol` int(11) NOT NULL AUTO_INCREMENT, `Rol` varchar(50) NOT NULL, PRIMARY KEY (`Id_Rol`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; -- Dumping data for table prod.rol: ~2 rows (approximately) /*!40000 ALTER TABLE `rol` DISABLE KEYS */; INSERT INTO `rol` (`Id_Rol`, `Rol`) VALUES (1, 'Administrador'), (2, 'Estandar'); /*!40000 ALTER TABLE `rol` ENABLE KEYS */; -- Dumping structure for table prod.users CREATE TABLE IF NOT EXISTS `users` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, `Nom` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `Ap` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `Dpto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `Puesto` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `Id_Rol` int(11) NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- Dumping data for table prod.users: ~4 rows (approximately) /*!40000 ALTER TABLE `users` DISABLE KEYS */; INSERT INTO `users` (`Id`, `Nom`, `Ap`, `username`, `password`, `Dpto`, `Puesto`, `Id_Rol`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'Felix', 'Estrada', 'festrada', '$2y$10$ssVbHSmUvusjRi.irutu5e9Ru9tbWq68TqH7kqvgLzK1wN7B06dC6', 'Infraestructura', 'Soporte Interno', 2, 'j0jRvdTs8sgbF8ucu7VNDj1zw3E6xjxUv6AwYMyNC9xmwjqEEJkurdXVQzmg', NULL, NULL), (2, 'Cesar', 'Contreras', 'ccontreras', '$2y$10$z3mqekH0mp3bV8OckNkRz.ddfwQFuJRUkgMtDYzGp0gljinkCCX82', 'Infraestructura', 'Soporte Externo', 1, 'DbQceSHOtPEeq0FHCLdVbpC0OU5tZK7mhgvr9SN3OgGWVVO9EwzOGZTTU1ai', NULL, NULL), (3, 'Jorge', 'Lopez', 'jlopez', '$2y$10$8KxqnQ4BIw9iLOezvor7deEm8D3iPpBmUVhUQeHz2sAFQkxXHE2r.', 'Infraestructura', 'Soporte Interno', 1, 'LOZepMK5vPODRUaJqVwcEG5Fl5NbiNdMO50pz8PlRXaJZ1QjlyJsuuTy6GW1', NULL, NULL), (4, 'Carolina', 'Arce', 'carse', '$2y$10$crpu6WqEyxuvCwlWn0UXNue0Ykb9AUYU5FCxje2wt3BSavD5EkrLi', 'R.H', 'R.H', 1, NULL, NULL, NULL); /*!40000 ALTER TABLE `users` ENABLE KEYS */; /*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */; /*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
Java
UTF-8
1,594
2.0625
2
[]
no_license
package br.ufba.dcc.mestrado.computacao.openhub.data.organization; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import br.ufba.dcc.mestrado.computacao.openhub.data.OpenHubResultDTO; @XmlRootElement(name = OpenHubPortifolioProjectDTO.NODE_NAME) public class OpenHubPortifolioProjectDTO implements OpenHubResultDTO { /** * */ private static final long serialVersionUID = 6203597426768385191L; public final static String NODE_NAME = "project"; private String name; private String activity; private String primaryLanguage; private Long iUseThis; private Double communityRating; @XmlElement(name = "name") public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement(name = "activity") public String getActivity() { return activity; } public void setActivity(String activity) { this.activity = activity; } @XmlElement(name = "primary_language") public String getPrimaryLanguage() { return primaryLanguage; } public void setPrimaryLanguage(String primaryLanguage) { this.primaryLanguage = primaryLanguage; } @XmlElement(name = "i_use_this") public Long getiUseThis() { return iUseThis; } public void setiUseThis(Long iUseThis) { this.iUseThis = iUseThis; } @XmlElement(name = "community_rating") public Double getCommunityRating() { return communityRating; } public void setCommunityRating(Double communityRating) { this.communityRating = communityRating; } }
Python
UTF-8
691
2.84375
3
[]
no_license
def user_check(u): a=['-','.','_'] if u[0].isalpha(): for i in u: if i.isalnum() or (i in a): continue else: return False else: return False return True n=int(input()) for i in range(n): a=input() b=a.find('<') try: c=a[b+1:-1] c=c.split('@') u=c[0] c=c[1].split('.') d=c[0] c.remove(c[0]) if len(c)>1: c=''.join(c) e=c else: e=c[0] except IndexError: continue if user_check(u) and d.isalpha() and (len(e)<=3 and e.isalpha()): print(a)
C++
UTF-8
1,129
3.078125
3
[ "MIT" ]
permissive
// 1126 #include <stdio.h> #include <stdlib.h> #include <vector> using namespace std; int main() { int n, m; scanf("%d %d", &n, &m); vector<vector<int> > graph; graph.resize(n+1); for(int i=0; i<=n; i++) { graph[i].resize(n+1); for(int j=0; j<=n; j++) graph[i][j] = -1; } for(int i=0; i<m; i++) { int v1, v2; scanf("%d%d", &v1, &v2); graph[v1][v2] = 1; graph[v2][v1] = 1; } int degree[n+1]; bool isEu = true; bool isEp = true; int oddCnt = 0; for(int i=1; i<=n; i++) { int cnt = 0; for(int j=1; j<=n; j++) { if(graph[i][j] == 1) cnt++; } if(cnt%2 == 1 && cnt>0) { isEu = false; oddCnt++; } else if(cnt==0){ isEu = false; isEp = false; } degree[i] = cnt; printf("%d%c", cnt, i==n?'\n':' '); } if(isEu) printf("Eulerian"); else if(isEp && oddCnt == 2) printf("Semi-Eulerian"); else printf("Non-Eulerian"); return 0; }
Markdown
UTF-8
3,106
3.03125
3
[ "MIT" ]
permissive
Cache Info Bundle ==================== This bundle adds a simple command to dump information about HTTP Cache in a Symfony project. ## Installation ```sh composer require mapado/cache-info-bundle ``` ```php // AppKernel.php $bundles = array( ... new Mapado\CacheInfoBundle\MapadoCacheInfoBundle(), ); ``` ## Usage ```sh php app/console mapado:http-cache:list ``` Dumps a list of informations about your cache settings ```sh +------------------------------------------------------------------------------+----------------+---------+ | route + pattern | private | ttl | +------------------------------------------------------------------------------+----------------+---------+ | my_route | public | 6h | | /my/route | | | +------------------------------------------------------------------------------+----------------+---------+ | another route | public | 1d | | /another/route | | | +------------------------------------------------------------------------------+----------------+---------+ | a private route | private | null | | /private | | | +------------------------------------------------------------------------------+----------------+---------+ | a complex cache route | public|private | 4h|null | | /complex | | | +------------------------------------------------------------------------------+----------------+---------+ ``` ## Cache time definition By default, this command leverage the power of Sensio Framework bundle `@Cache` annotation. It works also fine with the route cache definition (for the `FrameworkBundle:Template:template` routes). ### Complex route cache | Manual cache settings If you have a complex route cache, or if you manually call `$response->setSMaxAge()` and `$response->setPublic()`, you need to use the `@CacheMayBe` annotation. #### Example ```php use Mapado\CacheInfoBundle\Annotation\CacheMayBe; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache; class FooController { /** * @CacheMayBe(values={@Cache(public=true, smaxage="14400"), @Cache(public=false)}) */ public function complexRouteAction() { $isPublic = // determine if your route is public ... $response->setPublic($isPublic); if ($isPublic) { $response->setSMaxAge(14400); } return $response; } } ``` If you don't do that, the route will be marked as `private`
Python
UTF-8
2,660
2.671875
3
[ "Apache-2.0", "MIT" ]
permissive
r"""Main routine to calculate ROUGE scores across text files. Designed to replicate scores computed by the ROUGE perl implementation as closely as possible. Output is a text file in CSV format. Sample usage: rouge ---rouge_types=rouge1,rouge2,rougeL \ --target_filepattern=*.targets \ --prediction_fliepattern=*.decodes \ --output_filename=scores.csv \ --use_stemmer Which is equivalent to calling the perl ROUGE script as: ROUGE-1.5.5.pl -m -e ./data -n 2 -a /tmp/rouge/settings.xml Where settings.xml provides target and decode text. """ import argparse from phramer.metrics.rouge import io from phramer.metrics.rouge import rouge_scorer from phramer.metrics.rouge import scoring import multiprocessing as mp def main(args): scorer = rouge_scorer.RougeScorer(args.rouge_types, args.use_stemmer) aggregator = scoring.BootstrapAggregator() if args.aggregate else None io.compute_scores_and_write_to_csv( args.target_filepattern, args.prediction_filepattern, args.output_filename, scorer, aggregator, delimiter=args.delimiter, num_workers=args.num_workers, ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--target-filepattern", default=None, type=str, help="Files containing target text.", required=True, ) parser.add_argument( "--prediction-filepattern", default=None, type=str, required=True, help="Files containing prediction text.", ) parser.add_argument( "--output-filename", default=None, type=str, help="File in which to write calculated ROUGE scores as a CSV", required=True, ) parser.add_argument( "--delimiter", default="\n", type=str, help="Record delimiter in files.", ) parser.add_argument( "--rouge-types", nargs="+", type=str, default=["rouge1", "rouge2", "rougeL"], help="List of ROUGE types to calculate.", ) parser.add_argument( "--use-stemmer", action="store_true", default=False, help="Whether to use Porter stemmer to remove common suffixes.", ) parser.add_argument( "--aggregate", action="store_true", default=True, help="Write aggregates if this is set to True", ) parser.add_argument( "--num-workers", type=int, default=mp.cpu_count() - 1, help="The number of workers for processing", ) args = parser.parse_args() print main(args)
Markdown
UTF-8
5,348
2.953125
3
[]
no_license
三一 第六十二回作“彩云”,但显然就是第三十九回大家说她老实的彩霞,偷了许多东西送贾环,反而受他的气,第七十二回他终于负心。 第三十九回与第二十五回同属X本。第三十三回作“彩云”、同回有早本漏改的“姆姆”二字。显然贾环的恋人原名彩云,至X本改名彩霞,从此彩云不过是一个名字,没有特点或个性。 全抄本第二十五回彩霞初出场的一段如下: 那贾环……一时又叫彩云倒茶,一时又叫金钏儿剪蜡花。众丫鬟素日原厌恶他,只有彩云(他本作“霞”)还和他合的来,倒了一杯茶递与他……悄悄向贾环说:“你安分些罢,……”贾环道:“……你别哄我,如今你和宝玉好,把我不大理论,我也看出来了。”彩云(他本作“霞”)道:“没良心的……”(以下统作“彩霞”) 此外还有歧异,但是最值得注意的是彩霞头两次作“彩云”,此后方改彩霞。 全抄本此回是宝玉烫伤一回与五鬼回删并的初稿。原先宝玉烫伤一回写贾环支使不动别人,至少叫彩云倒茶倒了给他,因为彩云跟他还合得来。今本强调众婢的鄙薄,叫彩云倒茶也不倒,还是彩霞倒了杯给他——也许彩云改名彩霞自此始。——这一点删并时已改,全抄本这两个“彩云”是漏网之鱼。这是全抄本是X本第二十五回初稿的又一证。 吴世昌著《红楼梦探源》,发现元妃本来死在第五十八回,后来改为老太妃薨,是此书结构上的一个重大的转变。第五十八回属于X本。 第五十四回也属于X本,庚本此回与下一回之间的情形特殊,第五十四回末句“且说当下元宵已过”,与下一回第一句“且说元宵已过”重复,当是底本在这一行划了道线,分成两回。未分前这句是“且说当下元宵已过”,“当下”二字上承前段。这句挪到下一回回首,“当下”语气不合,因此删去。大概勾划得不够清楚,抄手把原来的一句也保存了。分回处没加“下回分解”,显然是X本把第五十四、五十五合回分成两回,所以不用回末套语。新的第五十五回仍旧保有第五十四、五十五合回的回末套语。 第五十五回开始,“且说元宵已过”底下紧接着就是庚本独有的太妃病一节,伏老太妃死。一回稿本最取巧的改写法是在回首加一段,这是又一例。如果在X本之前已经改元妃之死为老太妃死,无法加上第五十五回回首太妃病的伏笔,因为第五十四、五十五合回还没有一分为二。显然是X本改掉第五十八回元妃之死。 庚本八张回目页,也就是十回本的封面。内中七张有“脂砚斋凡四阅评过”字样,下半部有三张又有“庚辰秋月定本”或“庚辰秋定本”。唯一的例外是第六册,回目页上只有书名“石头记”与回目,前面又多一张题页,上书“石头记第五十一回至六十回”,是这十回本的封面。回目页背面有三行小字: 第五十一回 至六十回 脂砚斋凡四阅评过 庚辰秋定本 题页已有回数,这里又再重一遍,叠床架屋,显然不是原定的格式。这十回当是另一来源,编入“庚辰秋定本”的时候草草添上这本子的标志。 上半部四张回目页都没有日期。第四册的一张,上有“村嫽嫽是信口贻开河”句,在第三十九回回首已经改为“村姥姥是信口开河”。第三十九、四十两回属于X本。第四十一回正文“姥姥”最初三次都作“嫽嫽”,将此回与上十回的回目页连在一起,形成此本中部一个共同的基层。至少这一部份是个早本,还在用“嫽嫽”。第三十九、四十这两回是X本改写抽换的。 第一张回目页上“刘姥姥一进荣国府”,“嫽”已改“姥”,与第三十一至四十回的回目页显然不同时,是拼凑上白文本的时候,抄配一张回目页,——白文本本身没有回目页——所以照着第六回回首的回目抄作“姥”。这一张回目页可以撇开不算。 白文本与抄配的两回当然不算,另一来源的第六册虽然编入“庚辰秋定本”,也暂时搁过一边。此外的正文与回目页有些共同的特点,除了中部的“嫽嫽”,还有第十二回回末“林儒海”病重,第十四回回目作“林儒海捐馆扬州城”,回目页上也作“儒海”,可知林如海原名儒海;第十七、十八合回未分回,第十九、第八十回尚无回目,也都反映在回目页上。但是下半部也有几处不同,如第四十六回回目“鸳鸯女誓绝鸳鸯偶”,回目页上作“鸳鸯女誓绝鸳鸯女”(女误,改侣,同戚本);第四十九回“琉璃世界白雪红梅”,回目页上作“瑠璃”。 戚本保留了一些极旧的回目,因此第四十六回回目该是“鸳鸯侣”较早。“琉璃”是通行的写法,当是先写作“瑠璃”,后改“琉”。庚本下半部回目页与各回歧异处,都是回目页较老。那是因为这几回经过改写抽换,所以比回目页新。
Markdown
UTF-8
24
2.71875
3
[]
no_license
# mrwebivuyisa.github.io
Java
UTF-8
3,504
2.140625
2
[ "Apache-2.0" ]
permissive
package com.luanguan.mcs.empty_roll_location.infrastructure; import com.luanguan.mcs.empty_roll_location.domain.*; import com.luanguan.mcs.framework.domain.Version; import com.luanguan.mcs.mission.domain.MissionId; import com.luanguan.mcs.shared_kernel.BatteryModel; import com.luanguan.mcs.shared_kernel.Position; import com.luanguan.mcs.winding_machine.domain.ElectrodeType; import org.hibernate.annotations.OptimisticLockType; import org.hibernate.annotations.OptimisticLocking; import javax.persistence.*; import static com.luanguan.mcs.empty_roll_location.infrastructure.EmptyRollLocationJpaEntity.EmptyRollLocationState.*; import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; @Entity @Table(name = "t_empty_roll_location") @OptimisticLocking(type = OptimisticLockType.VERSION) class EmptyRollLocationJpaEntity { @Id @GeneratedValue Long id; @Column(nullable = false) String rack_position; @Column(nullable = false) String position; @Column(nullable = false) EmptyRollLocationState state; String battery_model; int electrode_type; Long mission_id; @javax.persistence.Version @Column(nullable = false) int version_number; EmptyRollLocation toDomainModel() { return Match(state).of( Case($(Loaded), () -> new LoadedEmptyRollLocation( new EmptyRollLocationInformation( new EmptyRollLocationId(id), new Position(rack_position), new Position(position) ), new Version(version_number), new BatteryModel(battery_model), ElectrodeType.getByValue(electrode_type) )), Case($(Loading), () -> new LoadingEmptyRollLocation( new EmptyRollLocationInformation( new EmptyRollLocationId(id), new Position(rack_position), new Position(position) ), new Version(version_number), new BatteryModel(battery_model), ElectrodeType.getByValue(electrode_type), new MissionId(mission_id) )), Case($(Unloaded), () -> new UnloadedEmptyRollLocation( new EmptyRollLocationInformation( new EmptyRollLocationId(id), new Position(rack_position), new Position(position) ), new Version(version_number) )), Case($(Unloading), () -> new UnloadingEmptyRollLocation( new EmptyRollLocationInformation( new EmptyRollLocationId(id), new Position(rack_position), new Position(position) ), new Version(version_number), new BatteryModel(battery_model), ElectrodeType.getByValue(electrode_type), new MissionId(mission_id) )) ); } enum EmptyRollLocationState { Loaded, Loading, Unloaded, Unloading } }
Swift
UTF-8
3,747
2.703125
3
[]
no_license
import KeychainAccess protocol LastSuccessLoginHolder { var lastSuccessLogin: String? { get } } enum AuthorizationStatus { case notAuthorized case authorized(jwt: String) } protocol AuthorizationStatusHolder: class { var authorizationStatus: AuthorizationStatus { get } var isAuthorized: Bool { get } } protocol LoginResponseProcessor: class { func processLoginResponse(_ loginResponse: LoginResponse) } protocol LogoutService: class { func processLogoutAction(completion: (() -> ())?) } final class AuthInfoHolder: LastSuccessLoginHolder, AuthorizationStatusHolder, LoginResponseProcessor, LogoutService { // MARK: - Properties private let syncQueue = DispatchQueue(label: "ru.dricom.AuthInfoHolderImpl.syncQueue") // MARK: - Keys private let authInfoKeychainServiceKey = "ru.dricom.keychain.authInfo" private let jwtKey = "jwt" private let lastSuccessLoginKey = "lastSuccessLogin" // MARK: - In-memory storage private var jwtStorage: String? private var lastSuccessLoginStorage: String? // MARK: - Init init() { // Load persistent session info once let loadedAuthInfo = loadSessionInfo() jwtStorage = loadedAuthInfo.jwt lastSuccessLoginStorage = loadedAuthInfo.lastSuccessLogin } // MARK: - LoginResponseProcessor func processLoginResponse(_ loginResponse: LoginResponse) { syncQueue.async { let authInfoKeychain = Keychain(service: self.authInfoKeychainServiceKey) .accessibility(.afterFirstUnlock) self.lastSuccessLoginStorage = loginResponse.user.email self.jwtStorage = loginResponse.jwt try? authInfoKeychain.removeAll() try? authInfoKeychain.set(loginResponse.jwt, key: self.jwtKey) if let email = loginResponse.user.email { try? authInfoKeychain.set(email, key: self.lastSuccessLoginKey) } } } // MARK: - LogoutService func processLogoutAction(completion: (() -> ())?) { syncQueue.async { self.jwtStorage = nil let authInfoKeychain = Keychain(service: self.authInfoKeychainServiceKey) .accessibility(.afterFirstUnlock) try? authInfoKeychain.remove(self.jwtKey) DispatchQueue.main.async { completion?() } } } // MARK: - LastSuccessLoginHolder var lastSuccessLogin: String? { get { var result: String? syncQueue.sync { result = self.lastSuccessLoginStorage } return result } } // MARK: - AuthorizationStatusHolder var jwt: String? { get { var result: String? syncQueue.sync { result = self.jwtStorage } return result } } var authorizationStatus: AuthorizationStatus { if let jwt = jwt { return .authorized(jwt: jwt) } else { return .notAuthorized } } var isAuthorized: Bool { switch authorizationStatus { case .authorized: return true case .notAuthorized: return false } } // MARK: - Private private func loadSessionInfo() -> (jwt: String?, lastSuccessLogin: String?) { let authInfoKeychain = Keychain(service: authInfoKeychainServiceKey) .accessibility(.afterFirstUnlock) return (jwt: authInfoKeychain[jwtKey], lastSuccessLogin: authInfoKeychain[lastSuccessLoginKey]) } }
C#
UTF-8
2,884
3.328125
3
[ "MIT", "zlib-acknowledgement" ]
permissive
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt using System; namespace NUnit.Common { /// <summary> /// Class used to guard against unexpected argument values /// or operations by throwing an appropriate exception. /// </summary> public static class Guard { /// <summary> /// Throws an exception if an argument is null /// </summary> /// <param name="value">The value to be tested</param> /// <param name="name">The name of the argument</param> public static void ArgumentNotNull(object value, string name) { if (value == null) throw new ArgumentNullException("Argument " + name + " must not be null", name); } /// <summary> /// Throws an exception if a string argument is null or empty /// </summary> /// <param name="value">The value to be tested</param> /// <param name="name">The name of the argument</param> public static void ArgumentNotNullOrEmpty(string value, string name) { ArgumentNotNull(value, name); if (value == string.Empty) throw new ArgumentException("Argument " + name +" must not be the empty string", name); } /// <summary> /// Throws an ArgumentOutOfRangeException if the specified condition is not met. /// </summary> /// <param name="condition">The condition that must be met</param> /// <param name="message">The exception message to be used</param> /// <param name="paramName">The name of the argument</param> public static void ArgumentInRange(bool condition, string message, string paramName) { if (!condition) throw new ArgumentOutOfRangeException(paramName, message); } /// <summary> /// Throws an ArgumentException if the specified condition is not met. /// </summary> /// <param name="condition">The condition that must be met</param> /// <param name="message">The exception message to be used</param> /// <param name="paramName">The name of the argument</param> public static void ArgumentValid(bool condition, string message, string paramName) { if (!condition) throw new ArgumentException(message, paramName); } /// <summary> /// Throws an InvalidOperationException if the specified condition is not met. /// </summary> /// <param name="condition">The condition that must be met</param> /// <param name="message">The exception message to be used</param> public static void OperationValid(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } } }
Java
UTF-8
373
1.734375
2
[]
no_license
package gg.babble.babble.dto.request; import java.util.List; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @AllArgsConstructor @NoArgsConstructor public class TagUpdateRequest { @NotNull private String name; @NotNull private List<String> alternativeNames; }
Markdown
UTF-8
2,827
2.625
3
[]
no_license
## 논문에서의 앙상블 - high level feature 더 높은 차원의 feature - low level feature 텍스쳐 같은 느낌 ## 앙상블 - 앙상블 기법은 weak learner 을 잘 조합해서 strong learner를 만드는것을 목표로 한다 - 현실에서의 기능은 개개인의 능력을 갖고있는 팀원들을 모아 개인이서 할수없는일을 해내는 것이 앙상블이다 >> 앙상블기법에는 대표적으로 bagging과 boosting이 있다 - bagging은 기본 데이터셋을 샘플링하여 n개의 데이터셋을 만들어서 n개의 모델을 학습시켜 최종 결정을 하는 모델이다. 샘플링을 마치고 나면 n개의 모델이 독립적으로 동시에 각각의 데이터셋을 학습할 수 있으므로 속도가 빠르다. 이 때문에 병렬적이라고 이야기한다. - boosting에서는 첫번째 모델이 기본 데이터셋을 그대로 학습을 한다. 그 다음 두번째 모델은 전체 데이터를 학습하되 첫번째 모델이 에러를 일으킨 데이터에 더 큰 중점을 두고 학습을 진행한다. 세번째는 앞의 두 모델이 힘을 합쳐도 맞추지 못한 데이터에 중점을 두고 학습을 진행한다. 앞 모델의 학습이 끝나야 뒷 모델이 그 결과를 기반으로하여 가중치를 결정하고 학습을 할 수 있기 때문에 순차적으로 학습을 해야한다. 이 때문에 직렬적이라고 이야기하며 상대적으로 속도가 느리다. - 예를 들면 bagging은 10000개의 데이터를 2000개씩 5조로 나누어 5개의 모델이 병렬로 학습을 진행하며 boosting은 5개의 모델이 모두 10000개의 데이터를 학습하되 어느 데이터를 중점으로 학습할지에 차이가 있고, 그 결정은 앞 모델들의 학습결과에 기반하여 결정한다. #### 모델의 bias와 variation(편의상 아래에서는 task는 classification이라고 생각하고 서술) - 알고리즘의 bias가 크다는 것은 모델이 정상적으로 학습을 마친 후 정확도가 기대치보다 떨어지는 것을 말한다. 이는 under fitting이라고도 생각할 수 있다. 구체적으로는 이상적인 decision boundary에 비해 지나치게 단순한 decision boundary(예를 들어 직선)를 사용한 경우이다. ![dkdtkdqmf](https://t1.daumcdn.net/cfile/tistory/997396365BA26D2C35) - 알고리즘의 variation이 크다는 것은 정상적으로 학습을 마친 후 새로운 데이터셋에 대해서는 그 결과가 매우 다르게 나오는 것을 이야기한다. 이는 overfitting이라고 생각할 수 있다. 구체적으로는 이상적인 decision boundary보다 지나치게 복잡한 decision boundary(복잡한 곡선)를 사용한 경우이다. ![dkdtkd](https://t1.daumcdn.net/cfile/tistory/99AA05365BA26D2E2F)
Python
UTF-8
1,299
3.21875
3
[]
no_license
#14_QCheckBox.py - under QWidgetDemo from PyQt5.QtWidgets import QDialog, QLineEdit, QPushButton, QVBoxLayout, QApplication, QLabel, QCheckBox import sys class QWidgetDemos(QDialog): def __init__(self): QDialog.__init__(self) self.setWindowTitle("QWidgets Demo") #ex2-to make handler to check whether checkbox is checked or not #1stmake checkbox-into an instance wide variable, by adding self. self.checkbox = QCheckBox() self.checkbox.setText("Check me..!") #ex1-To keep it checked, by default #checkbox.setChecked(True) close_button = QPushButton("Close") close_button.clicked.connect(self.close) layout = QVBoxLayout() layout.addWidget(self.checkbox) layout.addWidget(close_button) self.setLayout(layout) self.setFocus() #ex3-cont'd #3rd connect the Signal and Slot self.checkbox.stateChanged.connect(self.selected) #ex2-cont'd #2ndDefine a method handler- To check the status of Checkbox def selected(self): if self.checkbox.isChecked(): print("Yes, it is Checked..!") else: print("It is UnChecked, now..!") app = QApplication(sys.argv) dialog = QWidgetDemos() dialog.show() app.exec_()
C#
UTF-8
4,064
2.546875
3
[]
no_license
using SharpDX.Core; using SharpDX.Direct2D1; using SharpDX.DirectWrite; using SharpDX.Mathematics.Interop; namespace SharpDX.UI.Controls { class Label : UiControlBase { private TextFormat _format; private TextLayout _layout; private Brush _brush; private Color4 _color; private TextAlignment _horizontalAlignment; private ParagraphAlignment _verticalAlignment; private WordWrapping _wrap; private string _fontName; private float _fontSize; private bool _isTextLayoutValid; private bool _isTextFormatValid; private bool _isTextBrushValid; public string Text {get; private set;} public Label(string fontName = "Calibri", float fontSize = 16) { _fontName = fontName; _fontSize = fontSize; _horizontalAlignment = TextAlignment.Leading; _verticalAlignment = ParagraphAlignment.Near; _wrap = WordWrapping.Wrap; } protected override void Dispose(bool disposing) { Utilities.Dispose(ref _brush); Utilities.Dispose(ref _format); Utilities.Dispose(ref _layout); base.Dispose(disposing); } public Label SetText(string text) { this.Text = text; _isTextLayoutValid = false; return this; } public Label SetFontName(string name) { this._fontName = name; _isTextFormatValid = false; return this; } public Label SetFontSize(float size) { this._fontSize = size; _isTextFormatValid = false; return this; } public Label SetWrap(WordWrapping wrap) { this._wrap = wrap; _isTextFormatValid = false; return this; } public Label SetColor(ref Color4 color) { this._color = color; _isTextBrushValid = false; return this; } public Label SetColor(float r, float g, float b, float a) { this._color.Red = r; this._color.Green = g; this._color.Blue = b; this._color.Alpha = a; _isTextBrushValid = false; return this; } public Label SetHorizontalAlignment(TextAlignment alignment) { this._horizontalAlignment = alignment; _isTextFormatValid = false; return this; } public Label SetVerticalAlignment(ParagraphAlignment alignment) { this._verticalAlignment = alignment; _isTextFormatValid = false; return this; } public override void Render(Context context, UiManager uiMgr) { if (string.IsNullOrEmpty(Text)) return; if (!_isTextFormatValid) { Utilities.Dispose(ref _format); _format = new TextFormat(context.FactoryDWrite, _fontName, _fontSize) { TextAlignment = _horizontalAlignment, ParagraphAlignment = _verticalAlignment, WordWrapping = _wrap, }; _isTextFormatValid = true; } if (!_isTextLayoutValid) { Utilities.Dispose(ref _layout); var w = Program.FormWidth * Size.X; var h = Program.FormHeight * Size.Y; _layout = new TextLayout(context.FactoryDWrite, Text, _format, w, h); _isTextLayoutValid = true; } if (!_isTextBrushValid) { Utilities.Dispose(ref _brush); _brush = context.GetBrush(ref _color); _isTextBrushValid = true; } var p = new RawVector2(ScreenPosition.X * Program.FormWidth, ScreenPosition.Y * Program.FormHeight); context.BeginText(); context.RenderTarget2D.DrawTextLayout(p, _layout, _brush, DrawTextOptions.None); context.EndText(); } } }
PHP
UTF-8
2,699
2.78125
3
[]
no_license
<!DOCTYPE html> <html> <head> <title>All Orders</title> <meta name="Author" value="Chris Card"> <link rel="stylesheet" type="text/css" href="view_all_orders.css"> </head> <body> <?php $orders = load_orders(); function load_orders(){ $orders = array(); ini_set('auto_detect_line_endings',true); $DB_NAME = 'mysql'; $DB_HOST = 'localhost'; $DB_USER = 'root'; $DB_PASS = 'test'; $mysqli = new mysqli($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME); if (mysqli_connect_errno()) { die ("Connection faild: ".mysqli_connect_errno()."\n"); trigger_error("Failed to connect ot sql db"); exit; } $query = "SELECT Name, Customer, Orders.Price as Price, Quantity, D as Date FROM Orders INNER JOIN Products on Orders.Prod = Products.ID"; $result = $mysqli->query($query) or die($mysqli->error.__LINE__); if($result->num_rows > 0){ while ($row = $result->fetch_assoc()) { if(array_key_exists($row['Customer'], $orders)){ $tmp = array("Date"=>$row['Date'], "Drinks"=>$row['Quantity'], "Drink"=>$row['Name'],"Price"=>$row['Price']); array_push($orders[$row['Customer']],$tmp); } else { $tmp = array("Date"=>$row['Date'], "Drinks"=>$row['Quantity'], "Drink"=>$row['Name'],"Price"=>$row['Price']); $tmp_array2 = array(); array_push($tmp_array2, $tmp); $orders[$row['Customer']] = $tmp_array2; } } } mysqli_close($mysqli); ksort($orders); return $orders; } function generate_detail_page($orders) { if(sizeof($orders) == 0){ echo "<p style=\"font-size: 200%; color: #FF0000; margin-left: 20px;\">There are no orders to load!</p>"; return; } $grand_total = 0; foreach ($orders as $key => $value) { $total = 0; echo "<div class=\"cust_order\">"; echo "<p class=\"cust_title\"> Orders for: "."<span class=\"name_sp\">".$key."</span></p>"; echo "<ul>"; for ($i=0; $i < sizeof($value); $i++) { $total += $value[$i]["Price"]; $tmp = "On ".$value[$i]["Date"]." ordered ".$value[$i]["Drinks"]." ".$value[$i]["Drink"]." Total: \$".number_format($value[$i]["Price"],2); echo "<li class=\"order_item\">".$tmp."</li>"; } echo "</ul>"; echo "<p class=\"customer_total\">Customer total: \$".number_format($total,2)."</p><br>"; $grand_total += $total; echo "</div>"; } echo "<p class=\"grand_total\">Grand total: \$".number_format($grand_total,2)."</p>"; } ?> <h1>Chris's Coffee Shop</h1> <p id="order_head">Customer Orders:</p> <div id="order_detail"> <?php generate_detail_page($orders); ?> </div> </body> </html>
JavaScript
UTF-8
1,444
2.71875
3
[]
no_license
import { useReducer } from 'react'; function reducer(state, action) { switch (action.type) { case 'LOGIN': return { ...action.payload }; case 'SIGN_UP': return console.log('SIGN_UP REDUCER'); default: throw new Error(); } } const initialState = { isAuthenticated: false, error: '', }; const useAuth = () => { const [user, dispatch] = useReducer(reducer, initialState); useAuth.login = async (type, res, cb) => { const response = await res; let payload; if (response.access_token) { payload = { ...response, isAuthenticated: true }; localStorage.setItem('authUser', JSON.stringify({ ...response })); } else { payload = { isAuthenticated: false, error: response.message || 'SOMETHING_WENT_WRONG', }; } dispatch({ type, payload }); cb(payload); }; useAuth.signUp = async (type, res, cb) => { const response = await res; let payload; if (!response.id) { payload = { error: response.message || 'SOMETHING_WENT_WRONG', }; } dispatch({ type, payload }); cb(payload); }; useAuth.forgotPassword = async (res, cb) => { const response = await res; const payload = { msg: response.msg || 'SOMETHING_WENT_WRONG', }; cb(payload); }; useAuth.isAuthenticated = JSON.parse(localStorage.getItem('authUser')); return [user, dispatch]; }; export default useAuth;
Java
UTF-8
407
2.265625
2
[]
no_license
package test; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; /** * @author huanyao * @version 1.0 * @ClassName CustomLoggerFactory.java * @Description TODO(用一句话描述该文件做什么) * @date 2021/7/12 4:14 下午 */ public class CustomLoggerFactory implements ILoggerFactory { @Override public Logger getLogger(String name) { return new CustomLogger(); } }
C
UTF-8
2,365
2.625
3
[]
no_license
/* ** EPITECH PROJECT, 2024 ** MUL_my_rpg_2019 ** File description: ** Created by Leo Fabre */ #include "rpg.h" void give_popo(t_rpg *rpg, int fight_count) { switch (fight_count) { case 1: add_to_inventory(rpg, 5); add_xp(rpg, 75); break; case 3: add_to_inventory(rpg, 8); add_xp(rpg, 75); break; case 5: add_to_inventory(rpg, 10); add_xp(rpg, 75); break; case 7: add_to_inventory(rpg, 9); add_xp(rpg, 75); break; } } void end_fight(t_rpg *rpg) { static int fight_count = 0; rpg->fight->opponent->health = 0; rpg->fight->opponent = NULL; add_xp(rpg, 75); rpg->character->quests->stats->kill++; rpg->gamestate = GAMELOOP; give_popo(rpg, fight_count); fight_count++; } void fightloop_2(t_rpg *rpg) { display_attack_particle(rpg); draw_text_levitate(rpg, rpg->hud->pnj_details[TEXT_MPV], &rpg->hud->details_mob_pv, rpg->hud->clock[2]); draw_text_levitate_mob(rpg, rpg->hud->pnj_details[3], &rpg->hud->details_pv, rpg->hud->clock[3]); display_inventory(rpg); sfRenderWindow_display(rpg->window); } void fightloop(t_rpg *rpg) { sfRenderWindow_clear(rpg->window, sfBlack); display_backgroud(rpg); display_items(rpg); display_mobs(rpg); display_character(rpg); display_hud(rpg); if (rpg->fight->is_player_turn == TRUE) { update_progression(rpg); draw_progress_bar(rpg); } else { if (rpg->fight->opponent->health <= 0) { end_fight(rpg); return; } else if (rpg->character->health <= 0) { rpg->gamestate = GAMEOVERLOOP; return; } mob_attack(rpg); } fightloop_2(rpg); } void analyze_fight_events(t_rpg *rpg) { if (rpg->event.type == sfEvtClosed) sfRenderWindow_close(rpg->window); if (sfKeyboard_isKeyPressed(sfKeySpace) == sfTrue && rpg->fight->pressing_atk == FALSE && rpg->fight->is_player_turn == TRUE) { attack(rpg); rpg->fight->pressing_atk = TRUE; } if (sfKeyboard_isKeyPressed(sfKeySpace) == sfFalse) rpg->fight->pressing_atk = FALSE; if (sfKeyboard_isKeyPressed(sfKeyEscape) == sfTrue) { rpg->old_gamestate = FIGHTLOOP; rpg->gamestate = PAUSELOOP; } }
Go
UTF-8
1,326
3.234375
3
[ "MIT" ]
permissive
package apns import "encoding/json" // BadgeNumber is much a NullInt64 in // database/sql except instead of using // the nullable value for driver.Value // encoding and decoding, this is specifically // meant for JSON encoding and decoding type BadgeNumber struct { Number uint IsSet bool } // Unset will reset the BadgeNumber to // both 0 and invalid func (b *BadgeNumber) Unset() { b.Number = 0 b.IsSet = false } // Set will set the BadgeNumber value to // the number passed in, assuming it's >= 0. // If so, the BadgeNumber will also be marked valid func (b *BadgeNumber) Set(number uint) { b.Number = number b.IsSet = true } // MarshalJSON will marshall the numerical value of // BadgeNumber func (b BadgeNumber) MarshalJSON() ([]byte, error) { return json.Marshal(b.Number) } // UnmarshalJSON will take any non-nil value and // set BadgeNumber's numeric value to it. It assumes // that if the unmarshaller gets here, there is a // number to unmarshal and it's valid func (b *BadgeNumber) UnmarshalJSON(data []byte) error { err := json.Unmarshal(data, &b.Number) if err != nil { return err } // Since the point of this type is to // allow proper inclusion of 0 for int // types while respecting omitempty, // assume that set==true if there is // a value to unmarshal b.IsSet = true return nil }
SQL
UTF-8
650
4.15625
4
[]
no_license
SELECT pr . *, r.rating, r.comment, r.id AS review_id, u.username, b.name AS brand_name FROM (SELECT p . *, r.product_id, MAX(r.date_created) AS review_date FROM (SELECT * FROM product WHERE product.brand_id = ? ORDER BY date_created DESC LIMIT 0 , 10) p LEFT JOIN review r ON r.product_id = p.id GROUP BY p.id) pr LEFT JOIN review r ON r.product_id = pr.product_id AND r.date_created = pr.review_date LEFT JOIN user u ON u.id = r.user_id LEFT JOIN brand b ON b.id = pr.brand_id ORDER BY pr.date_created DESC;
JavaScript
UTF-8
1,186
2.703125
3
[ "MIT" ]
permissive
import React, { Component } from 'react' import ThemeSwitcher from 'react-css-vars' const myFirstTheme = { myBackground: 'palevioletred', myColor: 'purple', myAccent: 'darkred', } const mySecondTheme = { myBackground: 'red', myColor: 'yellow', myAccent: 'blue', } const themes = [myFirstTheme, mySecondTheme] export default class App extends Component { state = { themeIndex: null, } handleToggleTheme = themeIndex => { this.setState({ themeIndex }) } render() { const { themeIndex } = this.state return ( <ThemeSwitcher theme={themeIndex != null ? themes[themeIndex] : null} elementId="root"> <div className="exampleText"> <div> Hello I am example, <span>colored</span> using css variables. </div> <div> <button onClick={() => this.handleToggleTheme(null)}>Reset</button> <button onClick={() => this.handleToggleTheme(0)}>Theme 1</button> <button onClick={() => this.handleToggleTheme(1)}>Theme 2</button> </div> <a href="https://github.com/karl-run/react-css-vars">Source</a> </div> </ThemeSwitcher> ) } }
PHP
UTF-8
594
2.625
3
[]
no_license
<?php session_start(); function __autoload($classname) { include_once ('./classes/'. $classname .'.php'); } $email = isset( $_SESSION['registratie']['email'] ) ? $_SESSION['registratie']['email'] : ''; $pass = isset( $_SESSION['registratie']['pass'] ) ? $_SESSION['registratie']['pass'] : ''; if (isset($_POST['submit'])) { if (User::authenticate()) { Message::setMessage('U bent ingelogd.', 'success'); Header('Location: dashboard.php'); } else{ Message::setMessage('Er ging iets mis. Probeer opnieuw.', 'error'); Header('Location: login-form.php'); } } ?>
PHP
UTF-8
1,580
2.6875
3
[ "MIT" ]
permissive
<?php namespace net\pixeldepth; use net\pixeldepth\warframe\Warframe; final class Request_Listener { public static $action = ""; public static $page = ""; public static function listen(){ Utils :: clean_get(); self :: get_action(); self :: get_page(); self :: monitor(); } private static function get_action(){ if(isset($_GET["action"])){ self :: $action = strtolower(Utils :: strict_clean(str_replace("-", "_", $_GET["action"]))); } } private static function get_page(){ if(isset($_GET["page"])){ self :: $page = strtolower(Utils :: strict_clean(str_replace("-", "_", $_GET["page"]))); } } private static function monitor(){ /** * Each action loads a class, so we will check to see * if a class exists first */ $class = (empty(self :: $action))? "index" : self :: $action; $path = ($class == "admin")? PRIVATE_PATH : PUBLIC_PATH; $default = $path . "index.php"; $path .= $class . ".php"; if($class == "admin" && isset(self :: $page) && !empty(self :: $page)){ $path = PRIVATE_PATH . self :: $page . ".php"; $class = self :: $page; } if(!file_exists($path)){ if(file_exists($default)){ $path = $default; $class = "index"; } else { $path = $class = false; } } if($path){ $class_name = ucwords($class); if($class_name){ require_once($path); if(class_exists($class_name)){ $klass = new $class_name(Warframe :: $twig, Warframe :: $twig_loader); if(method_exists($klass, "init")){ $klass -> init(); } return; } } } exit(); } }
Java
UTF-8
5,421
2.234375
2
[]
no_license
package com.ejavashop.service.impl.member; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import com.ejavashop.core.ConstantsEJS; import com.ejavashop.core.PagerInfo; import com.ejavashop.core.ServiceResult; import com.ejavashop.core.exception.BusinessException; import com.ejavashop.entity.member.MemberCollectionProduct; import com.ejavashop.model.member.MemberCollectionProductModel; import com.ejavashop.service.member.IMemberCollectionProductService; import com.ejavashop.vo.member.FrontMemberCollectionProductVO; /** * * */ @Service(value = "memberCollectionProductService") public class MemberCollectionProductServiceImpl implements IMemberCollectionProductService { private static Logger log = LogManager .getLogger(MemberCollectionProductServiceImpl.class); @Resource private MemberCollectionProductModel memberCollectionProductModel; /** * 根据id取得会员收藏商品表 * @param memberCollectionProductId * @return */ @Override public ServiceResult<MemberCollectionProduct> getMemberCollectionProductById(Integer memberCollectionProductId) { ServiceResult<MemberCollectionProduct> result = new ServiceResult<MemberCollectionProduct>(); try { result.setResult(memberCollectionProductModel .getMemberCollectionProductById(memberCollectionProductId)); } catch (Exception e) { log.error("根据id[" + memberCollectionProductId + "]取得会员收藏商品表时出现未知异常:" + e); result.setSuccess(false); result.setMessage("根据id[" + memberCollectionProductId + "]取得会员收藏商品表时出现未知异常"); } return result; } /** * 根据会员id取得会员收藏商品表 * @param request * @param pager * @return */ @Override public ServiceResult<List<FrontMemberCollectionProductVO>> getCollectionProductByMemberId(Map<String, Object> queryMap, Integer memberId, PagerInfo pager) { ServiceResult<List<FrontMemberCollectionProductVO>> serviceResult = new ServiceResult<List<FrontMemberCollectionProductVO>>(); try { serviceResult.setResult(memberCollectionProductModel .getCollectionProductByMemberId(queryMap, memberId, pager)); } catch (BusinessException be) { serviceResult.setSuccess(false); serviceResult.setMessage(be.getMessage()); } catch (Exception e) { serviceResult.setError(ConstantsEJS.SERVICE_RESULT_CODE_SYSERROR, "服务异常,请联系系统管理员。"); log.error( "[memberCollectionProductService][getCollectionProductByMemberId]获取会员收藏商品列表时发生异常:", e); } return serviceResult; } /** * 保存会员收藏商品表 * @param productId * @param request * @return */ @Override public ServiceResult<MemberCollectionProduct> saveMemberCollectionProduct(Integer productId, Integer memberId) { ServiceResult<MemberCollectionProduct> serviceResult = new ServiceResult<MemberCollectionProduct>(); try { serviceResult.setResult( memberCollectionProductModel.saveMemberCollectionProduct(productId, memberId)); } catch (BusinessException be) { serviceResult.setSuccess(false); serviceResult.setMessage(be.getMessage()); } catch (Exception e) { serviceResult.setError(ConstantsEJS.SERVICE_RESULT_CODE_SYSERROR, "服务异常,请联系系统管理员。"); log.error("[memberCollectionProductService][saveMemberCollectionProduct]会员收藏商品时发生异常:", e); } return serviceResult; } /** * 取消收藏商品 * @param productId * @param request * @return */ @Override public ServiceResult<MemberCollectionProduct> cancelCollectionProduct(Integer productId, Integer memberId) { ServiceResult<MemberCollectionProduct> serviceResult = new ServiceResult<MemberCollectionProduct>(); try { serviceResult.setResult( memberCollectionProductModel.cancelCollectionProduct(productId, memberId)); } catch (BusinessException be) { serviceResult.setSuccess(false); serviceResult.setMessage(be.getMessage()); } catch (Exception e) { serviceResult.setError(ConstantsEJS.SERVICE_RESULT_CODE_SYSERROR, "服务异常,请联系系统管理员。"); log.error("[memberCollectionProductService][cancelCollectionProduct]取消收藏商品时发生异常:", e); } return serviceResult; } }
Rust
UTF-8
5,483
3.71875
4
[]
no_license
use std::iter::IntoIterator; #[derive(Debug)] pub struct Matrix<T> { pub dimensions: usize, m: Vec<T> } impl<T> Matrix<T> { pub fn new(dimensions: usize) -> Matrix<T> { Matrix { dimensions: dimensions, m: Vec::with_capacity(dimensions * dimensions) } } pub fn with_data(dimensions: usize, data: Vec<T>) -> Matrix<T> { assert!(data.len() == dimensions * dimensions); Matrix { dimensions: dimensions, m: data } } pub fn with_fn<F>(dimensions: usize, f: F) -> Matrix<T> where F: Fn(usize, usize) -> T { let mut matrix = Self::new(dimensions); for row in 0..dimensions { for col in 0..dimensions { let val = f(row, col); matrix.m.push(val); } } matrix } pub fn transpose(&mut self) { for row in 0..self.dimensions { for col in row..self.dimensions { let a = row * self.dimensions + col; let b = col * self.dimensions + row; self.m.swap(a, b); } } } pub fn get_row(&self, row: usize) -> &[T] { let range = self.row_range(row); &self.m[range] } pub fn get_row_mut(&mut self, row: usize) -> &mut [T] { let range = self.row_range(row); &mut self.m[range] } pub fn rotate_cw(&mut self) { self.transpose(); self.reverse_rows(); } pub fn rotate_ccw(&mut self) { self.reverse_rows(); self.transpose(); } pub fn get(&self, row: usize, col: usize) -> &T { &self.m[self.dimensions * row + col] } pub fn set(&mut self, row: usize, col: usize, val: T) { self.m[self.dimensions * row + col] = val; } fn row_range(&self, row: usize) -> ::std::ops::Range<usize> { let offset = self.dimensions * row; offset..offset + self.dimensions } fn reverse_rows(&mut self) { for row_ix in 0..self.dimensions { let row = self.get_row_mut(row_ix); row.reverse(); } } } pub struct IntoIter<'a, T> where T: 'a { matrix: &'a Matrix<T>, ix: usize } impl<'a, T> Iterator for IntoIter<'a, T> { type Item = &'a [T]; fn next(&mut self) -> Option<&'a [T]> { let current_ix = self.ix; let is_done = current_ix >= self.matrix.dimensions; self.ix += 1; if is_done { None } else { Some(self.matrix.get_row(current_ix)) } } } impl<'a, T> IntoIterator for &'a Matrix<T> { type Item = &'a [T]; type IntoIter = IntoIter<'a, T>; fn into_iter(self) -> Self::IntoIter { IntoIter { matrix: self, ix: 0 } } } #[cfg(test)] mod tests { use super::Matrix; #[test] fn test_rotate_cw() { let mut m = Matrix::with_fn(3, |row, col| (row, col)); m.rotate_cw(); assert_eq!(m.get_row(0), &[(2, 0), (1, 0), (0, 0)]); assert_eq!(m.get_row(1), &[(2, 1), (1, 1), (0, 1)]); assert_eq!(m.get_row(2), &[(2, 2), (1, 2), (0, 2)]); } #[test] fn test_rotate_ccw() { let mut m = Matrix::with_fn(3, |row, col| (row, col)); m.rotate_ccw(); assert_eq!(m.get_row(0), &[(0, 2), (1, 2), (2, 2)]); assert_eq!(m.get_row(1), &[(0, 1), (1, 1), (2, 1)]); assert_eq!(m.get_row(2), &[(0, 0), (1, 0), (2, 0)]); } #[test] fn test_transpose() { let mut m = Matrix::with_fn(3, |row, col| (row, col)); m.transpose(); assert_eq!(m.get_row(0), &[(0, 0), (1, 0), (2, 0)]); assert_eq!(m.get_row(1), &[(0, 1), (1, 1), (2, 1)]); assert_eq!(m.get_row(2), &[(0, 2), (1, 2), (2, 2)]); } #[test] fn test_set_row() { let mut m = Matrix::with_fn(2, |_, _| 0); assert_eq!(m.dimensions, 2); assert_eq!(m.get_row(0), &[0, 0]); assert_eq!(m.get_row(1), &[0, 0]); m.set(0, 1, 99); assert_eq!(m.get_row(0), &[0, 99]); assert_eq!(m.get_row(1), &[0, 0]); m.set(1, 0, 99); assert_eq!(m.get_row(0), &[0, 99]); assert_eq!(m.get_row(1), &[99, 0]); } #[test] fn test_get_row() { let m = Matrix::with_fn(3, |row, col| (row, col)); assert_eq!(m.get_row(0), &[(0, 0), (0, 1), (0, 2)]); assert_eq!(m.get_row(1), &[(1, 0), (1, 1), (1, 2)]); assert_eq!(m.get_row(2), &[(2, 0), (2, 1), (2, 2)]); } #[test] fn test_matrix_reverse_rows() { let mut m = Matrix::with_fn(3, |row, col| (row, col)); m.reverse_rows(); assert_eq!(m.get_row(0), &[(0, 2), (0, 1), (0, 0)]); assert_eq!(m.get_row(1), &[(1, 2), (1, 1), (1, 0)]); assert_eq!(m.get_row(2), &[(2, 2), (2, 1), (2, 0)]); } #[test] fn test_creating_matrix() { let m = Matrix::with_fn(3, |row, col| (row, col)); for i in 0..3 { for j in 0..3 { let &(a, b) = m.get(i, j); assert_eq!(a, i); assert_eq!(b, j); } } } #[test] fn test_into_iterator() { let m = Matrix::with_fn(3, |row, col| (row, col)); let collected: Vec<&[(usize, usize)]> = m.into_iter().collect(); assert_eq!(collected.len(), 3); assert_eq!(collected[0], &[(0, 0), (0, 1), (0, 2)]); assert_eq!(collected[1], &[(1, 0), (1, 1), (1, 2)]); assert_eq!(collected[2], &[(2, 0), (2, 1), (2, 2)]); // Take a new iterator to confirm that the matrix wasn't consumed the first // time. let collected: Vec<&[(usize, usize)]> = m.into_iter().collect(); assert_eq!(collected.len(), 3); } #[test] #[should_panic] fn test_with_data_panics_on_length_mismatch_in_input_vec() { Matrix::with_data(3, vec![1,2,3,4,5,6,7,8,9,10]); } #[test] fn test_with_data_works_when_input_vec_len_matches_dimensions() { Matrix::with_data(3, vec![1,2,3,4,5,6,7,8,9]); } }
Java
UTF-8
288
2.984375
3
[ "Apache-2.0" ]
permissive
/** * @author Lewis Matos, Julich Mera */ public class Dice{ public static void main(String[] args){ int face[]=new int[6]; for(int i=0; i<300; i++){ ++face[0+(int)(Math.random()*((5-0)+1))]; } for(int i=0; i<face.length; i++){ System.out.println((i+1)+"\t\t"+face[i]); } } }
JavaScript
UTF-8
277
2.71875
3
[]
no_license
function (key,values,rereduce){ var result = [], found = {}; if (rereduce) values = [].concat.apply([],values); for (var i=0; i<values.length; i++) found[values[i].toLowerCase()] = 1; for (var k in found) result.push(k); return result; }
Java
ISO-8859-1
187
1.648438
2
[]
no_license
package estoque.integration.dao.postgresql; //Padro Abstract Factory : ConcreteProduct public class CategoriaDAO extends DAO implements estoque.integration.dao.CategoriaDAO { }
PHP
UTF-8
2,393
2.5625
3
[]
no_license
<?php include 'conection.php'; if(isset($_POST["submit"])) { $name=$_POST["name"]; $address=$_POST["address"]; $gender=$_POST["gender"]; $dob=$_POST["dob"]; $phone=$_POST["phno"]; $email=$_POST["email"]; $username=$_POST["username"]; $password=$_POST["password"]; $conform=$_POST["conformpassword"]; //echo $c; $sql="INSERT INTO `tbl_userreg`( `name`, `address`, `gender`, `dob`, `phno`, `email`, `password`, `conformpassword`, `username`) VALUES ('$name','$address','$gender','$dob','$phone','$email','$username','$password','$conform')"; //echo $sql; $result1=mysqli_query($con,$sql); $sql1="INSERT INTO `kala`.`tbl_login1` (`username`, `password`, `conformpassword`, `role`) VALUES ('$username','$password','$conform',2)"; echo $sql1; $result=mysqli_query($con,$sql1); echo "REGISTER Sucessfully"; } ?> <!DOCTYPE html> <html> <head> </head> <body> <h1><center><p><font color=" #0d0d0d"> Student Registration Page</p></h1> <div><form name="myform" id="myform" method="post" action="#"><center> <table> <tr><td> Name:</td> <td><input type="text" name="name" required></td></tr> <tr><td> Address</td> <td><input type="text" name="address" maxlength="10" required></td></tr></br><tr></tr> <tr><td></TD><td><FIELDSET><LEGEND>GENDER</LEGEND><input type="radio" name="gender" value="male" checked> Male<br> <input type="radio" name="gender" value="female"> Female<br> <input type="radio" name="gender" value="other"> Other<br><br> </FIELDSET></td></tr> <tr><td>DOB</td><td> <input type="date" name="dob" placeholder="dd/mm/yy "required></td></td> <tr><td> Mob.no</td> <td><input type="tel" name="phno" max="20" required></td></tr></br><tr></tr> <tr><td> E-mail</td> <td><input type="email" name="email" required ></td></tr></br><tr></tr> <tr><td> User Name</td> <td><input type="text" name="username" required></td></tr></br><tr></tr> <tr><td> Password</td> <td><input type="password" name="password" required></td></tr></br><tr></tr> <tr><td> Conform Password</td> <td><input type="password" name="conformpassword" required></td></tr></br><tr></tr> <tr><td><input type="submit" value="submit" name="submit" ></td></tr></center> &nbsp&nbsp </table> </form></div> <div class="footer"><font color="white"> © 2016 Amalagiri Hospital of medical science. All rights reserved. </font></div> </body> </html>
Markdown
UTF-8
2,124
2.53125
3
[]
no_license
--- layout: default title: "当霸凌遇到流氓:印度专家称除非中国承认「一个印度」,印航不会更改台湾名称" date: 2018-06-28T05:07:48.000000+08:00 --- 中国民航局要求国际间44家航空公司,在各自网站上将对「台湾」的称谓标示改为「中国台湾」。印航发言人表示,更名应由政府决定;印度专家则认为,除非中国承认「一个印度」,否则印度航空不会更改台湾名称。 中央社今天报导,印度金德尔大学(OP Jindal Global University)国际事务学院资深研究员曼尼(Tridivesh Singh Maini)表示,由于中国没有承认「一个印度」,印度历次与中国的联合声明或公报,也都拒绝放入承认与支持「一个中国」的内容。 曼尼分析,除非「一个印度」获得承认,否则印度没有理由依循中国的「一个中国」原则,要求国家航空公司印度航空(Air India)更改台湾的名称。 所谓「一个印度」,是承认印度完整的领土,包括与巴基斯坦有主权争端的克什米尔,及与中国有主权争端的阿鲁纳查省,中国称为藏南)。 印度航空目前与台湾长荣航空合作,有从德里或孟买飞往台北的航班,在印度航空官网上,飞往台湾的航班,地点仍维持原有的「台北,桃园国际机场,台湾」(Taipei, Taoyaun International Airport, Taiwan),没有因为中国压力而更改。印度外交部到现在还有表态。 另外,在比利时首都布鲁塞尔,今天首度出现一支反对中国在国际间霸凌台湾的示威游行队伍,共约250人,成员包括台湾的外交官,台湾的友邦派驻在欧盟的大使、台湾侨胞留学生、欧洲议会议员、比利时国会议员及比利时政界人士等。 领头游行的台湾驻欧盟代表曾厚仁表示,最近几个月来,中国对台湾的打压变本加厉,手段粗暴,旅居比利时的侨界在代表处协助下,结合国际友人,希望透过这次活动让国际社会听到台湾人心声,并且对中国的霸凌大声说不。
Markdown
UTF-8
6,371
3.109375
3
[ "MIT" ]
permissive
--- title: 推免答辩·自我介绍 --- 老师们好,我是来自中大数据院的吴坎,本科就读的是计算机科学与技术专业的超算方向,也是我院的特色专业。接下来我将用大约九分钟的时间,从以下六个角度介绍自己,以便让老师们全面的了解我。 首先是我的学业情况。我的成绩在我们专业排名前 15%,同时我在大学三年里分别获得三等奖学金、二等奖学金、一等奖学金。其中由于疫情原因,今年获得的一等奖学金评选流程比往年稍慢一些,还在公示期。 接下来是我本科一些课程的成绩和班级排名。我有比较强的动手能力,能在实验课和以实验为主的课程取得高分和优异的成果。其中,在大二上学期,我在计算机组成与原理实验课上设计的单周期、多周期 CPU 项目成为我院 18 级实验课的模板。我是怎么知道这件事的呢(笑)?在大三的这个时候,我的博客访问量突然激增了十几倍,也有很多师弟师妹加我的微信,第一句话就是:“学长,我看了你的 CPU”。 也是在大三的这个时候,我院和网易游戏联合开设的一门移动互联网编程实践课程,我基于 Python + OpenCV + 网易 Airtest 框架设计了一个自动化脚本,使用图象识别的手段和游戏进行交互,避免触发游戏的反作弊系统。虽然技术含量上没有单多周期 CPU 那么硬核,但是相关的视频在 b 站上收获了 1.8w+ 次的观看和上百次的评论和三连,我觉得从结果上来看同样是很有趣的。 说完了一些课内实验,我还想谈一谈我的课外项目经历。我觉得自己有比较强的开源精神,在 Github 上有接近两百个 star 和 七十个 Follower,同时除了前面说的两个课内项目外还在 GitHub 上开源了其他十几个代码仓库。由于时间原因我向老师们介绍其中的两个。 首先想要向老师们介绍的是我的个人博客系统。我一直都有写博客的习惯,平时会将自己的学习笔记、实验心得、生活随笔等上传到我的博客,上大学的一千多天里已经积累了三百多篇博文。但是市面上的博客网站因为广告等原因一直不能满足我的个人需求,因此我在大二寒假开始开发自己的博客网站。起初只有博文功能,后来我陆续参考各种开源工具,开发了评论功能、打赏功能和展示功能。老师们现在看到的这个展示其实也是我自己开发的博客系统的一部分!所以我今天的展示其实是冒了一定的风险的(笑),希望接下来的展示过程也不要翻车。我的博客系统自开源以来收获了一百六十多个 star 和近 300 次 fork,网站的访问量也达到了上万次,算是我比较满意的一个项目了。 另外一个开源代码项目是我为我们学校的程序设计算法竞赛出的一套题目,题目涵盖了搜索、图论、数论、数据结构等知识点,是我比较用心出的一套题目了。 说到算法竞赛,接下来我来谈一谈我的竞赛经历。我是校 ACM 队队员,有比较强的代码能力,很遗憾今年推免没有上机考试(笑)。我在去年十一月,代表学校参加在中国矿业大学举办的国际大学生程序设计竞赛,收获了一枚银牌;在一个月之后的 CCF-CSP 认证中取得了万分之五的高排名。这是我去年在徐州拍的照片啦。 同时,我对高性能计算和体系结构方向比较感兴趣,是校超算队队长。今年八月份,我参加中科院举办的首届“先导杯”并行应用大奖赛,比赛的难点是在从来没有用过的国产类 GPU 异构加速器上进行算法设计。我通过矩阵分块、合并访存等一系列手段,在 GPU 上相对于传统算法取得了 4.74 倍的加速比,运行时间相较于 CPU 上的 Floyed 算法减少了上千倍,最终分别在其中的两个赛题中取得了第三名和第五名的好成绩。这是颁奖典礼上拍的照片。 在九月二十八日刚刚举办的中国高性能计算年会上,通过队列调度、卷积优化等手段,我们将非标准傅里叶变换过程加速了 76 倍,是决赛唯二跑进十秒以内的队伍,最终在“英特尔杯”并行应用大奖赛上取得了全国第二名的好成绩。当然目前获奖证书还没有寄到,但是相关获奖推送还在我们学院官网首页。 由于大学前几年在竞赛上投入的精力比较多,我的科研经历起步比较晚,但是其实是和我的竞赛经历是很契合的。今年八月份,我加入了国家超级计算广州中心和华为-鹏城实验室合作的半精度 Linpack 算法优化工作。所谓 Linpack 算法,可以理解成使用 LU 分解求解线性方程组,这和我之前参加的先导杯使用 LU 分解进行矩阵求逆有一定的相似之处。我们要使用异构加速卡上较强的半精度运算能力加速算法过程,然后使用数值上迭代的手段提高计算精度。这是近期一个比较新的技术手段,去年十一月份当时世界排名第一的超级计算机 Summit 使用这一手段将跑分提高了三倍,当然并没有将相关代码公开。我们的工作也进入代码验证阶段,计划先在天河的 GPU 节点上通过精度验证,后续会移植到华为基于 Atlas 的“云脑”集群上用作 benchmark。 最后是我的一些社会活动经历,由于我算是比较活跃的同学,经常能受到一些企业的邀请。去年三月份,我受邀参观腾讯在深圳的新总部。 去年六月份,我受邀参观无人驾驶独角兽企业小马智行,并体验了他们的无人驾驶技术。他们在九月份发布了全球首个 L4 级别的无人驾驶车,当然我坐的时候还没有,不过觉得已经非常稳了。 去年十二月份,我受邀参观谷歌上海 office。这些对我来说都是比较有趣的经历了。 最后是我的一些学生工作经历,我在大学期间一直努力锻炼自己的“领袖气质”,尝试各种学生干部职位并取得了一定的成果,同时即将被吸收为预备党员。 以上就是我的个人介绍,希望能够得到老师们的认可,谢谢老师!
JavaScript
UTF-8
2,971
2.859375
3
[]
no_license
var html = require('fs').readFileSync(__dirname+'/GeoChat3.html'); var server = require('http').createServer(function(req, res){ console.log('Running'); res.end(html); }); server.listen(8080); var nowjs = require('now'); var everyone = nowjs.initialize(server); var listOfRooms =[] ; //everyone.now.distributeMessage = function(message){ // console.log(message); // everyone.now.receiveMessage(this.now.usr_name, this.now.currentRoom, message); //}; // Send message to everyone in the users group everyone.now.distributeMessage = function(message){ console.log(message); if (this.now.distanceInMetres < 300 ) { var group = nowjs.getGroup(this.now.currentRoom); group.now.receiveMessage(this.now.usr_name+'@'+this.now.currentRoom, message); } else { console.log (this.now.usr_name + ' is too far to speak @ ' + this.now.currentRoom); } }; everyone.now.changeRoom = function(newRoom){ // calc distance to newRoom var distanceToRoom = this.now.CalcDistance(newRoom); console.log('now.changeRoom fired'); // save the oldRoom before overwriting var oldRoom = this.now.currentRoom; // update the client's currentRoom variable this.now.currentRoom = newRoom; if (oldRoom == newRoom ) { console.log('self clicking on ' + this.now.currentRoom); return 0; } // join the new room var newGroup = nowjs.getGroup(newRoom); newGroup.addUser(this.user.clientId); //if old room is not null; then leave the old room if(oldRoom){ var oldGroup = nowjs.getGroup(oldRoom); oldGroup.removeUser(this.user.clientId); //If last usr is leaving the group -> remove the marker from all usrs oldGroup.getUsers(function (users) { if (users.length == 0) { console.log(oldRoom + ' is now empty'); //remove the room from listOfRooms array for (i=0; i<listOfRooms.length;i++ ) { if (listOfRooms[i].roomName == oldRoom) { console.log('Removing ' + listOfRooms[i].roomName + ' from roomsList'); listOfRooms.splice(i, 1); everyone.now.roomsList = listOfRooms; everyone.now.RemoveMarker(oldRoom); } } } }); } console.log(this.now.usr_name + " just changed from " + oldRoom + " to "+ this.now.currentRoom); }; function RoomOb(lat, lng, roomName, owner, users) { this.lat = lat; this.lng = lng; this.roomName = roomName; this.owner = owner; this.users =[owner]; } // clinet side object des : Room(lat, lng, roomName, owner, users) { everyone.now.launchRoom = function(lat, lng, roomName){ var room = new RoomOb(lat, lng, roomName, this.now.usr_name, this.now.usr_name); console.log('appending room...'); listOfRooms.push(room); everyone.now.roomsList = listOfRooms; everyone.now.placeRoom(room); this.now.changeRoom(room.roomName); };
PHP
UTF-8
3,050
2.921875
3
[]
no_license
<?php error_reporting(E_ALL ^ E_NOTICE); function ajout_absence($date,$nom_absent){ try { $db=connect(); $resultat= $db->prepare("INSERT INTO absence (date,nom_absent) VALUES (?,?)"); $resultat->bindValue(1, $date, PDO::PARAM_INT); $resultat->bindValue(2, $nom_absent, PDO::PARAM_STR); $resultat->execute(); return true; } catch (PDOException $exc) { echo $exc->getMessage(); return false; } } function envoi_email(){ $headers= "From: achraflansari@gmail.com \r\n"; $headers.= "Content-Type: text/html; charset=\"UTF-8\"\r\n"; $message = "blabla"; if(mail("achraflansari@gmail.com", "Web message from: Trombinoscope(Gestion d'absence)", "Email from Trombinoscope (Rappel Absence) \n\n{$message}",$headers)){ //echo '<script> window.location.reload(true); </script>'; echo 'email envoyer'; } die ('Thank you for your support, the email has been sent and you will recieve a reply shortly.'); } function envoi_email2(){ $mail = 'achraflansari@gmail.com'; // Déclaration de l'adresse de destination. if (!preg_match("#^[a-z0-9._-]+@(hotmail|live|msn).[a-z]{2,4}$#", $mail)) // On filtre les serveurs qui rencontrent des bogues. { $passage_ligne = "\r\n"; } else { $passage_ligne = "\n"; } //=====Déclaration des messages au format texte et au format HTML. $message_txt = "Salut à tous, voici un e-mail envoyé par un script PHP."; $message_html = "<html><head></head><body><b>Salut à tous</b>, voici un e-mail envoyé par un <i>script PHP</i>.</body></html>"; //========== //=====Création de la boundary $boundary = "-----=".md5(rand()); //========== //=====Définition du sujet. $sujet = "Hey mon ami !"; //========= //=====Création du header de l'e-mail. $header = "From: \"WeaponsB\"<weaponsb@mail.fr>".$passage_ligne; $header.= "Reply-to: \"WeaponsB\" <weaponsb@mail.fr>".$passage_ligne; $header.= "MIME-Version: 1.0".$passage_ligne; $header.= "Content-Type: multipart/alternative;".$passage_ligne." boundary=\"$boundary\"".$passage_ligne; //========== //=====Création du message. $message = $passage_ligne."--".$boundary.$passage_ligne; //=====Ajout du message au format texte. $message.= "Content-Type: text/plain; charset=\"ISO-8859-1\"".$passage_ligne; $message.= "Content-Transfer-Encoding: 8bit".$passage_ligne; $message.= $passage_ligne.$message_txt.$passage_ligne; //========== $message.= $passage_ligne."--".$boundary.$passage_ligne; //=====Ajout du message au format HTML $message.= "Content-Type: text/html; charset=\"ISO-8859-1\"".$passage_ligne; $message.= "Content-Transfer-Encoding: 8bit".$passage_ligne; $message.= $passage_ligne.$message_html.$passage_ligne; //========== $message.= $passage_ligne."--".$boundary."--".$passage_ligne; $message.= $passage_ligne."--".$boundary."--".$passage_ligne; //========== //=====Envoi de l'e-mail. mail($mail,$sujet,$message,$header); //========== } envoi_email2(); ?>
C
UTF-8
1,859
2.90625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: apergens <apergens@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/08/13 14:01:37 by apergens #+# #+# */ /* Updated: 2014/08/13 21:22:34 by apergens ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int ft_count(const char *s, char c) { int i; int n; int a; i = -1; n = 0; a = 0; while (*(s + (++i))) { if (*(s + i) != c && (!i || (i > 0 && *(s + (i - 1)) == c))) n++; else if (*(s + i) == c) a++; } if (!a) return (0); else if (!n && ft_strlen(s)) return (1); return (n); } char **ft_strsplit(const char *s, char c) { int i; int max; int word; char *copy; char **split; if (s == NULL || *s == '\0' || (copy = ft_strdup(s)) == NULL) return (NULL); max = ft_count(copy, c); split = (char **)malloc(sizeof(char *) * (max + 1)); ft_memset(split, 0, sizeof(char *) * (max + 1)); i = -1; word = 0; while (word <= max && *(copy + (++i)) != '\0') { if (*(copy + i) != c && (!i || (i > 0 && *(copy + (i - 1)) == c))) *(split + (word++)) = copy + i; } ft_strreplace(copy, c, '\0'); i = -1; while (*(split + (++i)) != NULL) *(split + i) = ft_strdup(*(split + i)); ft_strdel(&copy); return (split); }
Swift
UTF-8
298
2.59375
3
[]
no_license
// // Extensions.swift // ReduxTest // // Created by Guilherme Paciulli on 07/08/17. // Copyright © 2017 Guilherme Paciulli. All rights reserved. // import Foundation extension String { public func isValid() -> Bool { return !(self.isEmpty || self.trimmingCharacters(in: .whitespaces).isEmpty) } }
JavaScript
UTF-8
3,820
2.71875
3
[]
no_license
import React, { Component } from 'react'; import Autosuggest from 'react-autosuggest'; import getData from './getData.js'; import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import { browserHistory } from 'react-router'; //https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters function escapeRegexCharacters(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function getSuggestions(props, value) { //generate master suggestions array from props let teams = props.teams.map(function(team) { return {value: team, display: team + ' (team)', type: 'TEAM'}; }); let champions = props.champions.map(function(champion) { return {value: champion, display: champion + ' (champion)', type: 'CHAMPION'}; }); let players = props.players.map(function(player) { return {value: player, display: player + ' (player)', type: 'PLAYER'}; }); let suggestions = teams.concat(champions).concat(players); const escapedValue = escapeRegexCharacters(value.trim()); if (escapedValue === '') { return []; } const regex = new RegExp(escapedValue, 'i'); return suggestions.filter(input => regex.test(input.value)); } function getSuggestionValue(suggestion) { return suggestion.value; } function renderSuggestion(suggestion) { return ( <span>{suggestion.display}</span> ); } function onSuggestionSelected(event, { suggestion, suggestionValue, sectionIndex, method }) { // navigate to route based on suggestion type switch(suggestion.type) { case 'TEAM': browserHistory.push('/teams/' + suggestion.value + '/1'); break; case 'CHAMPION': browserHistory.push('/champions/' + suggestion.value + '/1'); break; case 'PLAYER': browserHistory.push('/players/' + suggestion.value + '/1'); break; } } class Example extends Component { constructor() { super(); //initialize suggestions data with getData? or just use axios and add another GET route? getData('/teams', 'TEAMS_SUCCESS', 'TEAMS_ERROR'); getData('/champions', 'CHAMPIONS_SUCCESS', 'CHAMPIONS_ERROR'); getData('/players', 'PLAYERS_SUCCESS', 'PLAYERS_ERROR'); this.state = { value: '', suggestions: [] }; } onChange = (event, { newValue, method }) => { this.setState({ value: newValue }); }; onSuggestionsFetchRequested = ({ value }) => { this.setState({ suggestions: getSuggestions(this.props, value) }); }; onSuggestionsClearRequested = () => { this.setState({ suggestions: [] }); }; render() { const { value, suggestions } = this.state; const inputProps = { placeholder: "Search for a team, player, or champion below.", value, onChange: this.onChange }; return ( <Autosuggest suggestions={suggestions} onSuggestionsFetchRequested={this.onSuggestionsFetchRequested} onSuggestionsClearRequested={this.onSuggestionsClearRequested} getSuggestionValue={getSuggestionValue} onSuggestionSelected={onSuggestionSelected} renderSuggestion={renderSuggestion} inputProps={inputProps} focusFirstSuggestion={true} /> ); } } const mapStateToProps = (state) => { return { teams: state.teams, champions: state.champions, players: state.players }; }; export default withRouter(connect(mapStateToProps, null)(Example));
JavaScript
UTF-8
2,636
2.546875
3
[]
no_license
require('dotenv').config(); require('../../lib/utils/connect')(); const mongoose = require('mongoose'); const User = require('../.././lib/models/User'); const { tokenized } = require('../../lib/utils/token'); describe('test the user model', () => { beforeEach(done => { return mongoose.connection.dropDatabase(() => { done(); }); }); it('validates a good model', () => { const user = new User({ email: 'LOL@gmail.com' }); expect(user.toJSON()).toEqual({ _id: expect.any(Object), email: 'LOL@gmail.com' }); }); it('tests that the model has a required email', () => { const user = new User(); const errors = user.validateSync().errors; expect(errors.email.message).toEqual('Path `email` is required.'); }); it('stores a temp password', () => { const user = new User({ email: 'LOL@gmail.com', password: 'YES' }); expect(user._tempPassword).toEqual('YES'); }); it('saves the hashed clear password', () => { const user = new User({ email: 'LOL@gmail.com', password: 'YES' }); user.save() .then(user => { expect(user.passwordHash).toEqual(expect.any(String)); }); }); it('compares the clear the hashed password', () => { const user = new User({ email: 'LOL@gmail.com', password: 'YES' }); return user.save() .then(user => { return user.compare('YES'); }) .then(result => { expect(result).toBeTruthy(); }); }); it('can find a user from a token', () => { const user = new User({ email: 'LOL@gmail.com', password: 'YES' }); return user.save() .then(user => { return tokenized(user); }) .then(token => { return User.findByToken(token); }) .then(user => { expect(user.email).toContain('LOL@gmail.com'); }); }); it('can return a JSON object of the user without certain fields', () => { const user = new User({ email: 'LOL@gmail.com', password: 'YES' }); return user.save() .then(user => { expect(user.email).toContain('LOL@gmail.com'); }); }); it('it returns a JSON object using the static method', () => { const user = new User({ email: 'LOL@gmail.com', password: 'YES' }); return user.save() .then(user => { return user.authToken(); }) .then(res => { expect(res).toEqual(expect.any(String)); }); }); });
Python
UTF-8
383
3.28125
3
[]
no_license
def main(): genome=input('please input a string:') found=False start=-1 for i in range(len(genome)-2): triplet=genome[i:i+3] if triplet=='ATG': start=i+3 elif (triplet=='TAG' or triplet=='TAA' or triplet=='TGA') and start!=-1: gene=genome[start:i] if len(gene)%3==0: found=True print(gene) start=-1 if not found: print('no gene is found') main()
Shell
UTF-8
577
3.375
3
[]
no_license
#!/bin/bash set -x GCP_FILESTORE_IP=$1 ETH_GATEWAY=$2 ETH_DEV=$(ifconfig | grep -B1 "$(echo "${ETH_GATEWAY}" | awk -F. '{print $1 "." $2 "." $3}')" | grep eth | awk -F: '{print $1}') # change BOOTPROTO from default none to dhcp on 2nd NIC sed -i 's/BOOTPROTO=none/BOOTPROTO="dhcp"/' /etc/sysconfig/network-scripts/ifcfg-"${ETH_DEV}" # create static route file for 2nd NIC echo "${GCP_FILESTORE_IP} via ${ETH_GATEWAY} dev ${ETH_DEV}" > /etc/sysconfig/network-scripts/route-"${ETH_DEV}" chmod 644 /etc/sysconfig/network-scripts/route-"${ETH_DEV}" systemctl restart network
Markdown
UTF-8
6,086
3.1875
3
[ "MIT" ]
permissive
--- layout: post title: 浅谈Disruptor categories: [Java, 高性能, 锁] description: 浅谈Disruptor keywords: Disruptor, 无锁, 高性能 --- <h1 text-align="center">浅谈Disruptor</h1> Disruptor是一个低延迟(low-latency),高吞吐量(high-throughput)的事件发布订阅框架。通过Disruptor,可以在一个JVM中发布事件,和订阅事件。相对于Java中的阻塞队列(ArrayBlockingQueue,LinkedBlockingQueue),Disruptor的优点是性能更高。它采用了一种无锁的数据结构设计,利用环形数组(RingBuffer)来存放事件,通过对象复用减少垃圾回收进一步提高性能。 ## 从"慢日志"说起 线上有一个接口最近频繁报警(tp99变高),通过监控报警系统定位到问题主要出现在日志打印环节。接口方法入参和出参都会打印"info"日志,我们采用的日志是logback。它默认的是同步打印日志,在日志报文过大时,磁盘IO耗时会变得更加明显。某个慢请求90%的处理时间都消耗在日志打印中。于是我们决定采用异步的方式打印日志。sl4j2日志框架支持异步的日志打印,改成异步日志打印之后接口性能报警消失。而sl4j2高性能的秘密就在于Disruptor。 ## Disruptor解决的问题 设想一下,在一个JVM中当我们有多个消息的生产者线程,一个消费者线程时,他们之间如何进行高并发、线程安全的协调?很简单,用一个阻塞队列。 当我们有多个消息的生产者线程,多个消费者线程,并且每一条消息需要被所有的消费者都消费一次(这就不是一般队列,只消费一次的语义了),该怎么做? 这时仍然需要一个队列。但是: 1. 每个消费者需要自己维护一个指针,知道自己消费了队列中多少数据。这样同一条消息,可以被多个人独立消费。 2. 队列需要一个全局指针,指向最后一条被所有生产者加入的消息。消费者在消费数据时,不能消费到这个全局指针之后的位置——因为这个全局指针,已经是代表队列中最后一条可以被消费的消息了。 3. 需要协调所有消费者,在消费完所有队列中的消息后,阻塞等待。 4. 如果消费者之间有依赖关系,即对同一条消息的消费顺序,在业务上有固定的要求,那么还需要处理谁先消费,谁后消费同一条消息的问题。 总而言之,如果有多个生产者,多个消费者,并且同一条消息要给到所有的消费者都去处理一下,需要做到以上4点。这是不容易的。 LMAX Disruptor,正是这种场景下,满足以上4点要求的单机跨线程消息传递、分发的开源、高性能实现。 ## 关键概念 1. RingBuffer 应用需要传递的消息在Disruptor中称为Event(事件)。 RingBuffer是Event的数组,实现了阻塞队列的语义: 如果RingBuffer满了,则生产者会阻塞等待。 如果RingBuffer空了,则消费者会阻塞等待。 2. Sequence 在上文中,我提到“每个消费者需要自己维护一个指针”。这里的指针就是一个单调递增长整数(及其基于CAS的加法、获取操作),称为Sequence。 除了每个消费者需要维护一个指针外,RingBuffer自身也要维护一个全局指针(如上一节第2点所提到的),记录最后一条可以被消费的消息。 ## 生产场景实现 生产者往RingBuffer中发送一条消息(RingBuffer.publish())时: 1. 生产者的私有sequence会+1 2. 检查生产者的私有sequence与RingBuffer中Event个数的关系。如果发现Event数组满了(下图红框中的判断),则阻塞(下图绿框中的等待)。 3. RingBuffer会在Event数组中(sequencer+1) % BUFFER_SIZE的地方,放入Event。这里的取模操作,就体现了Event数组用到最后,则回到头部继续放,所谓"Ring" Buffer的轮循复用语义。 ## 消费场景实现 消费者从RingBuffer循环队列中获取一条消息时: 1. 从消费者私有Sequence,可以知道它自己消费到了RingBuffer队列中的哪一条消息。 2. 从RingBuffer的全局指针Sequence,可以知道RingBuffer中最后一条没有被消费的消息在什么位置。 3. N = (RuingBuffer的全局指针Sequence - 消费者私有Sequence),就是当前消费者,还可以消费多少Event。 4. 如果以上差值N为0,说明当前消费者已经消费过RingBuffer中的所有消息了。那么当前消费者会阻塞。等待生产者加入更多的消息。 5. 如果RingBuffer中,还有可以被当前消费者消费的Event,即N > 0, 那么消费者,会一口气获取所有可以被消费的N个Event。这种一口气消费尽量多的Event,是高性能的体现。 从RingBuffer中每获取一个Event,都会回调绿框中的eventHandler——这是应用注册的Event处理方法,执行应用的Event消费业务逻辑。 ## 高性能的实现细节 1. 无锁,无锁就没有锁竞争。当生产者、消费者线程数很高时,意义重大。所以, 往大里说,每个消费者维护自己的Sequence,基本没有跨线程共享的状态。 往小里说,Sequence的加法是CAS实现的。 当生产者需要判断RingBuffer是否已满时,用CAS比较原先RingBuffer的Event个数,和假定放入新Event后Event的个数。 如果CAS返回false,说明在判断期间,别的生产者加入了新Event;或者别的消费者拿走了Event。那么当前判断无效,需要重新判断。 2. 对象的复用,JVM运行时,一怕创建大对象,二怕创建很多小对象。这都会导致JVM堆碎片化、对象元数据存储的额外开销大。这是高性能Java应用的噩梦。 为了解决第二点“很多小对象”,主流开源框架都会自己维护、复用对象池。LMAX Disruptor也不例外。 生产者不是创建新的Event对象,放入到RingBuffer中。而是从RingBuffer中取出一个已有的Event对象,更新它所指向的业务数据,来代表一个逻辑上的新Event。
Java
UTF-8
1,166
2.84375
3
[]
no_license
package io.goen.net.p2p.dht; import io.goen.net.p2p.Node; public class NodeContract implements Comparable<NodeContract> { private Node node; private long lastTouch; private int staleCount; public NodeContract(Node node) { this.node = node; this.lastTouch = System.currentTimeMillis() / 1000L; this.staleCount = 0; } public Node getNode() { return node; } public void setNode(Node node) { this.node = node; } public long getLastTouch() { return lastTouch; } public void setLastTouch(long lastTouch) { this.lastTouch = lastTouch; } public int getStaleCount() { return staleCount; } public void setStaleCount(int staleCount) { this.staleCount = staleCount; } public void updateTouchNow() { this.lastTouch = System.currentTimeMillis() / 1000L; } public void resetStaleCount() { this.staleCount = 0; } public void incrementStaleCount() { this.staleCount++; } public void refresh() { this.updateTouchNow(); resetStaleCount(); } @Override public int compareTo(NodeContract o) { if (this.getNode().equals(o.getNode())) { return 0; } return (this.getLastTouch() > o.getLastTouch()) ? 1 : -1; } }
C
GB18030
516
3.296875
3
[]
no_license
#pragma once #include "000⺯.h" int Fbi(int n) { if (n <= 0) return 0; else if (n == 1) return 1; else return Fbi(n - 1) + Fbi(n - 2); } int T010() { int i; int a[40]; printf("ʾ쳲У\n"); a[0] = 0; a[1] = 1; printf("%d ", a[0]); printf("%d ", a[1]); for (i = 2; i < 40; i++) { a[i] = a[i - 1] + a[i - 2]; printf("%d ", a[i]); } printf("\n"); printf("ݹʾ쳲У\n"); for (i = 0; i < 40; i++) printf("%d ", Fbi(i)); return 0; }
Java
UTF-8
215
1.84375
2
[]
no_license
package org.iplantc.de.client.models.apps; import org.iplantc.de.client.models.HasSettableId; public interface AppRefLink extends HasSettableId { void setRefLink(String refLink); String getRefLink(); }
C
UTF-8
243
3.59375
4
[]
no_license
#include "main.h" /** * _isupper - check for capitalized letter * @c: ascii character buffer * Return: 1 for true, 0 for false */ int _isupper(int c) { int i = 65; for (; i <= 90; i++) { if (c == i) return (1); } return (0); }
Ruby
UTF-8
4,606
3.296875
3
[]
no_license
class Node include Comparable attr_accessor :data, :left, :right def initialize(data) @data = data @left = nil @right = nil end end class Tree attr_accessor :root def initialize(array) @root = build_tree(array.uniq.sort) end def build_tree(array) return nil if array.empty? # Takes the left node as root for even arrays mid_index = (array.length - 1)/2 root = Node.new(array[mid_index]) if mid_index == 0 root.left = nil else root.left = build_tree(array[0..mid_index-1]) end if mid_index == 0 && array.length == 1 root.right = nil else root.right = build_tree(array[mid_index + 1..array.length]) end root end def pretty_print(node = @root, prefix = '', is_left = true) pretty_print(node.right, "#{prefix}#{is_left ? '│ ' : ' '}", false) if node.right puts "#{prefix}#{is_left ? '└── ' : '┌── '}#{node.data}" pretty_print(node.left, "#{prefix}#{is_left ? ' ' : '│ '}", true) if node.left end def insert(value, node = @root) return nil if value == node.data if value < node.data node.left.nil? ? node.left = Node.new(value) : insert(value, node.left) else node.right.nil? ? node.right = Node.new(value) : insert(value, node.right) end end def delete(value, node = @root) if value < node.data if node.left.nil? puts "Value does not exist." return nil else node.left = delete(value, node.left) end elsif value > node.data if node.right.nil? puts "Value does not exist." return nil else node.right = delete(value, node.right) end else # Matching value p node # Node has 0-1 child return node.right if node.left.nil? return node.left if node.right.nil? # Node has 2 children next_predecessor = node.right next_predecessor = node.left until node.left.nil? node.data = next_predecessor.data node.right = delete(node.data, node.right) end node end def find(value) return nil if value.nil? node = @root until value == node.data if value < node.data node = node.left return nil if node.nil? else node = node.right return nil if node.nil? end end node end def level_order(node = @root, queue = []) array = [] queue << node until queue[0].nil? yield(queue[0]) if block_given? array << queue[0].data queue << queue[0].left unless queue[0].left.nil? queue << queue[0].right unless queue[0].right.nil? queue.shift end array end def inorder(node = @root, array = [], &block) inorder(node.left, array, &block) unless node.left.nil? yield(node) if block_given? array << node.data inorder(node.right, array, &block) unless node.right.nil? array end def preorder(node = @root, array = [], &block) yield(node) if block_given? array << node.data preorder(node.left, array, &block) unless node.left.nil? preorder(node.right, array, &block) unless node.right.nil? array end def postorder(node = @root, array = [], &block) postorder(node.left, array, &block) unless node.left.nil? postorder(node.right, array, &block) unless node.right.nil? yield(node) if block_given? array << node.data end def height(node = @root) node = node.instance_of?(Node) ? find(node.data) : find(node) return -1 if node.nil? left = node.left ? height(node.left) : -1 right = node.right ? height(node.right) : -1 [left, right].max + 1 end def depth(node = @root) ans = height(node) ans == -1 ? -1 : height(@root) - height(node) end def balanced?(node = @root) return true if node.nil? left = height(node.left) right = height(node.right) return true if (left - right).abs <= 1 && balanced?(node.left) && balanced?(node.right) false end def rebalance @root = build_tree(inorder()) end def print_test puts "" puts "Is BST balanced? #{self.balanced?}." puts "Level-order: #{self.level_order}" puts "Preorder: #{self.preorder}" puts "Preorder: #{self.postorder}" puts "Inorder: #{self.inorder}" puts "" end end array = Array.new(15) {rand(1..100)} bst = Tree.new(array) bst.pretty_print bst.print_test 10.times do a = rand(100..150) bst.insert(a) end bst.pretty_print puts "" puts "Is updated BST balanced? #{bst.balanced?}." puts "" bst.rebalance bst.pretty_print bst.print_test
Python
UTF-8
409
3.34375
3
[ "MIT" ]
permissive
#!/bin/python def pad(string,mylen,char): i=len(string); final=""; while i<=mylen: final+=char; i+=1; return string+final; team=[{'name':'Rob','title':'SR Analyst'},{'name':'Usha','title':'SR Analyst'},{'name':'Tom','title':'SR Analyst'},{'name':'t','title':'Lead'}]; team=sorted(team,key=lambda k:k['title']); for object in team: print pad(object['name'],20," ")," ",pad(object['title'],20," ");
Python
UTF-8
7,317
3.296875
3
[]
no_license
from sys import exit import time import random import os import game #Creates a parent class for the player class Person(object): def __init__(self, name, age, weight, gender): self.name = name self.age = age self.weight = weight self.gender = gender class Player(Person): def start(self): self.game.play() class Scene(object): def enter(self): pass class Uvod(Scene): def enter(self): print "Identifikacija:\n" #Creats a pause between two priting statements. time.sleep(1) name = raw_input("Kako se zoves?\n >") age = raw_input("Koliko imas godina?\n >") weight = raw_input("Koliko si tezak?\n >") gender = raw_input("Koji si pol?\n >") time.sleep(2) print "\nHello %s!\n" % name time.sleep(1) a = raw_input("Izaberi opciju:\n1.Zapocni igru\n 2.Odustani\n") if a.lower() == "zapocni igru" or a == "1": time.sleep(1) #Clears the screan without stopping the game. os.system('cls') return 'uvodna', Player(name, age, weight, gender) else: #this command ends the game. return exit(1) class Uvodna(Scene): def enter(self, player1): print """ Godina je 2080. Raketa ujedinjenih nacija nalazi se u susednoj galaksiji u potrazi za planetom na kojoj bi covecanstvo moglo da se nastani. Situacija na Zemlji je vrlo losa. Veci deo leda na polovima je otopljen. Priobalni gradovi su uglavnom potopljeni. Zbog epidemija I ratova doslo je do smanjenja broja stanovnika. Nije doslo do nuklearnog rata, ali preti rat izmedju bogatih I siromasnih jer su bogati resili da se otarase siromasnih posto vecinu poslova koji su obavljali siromasi I neobrazovani sada obavljaju roboti. Ti si vodja misije. Cilj misije je da se istrazi da li je na planeti u susednoj galaksiji moguc zivot. U toku misije medjutim saznajete da se na planeti X nalazi velika kolicina supstance XYZ koja je vrlo mocna energetski (cak 10 puta vise od nafte). Tvoj zamenik te hapsi I baca u tamnicu pod izgovorom da si poludeo I da si pretnja za misiju. Jedini nacin da se izbavis je da prodjes niz testova opste informisanosti. Imas 15 minuta da predjes sve nivoe.\n""" time.sleep(2) a = raw_input("When you are ready press 'r' i onda 'Enter'\n") if a == 'r': time.sleep(1) os.system('cls') return "vrata1" class Vrata1(Scene): def enter(self, player1): print """\n Nalazis se u mracnoj sobi. Prozorcic se otvara, i kroz njega ti dlakava ruka daje tanjir pun neki splacina. Ti kazes da zelis da uradis test. Vlasnik dlakave ruke ti kaze da je to Ok ali da moras to da trazis uctivo na Francuskom.""" time.sleep(2) a = raw_input("""Da li ces da kazes:\n1. Je voudrais fair une test!\n ili\n 2.S\'il vous plait une paraplui!?\n""") time.sleep(1) os.system('cls') if a == "Je voudrais fair une test!" or a == "1": print "Novo pitanje:\n" time.sleep(1) b = raw_input("Kako se na Francuskom kaze 'jedna zena'?\n\n") if b == "une femme": print "\nTacan odgovor!\n" time.sleep(1) return 'vrata2' else: return 'vrata1' else: return 'vrata1' class Vrata2(Scene): def enter(self, player1): time.sleep(1) print player1.name time.sleep(1) print player1.gender print """ Vrata se otvaraju, mracnim prljavim hodnikom ides do stepenica.Penjes se, ali nakon tridesetak stepenika nailazis na zakljucana vrata. Kucas: Cujes glas sa druge strane koji pita na portugalskom:\n""" time.sleep(2) print "Qui e? Voce es um hommem ou uma mulher?" time.sleep(2) a = raw_input("Odgovor:") if a.lower() == player1.name.lower() + "," + player1.gender.lower(): if player1.gender.lower() == "f" or player1.gender.lower() == "female": time.sleep(1) print "Dobrodosla na novi nivo!" time.sleep(1) os.system('cls') return 'vrata3' elif player1.gender.lower() == "muski" or player1.gender.lower() == "m": time.sleep(1) os.system('cls') print "Dobrodosao na novi nivo!" time.sleep(2) os.system('cls') return 'vrata3' else: time.sleep(1) return 'vrata1' else: time.sleep(1) return 'vrata1' class Vrata3(Scene): def enter(self, player1): print """hodnik vodi do drugih stepenica (sat na tvojoj ruci pokazuje da je proslo x minuta). Nailazis ubrzo na jos jedne sada nesto cistije stepenice. Penjes se I nakon tridesetak stepenika, nailazis na vrata. Kucas, tisina. Udaras. Cujes glas na srpskom: Sta lupas, bolje reci koji je glavni grad kalifornije! """ c = raw_input("Odgovor: ") if c.lower() == "sacramento": time.sleep(2) os.system('cls') return 'vrata4' elif c.lower() == "los angeles": print "Wrong answer! Moras iz pocetka" return 'vrata1' else: print "I don't understand, try again." return 'vrata3' class Vrata4(Scene): def enter(self, player1): print """Ulazis u novi hodnik koji je sasvim cist. Nailazis opet na stepenice, posle tridesetak stepenika opet nailazis na vrata. Na vratima je ekran, i na ekranu se nalazi pitanje:""" answer = raw_input("""Ko bi prema Platonu trebao da bude vladar idealne drzave 1. Ekonomista\n 2. Filozof?""") if answer == "2" or answer.lower() == "filozof": print "Tacan odgovor. Ti si bas neki znalac?!" time.sleep(2) os.system('cls') return 'velika soba' else: print "Greska, probaj ponovo." return 'vrata4' class Game(object): def __init__(self, scene_name): self.scene_name = scene_name def play(self): scenes = {'uvod': Uvod(), 'uvodna': Uvodna(), 'vrata1': Vrata1(),'vrata2': Vrata2(), 'vrata3': Vrata3(), 'vrata4': Vrata4(), 'velika soba': game.VelikaSoba()} current_scene = scenes.get(self.scene_name) current_scene, player1 = current_scene.enter() current_scene = scenes.get(current_scene) while True: next_scene = current_scene.enter(player1) current_scene = scenes.get(next_scene) game_play = Game('uvod') game_play.play()
Java
UTF-8
5,208
2.296875
2
[]
no_license
package com.example.admin.androidproject.DAO; import android.util.Log; import com.example.admin.androidproject.Entities.FoodEntities; import com.example.admin.androidproject.Entities.OrderEntities; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.Calendar; import java.util.Date; /** * Created by Admin on 3/21/2018. */ public class SingleViewDao { public SingleViewDao() { } public FoodEntities getInfoFood(String idFood) throws SQLException { FoodEntities food = null; Connection conn = null; PreparedStatement pre = null; ResultSet rs = null; try { String sql = "select FoodName,FoodPrice,FoodQuantity,FoodDescription,FoodImg from FoodTBL where FoodID = ?"; conn = new BaseDAO().CONN(); pre = conn.prepareStatement(sql); pre.setString(1, idFood); rs = pre.executeQuery(); while (rs.next()) { food = new FoodEntities(); food.setFoodName(rs.getString("FoodName")); food.setFoodPrice(rs.getDouble("FoodPrice")); food.setFoodQuantity(rs.getInt("FoodQuantity")); if (rs.getString("FoodDescription") != null) { food.setFoodDes(rs.getString("FoodDescription")); } else food.setFoodDes("N/A"); food.setFoodImg(rs.getString("FoodImg")); } } catch (Exception e) { Log.e("error", e.getMessage()); } finally { if (conn != null) { conn.close(); } if (pre != null) { pre.close(); } if (rs != null) { rs.close(); } } return food; } public boolean addImployee(OrderEntities e,int total) throws SQLException { Connection conn = null; PreparedStatement pre = null; boolean checkInsert = false; boolean checkUpdate = false; try { conn = new BaseDAO().CONN(); conn.setAutoCommit(false); String sql = "INSERT INTO [OrderTBL]\n" + " ([TableNo]\n" + " ,[OrderTime]\n" + " ,[FoodID]\n" + " ,[FoodOrderQuantity]\n" + " ,[DemandCustomer]\n" + " ,[StatusID]\n" + " ,[EmployeeOrder],[OrderID])\n" + " VALUES\n" + " (?,?,?,?,?,?,?,?)"; pre = conn.prepareStatement(sql); pre.setInt(1, e.getTableNo()); Date currentTime = Calendar.getInstance().getTime(); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime()); pre.setDate(2, date); pre.setString(3,e.getFoodId()); pre.setInt(4, e.getFoodOrderQuantity()); pre.setString(5, "N/A"); pre.setInt(6, 1); pre.setString(7, e.getEmployeeId()); pre.setString(8,e.getOrderId()); pre.addBatch(); int[] count = pre.executeBatch(); if (count.length > 0) { conn.commit(); checkInsert = true; } checkUpdate = updateQuantityFood(e,conn,total); if (!checkInsert && !checkUpdate) { conn.setAutoCommit(true); conn.rollback(); } } catch (Exception ex) { Log.e("error", ex.getMessage()); } finally { if (pre != null) { pre.close(); } if (conn != null) { conn.close(); } } return checkInsert && checkUpdate; } public boolean updateQuantityFood(OrderEntities e,Connection conn,int total) throws SQLException { PreparedStatement pre = null; boolean checkUpdate = false; try { conn = new BaseDAO().CONN(); conn.setAutoCommit(false); String sql = "Update FoodTBL set FoodQuantity =?,InStock =? where FoodID =?"; pre = conn.prepareStatement(sql); int quantityAfter = total - e.getFoodOrderQuantity(); pre.setInt(1,quantityAfter); if(quantityAfter >=0){ pre.setInt(2,1); } else { pre.setInt(2,0); } pre.setString(3,e.getFoodId()); pre.addBatch(); int[] count = pre.executeBatch(); if (count.length > 0) { checkUpdate = true; conn.commit(); } } catch (Exception ex) { Log.e("error", ex.getMessage()); } finally { if (pre != null) { pre.close(); } } return checkUpdate; } }
C++
UTF-8
868
3.71875
4
[ "MIT" ]
permissive
#include "stdafx.h" #include "Tree.h" // Constructor Tree::Tree() { root = nullptr; } // Virtual Destructor Tree::~Tree() { } // Returns the Root Node Node* Tree::getRoot() { return root; } // Sets the Root Node void Tree::setRoot(Node* tmp) { root = tmp; } // Inserts a new int into the tree, then calls 'reheap()' if needed void Tree::insert(Node* cur) { } // Reheaps the tree to correct bad ordering void Tree::heapify(Node* cur) { } // Swaps node A with node B void Tree::swap(Node* a, Node* b) { int val = a->getValue(); a->setValue(b->getValue()); b->setValue(val); } // Prints the current tree, must start with head, does an in-order traversal void Tree::print(Node* cur) { std::cout << cur->getValue() << " "; if (cur->getLeft() != nullptr) { print(cur->getLeft()); } if (cur->getRight() != nullptr) { print(cur->getRight()); } }
C++
WINDOWS-1252
478
3
3
[]
no_license
/* * @lc app=leetcode.cn id=9 lang=cpp * * [9] ????C??? */ #include <string> #include <iostream> using namespace std; class Solution { public: bool isPalindrome(int x) { string str_(to_string (x)); string resStr(str_); reverse(resStr.begin(), resStr.end()); if (str_ == resStr) return true; return false } }; int main() { cout << Solution().isPalindrome(0); return 0; }
Go
UTF-8
2,968
2.625
3
[ "Apache-2.0" ]
permissive
package namespace import ( "context" "fmt" "sync/atomic" "github.com/pingcap/errors" "github.com/tidb-incubator/weir/pkg/config" "github.com/tidb-incubator/weir/pkg/proxy/driver" "github.com/tidb-incubator/weir/pkg/proxy/metrics" ) type NamespaceHolder struct { nss map[string]Namespace } type NamespaceWrapper struct { nsmgr *NamespaceManager name string connCounter int64 } func CreateNamespaceHolder(cfgs []*config.Namespace, build NamespaceBuilder) (*NamespaceHolder, error) { nss := make(map[string]Namespace, len(cfgs)) for _, cfg := range cfgs { ns, err := build(cfg) if err != nil { return nil, errors.WithMessage(err, fmt.Sprintf("create namespace error, namespace: %s", cfg.Namespace)) } nss[cfg.Namespace] = ns } holder := &NamespaceHolder{ nss: nss, } return holder, nil } func (n *NamespaceHolder) Get(name string) (Namespace, bool) { ns, ok := n.nss[name] return ns, ok } func (n *NamespaceHolder) Set(name string, ns Namespace) { n.nss[name] = ns } func (n *NamespaceHolder) Delete(name string) { delete(n.nss, name) } func (n *NamespaceHolder) Clone() *NamespaceHolder { nss := make(map[string]Namespace) for name, ns := range n.nss { nss[name] = ns } return &NamespaceHolder{ nss: nss, } } func (n *NamespaceWrapper) Name() string { return n.name } func (n *NamespaceWrapper) IsDatabaseAllowed(db string) bool { return n.mustGetCurrentNamespace().IsDatabaseAllowed(db) } func (n *NamespaceWrapper) ListDatabases() []string { return n.mustGetCurrentNamespace().ListDatabases() } func (n *NamespaceWrapper) IsDeniedSQL(sqlFeature uint32) bool { return n.mustGetCurrentNamespace().IsDeniedSQL(sqlFeature) } func (n *NamespaceWrapper) IsAllowedSQL(sqlFeature uint32) bool { return n.mustGetCurrentNamespace().IsAllowedSQL(sqlFeature) } func (n *NamespaceWrapper) IsDeniedHost(host string) bool { return n.mustGetCurrentNamespace().IsDeniedHost(host) } func (n *NamespaceWrapper) GetPooledConn(ctx context.Context) (driver.PooledBackendConn, error) { return n.mustGetCurrentNamespace().GetPooledConn(ctx) } func (n *NamespaceWrapper) IncrConnCount() { currCnt := atomic.AddInt64(&n.connCounter, 1) metrics.QueryCtxGauge.WithLabelValues(n.name).Set(float64(currCnt)) } func (n *NamespaceWrapper) DescConnCount() { currCnt := atomic.AddInt64(&n.connCounter, -1) metrics.QueryCtxGauge.WithLabelValues(n.name).Set(float64(currCnt)) } func (n *NamespaceWrapper) Closed() bool { _, ok := n.nsmgr.getCurrentNamespaces().Get(n.name) return !ok } func (n *NamespaceWrapper) GetBreaker() (driver.Breaker, error) { return n.mustGetCurrentNamespace().GetBreaker() } func (n *NamespaceWrapper) GetRateLimiter() driver.RateLimiter { return n.mustGetCurrentNamespace().GetRateLimiter() } func (n *NamespaceWrapper) mustGetCurrentNamespace() Namespace { ns, ok := n.nsmgr.getCurrentNamespaces().Get(n.name) if !ok { panic(errors.New("namespace not found")) } return ns }
Go
UTF-8
2,985
2.640625
3
[]
no_license
package main import ( "bufio" "context" "flag" "fmt" "log" "math/rand" "time" "github.com/andregri/tiny-p2p-blockchain/api" "github.com/andregri/tiny-p2p-blockchain/blockchain" "github.com/andregri/tiny-p2p-blockchain/peer" "github.com/libp2p/go-libp2p-core/network" "github.com/libp2p/go-libp2p-core/protocol" ) var blockChannel = make(chan blockchain.Block) func main() { listenAddr := flag.String("listen", "", "listen address") listenPort := flag.Int("port", 0, "listen port") proto := flag.String("proto", "blk", "protocol name") flag.Parse() if *listenPort == 0 { panic("port must be > 0") } log.SetFlags(log.LstdFlags | log.Lshortfile) ctx := context.Background() host, _ := peer.GenerateNewHost(*listenAddr, *listenPort) // Set a function as stream handler. // This function is called when a peer initiates a connection and starts a stream with this peer. host.SetStreamHandler(protocol.ID(*proto), handleStream) fmt.Printf("\n[*] Your Multiaddress Is: /ip4/%s/tcp/%v/p2p/%s\n", *listenAddr, *listenPort, host.ID().Pretty()) // Discover new peers peerChan := peer.InitMdns(host, "rendesvouz") // Add genesis block if chain is empty go func() { if len(blockchain.Blockchain) < 1 { genesis := blockchain.GenerateGenesisBlock() blockchain.Blockchain = append(blockchain.Blockchain, genesis) } generateRandomBlocks() }() // Start API go func() { api.Start(*listenPort + 100) }() // Connect to new peers for { peer := <-peerChan // will block untill we discover a peer fmt.Println("Found peer:", peer, ", connecting") if err := host.Connect(ctx, peer); err != nil { log.Println("Connection failed:", err) } // open a stream, this stream will be handled by handleStream other end stream, err := host.NewStream(ctx, peer.ID, protocol.ID(*proto)) if err != nil { log.Println("Stream open failed", err) } else { rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream)) go blockchain.WriteBlockchain(rw, blockChannel) go blockchain.ReadBlockchain(rw) fmt.Println("Connected to:", peer) } } } func handleStream(stream network.Stream) { fmt.Println("Got a new stream!") // Create a buffer stream for non blocking read and write. rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream)) go blockchain.WriteBlockchain(rw, blockChannel) go blockchain.ReadBlockchain(rw) // 'stream' will stay open until you close it (or the other side closes it). } func generateRandomBlocks() { for { // Sleep for a random time sleepTime := rand.Intn(20) + 10 time.Sleep(time.Duration(sleepTime) * time.Second) // Generate a new block amount := rand.Intn(1000) lastBlockIndex := len(blockchain.Blockchain) - 1 oldBlock := blockchain.Blockchain[lastBlockIndex] block, err := blockchain.GenerateBlock(oldBlock, amount) if err != nil { log.Println(err) } log.Printf("Block %d generated\n", amount) blockChannel <- block } }
TypeScript
UTF-8
593
2.65625
3
[]
no_license
import { Column, Model, Table, PrimaryKey, AutoIncrement, DataType, Unique } from 'sequelize-typescript' @Table export default class Account extends Model<Account> { @PrimaryKey @AutoIncrement @Column(DataType.INTEGER) id!: number @Column(DataType.STRING) name!: string @Unique @Column(DataType.STRING) username!: string @Column(DataType.STRING) password!: string @Column(DataType.STRING) avatar!: string @Column(DataType.INTEGER) state!: number @Column(DataType.STRING) background!: string @Column(DataType.INTEGER) rol!: number }
Markdown
UTF-8
4,616
2.921875
3
[]
no_license
## To Many Open files 今天查看服务日志的时候,突然发现服务器上出现了大量的错误日志`socket: too many open files` , > too many open files(打开的文件过多)是Linux系统中常见的错误,从字面意思上看就是说程序打开的文件数过多,不过这里的files不单是文件的意思,也包括打开的通讯链接(比如socket),正在监听的端口等等,所以有时候也可以叫做句柄(handle),这个错误通常也可以叫做句柄数超出系统限制。 引起的原因就是进程在某个时刻打开了超过系统限制的文件数量以及通讯链接数 用以往的经验分析,肯定是文件`fd`过少,到服务器通过`ulimit -n` 查到了`65535`, 理论上找个值已经够大了。排除系统的`fd`过少问题。 百度一圈基本上都是让改`ulimit `的参数,或者改内核的参数。查找问题的原因,要先从自身查起,又重新阅读了几遍相关代码,发现无明显的问题。于是可以排除掉代码的问题,问题基本上确定服务器上。 **查看TCP链接** ```shell netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}' ``` 大量的`CLOSE_WAIT`, <img src="https://image.fishedee.com/b833483e2dd182f52c37b413d4a0f6d9dfe00aa1" alt="img" style="zoom:90%;" /> **查看进程的最大fd** ```shell lsof -p pid | wc -l cat /proc/[pid]/limits 1024 ``` 查看进程的最大`fd` 发现居然是1024,而不是设置的`65535`,那么由此可知应该是某些地方设置了这个值,通过询问运维,知道他使用`supervisor` 去守护进程。然后就知道了`supervisor` 管理子进程,子进程继承父进程的`fd`. 肯定是`supervisor` 某些地方的设置过低,查阅supervisor文档,`[supervisord]` 段中配置 `minfds` 参数默认为1024,将`1024`改为65535,然后重启服务,问题解决。 ## 备忘 | 可以导致的原因 | 处理方法 | 补充说明 | | :--------------------- | :----------------------------- | :---------------------------------- | | 单个进程打开 fb 过多 | `/etc/security/limits.conf` | 修改文件或使用`prlimit`命令 | | 操作系统打开的 fb 过多 | `/proc/sys/fs/file-max` | 直接`echo`写入即可 | | Systemd 对进程限制 | `LimitNOFILE=20480000` | 通常在/etc/systemd/system/目录下 | | Supervisor 对进程限制 | `minfds` | 通常在/etc/supervisor/conf.d/目录下 | | Inotify 达到上限 | `sysctl -p`/`/etc/sysctl.conf` | 该机制受到`2`个内核参数的影响 | ### 1. shell级别限制 ```shell # 当前shell的当前用户所有进程能打开的最大文件数量 # 这就意味着root用户和escape用户能够打开的最大文件数量有可能不同 # 非root用户只能越设置越小,而root用户不受限制 # 在ulimit命令里的最大文件打开数量的默认值是1024个 # 如果limits.con有设置,则默认值以limits.conf为准 # 修改后立即生效,重新登录进来后失效,因为被重置为limits.conf里的设定值 ulimit -n #查看允许打开的最大fd #临时设置 ulimit -n 10240 #永久生效 vim /etc/security/limits.conf ``` ### 2. 用户级限制 ```bash # 2.用户级限制 ############### # 一个用户可能同时连接多个shell到系统,所以还有针对用户的限制 # 这里是通过修改/etc/security/limits.conf文件实现限制控制的 # 表示escape用户不管开启多少个shell终端所能打开的最大文件数量为65535个 escape soft nofile 65535 # 软限制 escape hard nofile 10240 # 硬限制 ``` ### 3. 系统级限制 ```bash # 当前内核可以打开的最大的文件句柄数 # 系统会计算内存资源给出的建议值,一般为内存大小(KB)的10%来计算 $ cat /proc/sys/fs/file-max 3283446 $ grep -r MemTotal /proc/meminfo | awk '{printf("%d",$2/10)}' 3294685 # 单个进程可分配的最大文件数 $ cat /proc/sys/fs/nr_open 1048576 # 查看整个系统目前使用的文件句柄数 # 已分配文件句柄的数目 已使用文件句柄的数目 文件句柄的最大数目 $ cat /proc/sys/fs/file-nr 8056 0 3283446 ``` ## 参考文章 - [golang 进程出现too many open files的排查过程](https://studygolang.com/articles/8671) - [golang 踩坑之 - 服务的文件句柄超出系统限制(too many open files)](https://kebingzao.com/2018/06/26/golang-too-many-file/) - [解决Supervisor默认并发限制](https://www.escapelife.site/posts/5457f758.html)
C++
UTF-8
971
2.640625
3
[]
no_license
/* * CanThrottle.h * * Created on: 18.06.2013 * Author: Michael Neuweiler */ #ifndef CAN_THROTTLE_H_ #define CAN_THROTTLE_H_ #include <Arduino.h> #include "config.h" #include "Throttle.h" #include "TickHandler.h" #define CAN_THROTTLE_REQUEST_ID 0x7e0 // the can bus id of the throttle level request #define CAN_THROTTLE_RESPONSE_ID 0x7e8 // the can bus id of the throttle level response #define CAN_THROTTLE_DATA_BYTE 4 // the number of the data byte containing the throttle level #define CAN_THROTTLE_REQUEST_DELAY 200 // milliseconds to wait between sending throttle requests class CanThrottle: public Throttle { public: CanThrottle(CanHandler *canHandler); void setup(); void handleTick(); Device::DeviceId getId(); int getThrottle(); protected: signed int outputThrottle; //the final signed throttle. [-1000, 1000] in tenths of a percent of maximum private: uint32_t lastRequestTime; }; #endif /* CAN_THROTTLE_H_ */
Python
UTF-8
663
2.75
3
[]
no_license
from docx import Document def write(docname): document = Document() styles = document.styles document.add_heading('Document Tile',0) p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold').bold = True p.add_run('italic.').italic = True document.add_heading('Heading, level 1', level=1) #document.add_paragraph('Intense quote', style=style) p = document.add_paragraph( '', style='ListBullet') p.add_hyperlink(text='foobar', url='http://github.com') document.add_paragraph( 'first item in ordered list', style='ListNumber') document.add_page_break() document.save(docname)
C++
UTF-8
2,428
2.890625
3
[ "Apache-2.0" ]
permissive
#pragma once #include "xo/system/assert.h" #include "xo/utility/types.h" namespace xo { /// find element in a container template< typename C > typename auto find( C& cont, const typename C::value_type& e ) { auto it = std::begin( cont ); for ( ; it != std::end( cont ); ++it ) if ( *it == e ) break; return it; } /// find element in a container template< typename C, typename P > auto find( const C& cont, const typename C::value_type& e ) { auto it = std::begin( cont ); for ( ; it != std::end( cont ); ++it ) if ( *it == e ) break; return it; } /// find element in a container template< typename C, typename P > auto find_if( C& cont, P pred ) { auto it = std::begin( cont ); for ( ; it != std::end( cont ); ++it ) if ( pred( *it ) ) break; return it; } /// find element in a container template< typename C, typename P > auto find_if( const C& cont, const P pred ) { auto it = std::begin( cont ); for ( ; it != std::end( cont ); ++it ) if ( pred( *it ) ) break; return it; } /// find element in a container template< typename C, typename P > typename C::value_type& find_ref_if( C& cont, P pred ) { auto it = std::begin( cont ); for ( ; it != std::end( cont ); ++it ) if ( pred( *it ) ) return *it; xo_error( "Could not find element" ); } /// count element in a container template< typename C, typename P > size_t count( const C& cont, typename C::value_type& e ) { size_t c = 0; for ( auto it = std::begin( cont ); it != std::end( cont ); ++it ) c += size_t( *it == e ); return c; } /// count element in a container template< typename C, typename P > size_t count_if( const C& cont, P pred ) { size_t c = 0; for ( auto it = std::begin( cont ); it != std::end( cont ); ++it ) c += size_t( pred( *it ) ); return c; } /// copy elements of one container to another template< typename InIt, typename OutIt > OutIt copy( InIt ib, InIt ie, OutIt ob ) { for ( ; ib != ie; ++ib, ++ob ) *ob = *ib; } /// append a container to another template< typename C1, typename C2 > C1& append( C1& c1, C2& c2 ) { c1.insert( c1.end(), c2.begin(), c2.end() ); return c1; } template< typename C > index_t find_index( const C& cont, const typename C::value_type& e ) { auto it = find( cont, e ); if ( it == std::end( cont ) ) return no_index; else return it - std::begin( cont ); } template< typename C > index_t back_index( const C& cont ) { return size( cont ) > 0 ? size( cont ) - 1 : no_index; } }
TypeScript
UTF-8
2,218
2.78125
3
[]
no_license
export const enum CouponType { AFFILIATECOUPON = 'AFFILIATECOUPON', ABSOLUTECOUPON = 'ABSOLUTECOUPON' } export const enum CouponAmountType { ONETHOUSAND = 'ONETHOUSAND', THREETHOUSAND = 'THREETHOUSAND', FIVETHOUSAND = 'FIVETHOUSAND', SEVENTHOUSAND = 'SEVENTHOUSAND', TENTHOUSAND = 'TENTHOUSAND' } export const enum CouponUseType { DAYUSE = 'DAYUSE', FULLRENT = 'FULLRENT', RELAYRENT = 'RELAYRENT' } export const enum StateCoupon { NORMAL = 'NORMAL', ABNORMAL = 'ABNORMAL', DELETE = 'DELETE' } export interface ICoupon { id?: number; couponName?: string; couponType?: CouponType; couponAllUse?: boolean; couponUseAffiliateId?: number; couponAmountType?: CouponAmountType; couponDuplication?: boolean; couponAutoPublish?: boolean; couponUseTypeLimit?: boolean; couponUseType?: CouponUseType; couponUsePriceLimit?: boolean; couponUsePrice?: number; couponUseExpireLimit?: boolean; couponUseExpireMonth?: number; couponCreateDt?: Date; couponUpdateDt?: Date; couponCurrentPublishedDt?: Date; couponState?: StateCoupon; } export class Coupon implements ICoupon { constructor( public id?: number, public couponName?: string, public couponType?: CouponType, public couponAllUse?: boolean, public couponUseAffiliateId?: number, public couponAmountType?: CouponAmountType, public couponDuplication?: boolean, public couponAutoPublish?: boolean, public couponUseTypeLimit?: boolean, public couponUseType?: CouponUseType, public couponUsePriceLimit?: boolean, public couponUsePrice?: number, public couponUseExpireLimit?: boolean, public couponUseExpireMonth?: number, public couponCreateDt?: Date, public couponUpdateDt?: Date, public couponCurrentPublishedDt?: Date, public couponState?: StateCoupon ) { this.couponAllUse = this.couponAllUse || false; this.couponDuplication = this.couponDuplication || false; this.couponAutoPublish = this.couponAutoPublish || false; this.couponUseTypeLimit = this.couponUseTypeLimit || false; this.couponUsePriceLimit = this.couponUsePriceLimit || false; this.couponUseExpireLimit = this.couponUseExpireLimit || false; } }
Python
UTF-8
1,266
2.921875
3
[]
no_license
import gettrades import opentrades import closetrades import get_prices import sys import time import oandapy if len(sys.argv) == 4: trials = int(sys.argv[1]) keep_alive = True if int(sys.argv[2]) == 1 else False compress = True if int(sys.argv[3]) == 1 else False print ("keep alive " + str(keep_alive)) print ("compress " + str(compress)) token = "b47aa58922aeae119bcc4de139f7ea1e-27de2d1074bb442b4ad2fe0d637dec22" oanda = oandapy.API(environment="practice", access_token=token, keep_alive=keep_alive, compress=compress) # OPEN AND CLOSE TRADES print ("\nquote: 10 instruments") get_prices.run(oanda, trials, 10) print ("\nquote: 50 instruments") get_prices.run(oanda, trials, 50) print ("\nquote: 120 instruments") get_prices.run(oanda, trials, 120) """ print "\nopen and close trades" closetrades.run(oanda, trials) print ("\n10 trades") gettrades.run(oanda, trials, trades=10) print ("\n50 trades") gettrades.run(oanda, trials, trades=50) print ("\n100 trades") gettrades.run(oanda, trials, trades=100) print ("\n500 trades") gettrades.run(oanda, trials, trades=500) """ else: print "Enter [number of trials] [keep-alive] [compress]"
Java
UTF-8
1,143
2.390625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aplicacion.controlador.beans; import java.io.Serializable; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; /** * * @author Sergio Romero */ @ManagedBean @SessionScoped public class GuestPreferences implements Serializable { private static final long serialVersionUID = 1L; private String theme = "omega"; //tema por defecto /** * Metodo que permite obtener el tema * @return el tema */ public String getTheme() { Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(); if (params.containsKey("theme")) { theme = params.get("theme"); } return theme; } /** * Metodo que permite asignar el tema * @param theme the themes to set */ public void setTheme(String theme) { this.theme = theme; } }