Dataset Viewer
Auto-converted to Parquet
text
stringlengths
6
571k
labels
stringclasses
154 values
/* * Copyright (c) 2000 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include <config.h> __RCSID("$Heimdal: getaddrinfo_hostspec.c 14773 2005-04-12 11:29:18Z lha $" "$NetBSD: getaddrinfo_hostspec.c,v 1.2 2008/03/22 08:37:21 mlelstv Exp $"); #endif #include "roken.h" /* getaddrinfo via string specifying host and port */ int ROKEN_LIB_FUNCTION roken_getaddrinfo_hostspec2(const char *hostspec, int socktype, int port, struct addrinfo **ai) { const char *p; char portstr[NI_MAXSERV]; char host[MAXHOSTNAMELEN]; struct addrinfo hints; int hostspec_len; struct hst { const char *prefix; int socktype; int protocol; int port; } *hstp, hst[] = { { "http://", SOCK_STREAM, IPPROTO_TCP, 80 }, { "http/", SOCK_STREAM, IPPROTO_TCP, 80 }, { "tcp/", SOCK_STREAM, IPPROTO_TCP }, { "udp/", SOCK_DGRAM, IPPROTO_UDP }, { NULL } }; memset(&hints, 0, sizeof(hints)); hints.ai_socktype = socktype; for(hstp = hst; hstp->prefix; hstp++) { if(strncmp(hostspec, hstp->prefix, strlen(hstp->prefix)) == 0) { hints.ai_socktype = hstp->socktype; hints.ai_protocol = hstp->protocol; if(port == 0) port = hstp->port; hostspec += strlen(hstp->prefix); break; } } p = strchr (hostspec, ':'); if (p != NULL) { char *end; port = strtol (p + 1, &end, 0); hostspec_len = p - hostspec; } else { hostspec_len = strlen(hostspec); } snprintf (portstr, sizeof(portstr), "%u", port); snprintf (host, sizeof(host), "%.*s", hostspec_len, hostspec); return getaddrinfo (host, portstr, &hints, ai); } int ROKEN_LIB_FUNCTION roken_getaddrinfo_hostspec(const char *hostspec, int port, struct addrinfo **ai) { return roken_getaddrinfo_hostspec2(hostspec, 0, port, ai); }
C
#ifndef STATIC_GRAPH_HPP #define STATIC_GRAPH_HPP #include "util/graph_traits.hpp" #include "util/integer_range.hpp" #include "util/percent.hpp" #include "util/permutation.hpp" #include "util/typedefs.hpp" #include "util/vector_view.hpp" #include "storage/shared_memory_ownership.hpp" #include "storage/tar_fwd.hpp" #include <boost/assert.hpp> #include <algorithm> #include <limits> #include <type_traits> #include <utility> #include <vector> namespace osrm { namespace util { template <typename EdgeDataT, storage::Ownership Ownership> class StaticGraph; namespace serialization { template <typename EdgeDataT, storage::Ownership Ownership> void read(storage::tar::FileReader &reader, const std::string &name, StaticGraph<EdgeDataT, Ownership> &graph); template <typename EdgeDataT, storage::Ownership Ownership> void write(storage::tar::FileWriter &writer, const std::string &name, const StaticGraph<EdgeDataT, Ownership> &graph); } // namespace serialization namespace static_graph_details { using NodeIterator = NodeID; using EdgeIterator = NodeID; struct NodeArrayEntry { // index of the first edge EdgeIterator first_edge; }; template <typename EdgeDataT> struct EdgeArrayEntry; template <typename EdgeDataT> struct EdgeArrayEntry { NodeID target; EdgeDataT data; }; template <> struct EdgeArrayEntry<void> { NodeID target; }; template <typename EdgeDataT> struct SortableEdgeWithData; template <> struct SortableEdgeWithData<void> { NodeIterator source; NodeIterator target; SortableEdgeWithData() = default; SortableEdgeWithData(NodeIterator source, NodeIterator target) : source(source), target(target) { } bool operator<(const SortableEdgeWithData &right) const { return std::tie(source, target) < std::tie(right.source, right.target); } bool operator==(const SortableEdgeWithData &right) const { return std::tie(source, target) == std::tie(right.source, right.target); } }; template <typename EdgeDataT> struct SortableEdgeWithData : SortableEdgeWithData<void> { using Base = SortableEdgeWithData<void>; EdgeDataT data; SortableEdgeWithData() = default; template <typename... Ts> SortableEdgeWithData(NodeIterator source, NodeIterator target, Ts &&... data) : Base{source, target}, data{std::forward<Ts>(data)...} { } }; template <typename EntryT, typename OtherEdge> EntryT edgeToEntry(const OtherEdge &from, std::true_type) { return EntryT{from.target, from.data}; } template <typename EntryT, typename OtherEdge> EntryT edgeToEntry(const OtherEdge &from, std::false_type) { return EntryT{from.target}; } } // namespace static_graph_details template <typename EdgeDataT, storage::Ownership Ownership = storage::Ownership::Container> class StaticGraph { template <typename T> using Vector = util::ViewOrVector<T, Ownership>; public: using InputEdge = static_graph_details::SortableEdgeWithData<EdgeDataT>; using NodeIterator = static_graph_details::NodeIterator; using EdgeIterator = static_graph_details::EdgeIterator; using EdgeRange = range<EdgeIterator>; using NodeArrayEntry = static_graph_details::NodeArrayEntry; using EdgeArrayEntry = static_graph_details::EdgeArrayEntry<EdgeDataT>; EdgeRange GetAdjacentEdgeRange(const NodeID node) const { return irange(BeginEdges(node), EndEdges(node)); } StaticGraph() {} template <typename ContainerT> StaticGraph(const std::uint32_t nodes, const ContainerT &edges) { BOOST_ASSERT(std::is_sorted(const_cast<ContainerT &>(edges).begin(), const_cast<ContainerT &>(edges).end())); InitializeFromSortedEdgeRange(nodes, edges.begin(), edges.end()); } StaticGraph(Vector<NodeArrayEntry> node_array_, Vector<EdgeArrayEntry> edge_array_) : node_array(std::move(node_array_)), edge_array(std::move(edge_array_)) { BOOST_ASSERT(!node_array.empty()); number_of_nodes = static_cast<decltype(number_of_nodes)>(node_array.size() - 1); number_of_edges = static_cast<decltype(number_of_edges)>(node_array.back().first_edge); BOOST_ASSERT(number_of_edges <= edge_array.size()); BOOST_ASSERT(number_of_nodes == node_array.size() - 1); } unsigned GetNumberOfNodes() const { return number_of_nodes; } unsigned GetNumberOfEdges() const { return number_of_edges; } unsigned GetOutDegree(const NodeIterator n) const { return EndEdges(n) - BeginEdges(n); } inline NodeIterator GetTarget(const EdgeIterator e) const { return NodeIterator(edge_array[e].target); } auto &GetEdgeData(const EdgeIterator e) { return edge_array[e].data; } const auto &GetEdgeData(const EdgeIterator e) const { return edge_array[e].data; } EdgeIterator BeginEdges(const NodeIterator n) const { return EdgeIterator(node_array.at(n).first_edge); } EdgeIterator EndEdges(const NodeIterator n) const { return EdgeIterator(node_array.at(n + 1).first_edge); } // searches for a specific edge EdgeIterator FindEdge(const NodeIterator from, const NodeIterator to) const { for (const auto i : irange(BeginEdges(from), EndEdges(from))) { if (to == edge_array[i].target) { return i; } } return SPECIAL_EDGEID; } /** * Finds the edge with the smallest `.weight` going from `from` to `to` * @param from the source node ID * @param to the target node ID * @param filter a functor that returns a `bool` that determines whether an edge should be * tested or not. * Takes `EdgeData` as a parameter. * @return the ID of the smallest edge if any were found that satisfied *filter*, or * `SPECIAL_EDGEID` if no * matching edge is found. */ template <typename FilterFunction> EdgeIterator FindSmallestEdge(const NodeIterator from, const NodeIterator to, FilterFunction &&filter) const { static_assert(traits::HasDataMember<EdgeArrayEntry>::value, "Filtering on .data not possible without .data member attribute"); EdgeIterator smallest_edge = SPECIAL_EDGEID; EdgeWeight smallest_weight = INVALID_EDGE_WEIGHT; for (auto edge : GetAdjacentEdgeRange(from)) { const NodeID target = GetTarget(edge); const auto &data = GetEdgeData(edge); if (target == to && data.weight < smallest_weight && std::forward<FilterFunction>(filter)(data)) { smallest_edge = edge; smallest_weight = data.weight; } } return smallest_edge; } EdgeIterator FindEdgeInEitherDirection(const NodeIterator from, const NodeIterator to) const { EdgeIterator tmp = FindEdge(from, to); return (SPECIAL_NODEID != tmp ? tmp : FindEdge(to, from)); } EdgeIterator FindEdgeIndicateIfReverse(const NodeIterator from, const NodeIterator to, bool &result) const { EdgeIterator current_iterator = FindEdge(from, to); if (SPECIAL_NODEID == current_iterator) { current_iterator = FindEdge(to, from); if (SPECIAL_NODEID != current_iterator) { result = true; } } return current_iterator; } void Renumber(const std::vector<NodeID> &old_to_new_node) { std::vector<NodeID> new_to_old_node(number_of_nodes); for (auto node : util::irange<NodeID>(0, number_of_nodes)) new_to_old_node[old_to_new_node[node]] = node; Vector<NodeArrayEntry> new_node_array(node_array.size()); // Build up edge permutation auto new_edge_index = 0; std::vector<EdgeID> old_to_new_edge(edge_array.size(), SPECIAL_EDGEID); for (auto node : util::irange<NodeID>(0, number_of_nodes)) { auto new_first_edge = new_edge_index; for (auto edge : GetAdjacentEdgeRange(new_to_old_node[node])) { edge_array[edge].target = old_to_new_node[edge_array[edge].target]; old_to_new_edge[edge] = new_edge_index++; } new_node_array[node].first_edge = new_first_edge; } new_node_array.back().first_edge = new_edge_index; node_array = std::move(new_node_array); BOOST_ASSERT(std::find(old_to_new_edge.begin(), old_to_new_edge.end(), SPECIAL_EDGEID) == old_to_new_edge.end()); util::inplacePermutation(edge_array.begin(), edge_array.end(), old_to_new_edge); } friend void serialization::read<EdgeDataT, Ownership>(storage::tar::FileReader &reader, const std::string &name, StaticGraph<EdgeDataT, Ownership> &graph); friend void serialization::write<EdgeDataT, Ownership>(storage::tar::FileWriter &writer, const std::string &name, const StaticGraph<EdgeDataT, Ownership> &graph); protected: template <typename IterT> void InitializeFromSortedEdgeRange(const std::uint32_t nodes, IterT begin, IterT end) { number_of_nodes = nodes; number_of_edges = static_cast<EdgeIterator>(std::distance(begin, end)); node_array.reserve(number_of_nodes + 1); node_array.push_back(NodeArrayEntry{0u}); auto iter = begin; for (auto node : util::irange(0u, nodes)) { iter = std::find_if(iter, end, [node](const auto &edge) { return edge.source != node; }); unsigned offset = std::distance(begin, iter); node_array.push_back(NodeArrayEntry{offset}); } BOOST_ASSERT_MSG( iter == end, ("Still " + std::to_string(std::distance(iter, end)) + " edges left.").c_str()); BOOST_ASSERT(node_array.size() == number_of_nodes + 1); edge_array.resize(number_of_edges); std::transform(begin, end, edge_array.begin(), [](const auto &from) { return static_graph_details::edgeToEntry<EdgeArrayEntry>( from, traits::HasDataMember<EdgeArrayEntry>{}); }); } protected: NodeIterator number_of_nodes; EdgeIterator number_of_edges; Vector<NodeArrayEntry> node_array; Vector<EdgeArrayEntry> edge_array; }; } // namespace util } // namespace osrm #endif // STATIC_GRAPH_HPP
C++
from BDall import * from MetodosBD import basedatos from random import randrange import time from datetime import date print("bienvenido a los Tacos de perro : 7 C/U") option= int(input("Ver Menu: 1 \nHacer Pedido: 2 \nMostrar Pedido: 3 \nCancelar Pedido: 4 \n")) cont = 0 db = basedatos() today=date.today() while cont == 0: if option == 1: res = basedatos.selectTaco(db) print(res) elif option == 2: usuario = input("Introduzca su id:") u = basedatos.selectCliente(db,usuario) if (u == True): pedido = int(input("¿Qué taco va a querer (Introduzca su id)?")) if(pedido <= 100): id_orden = randrange(100) fecha =str(date(today.year, today.month, today.day)) tipo = input("¿con salsa o sin salsa primo?") res1 = basedatos.insertarOrden_db(db,id_orden,'60',fecha,tipo,pedido,usuario) elif(pedido > 100): print('Se acabo el guiso') elif option == 3: orden = input("Introduzca su id de Pedido:") res = basedatos.selectOrden(db,orden) print(res) elif option == 4: orden = input("Introduzca el id del Pedido a eliminar:") res = basedatos.deleteOrden(db,orden) if (res == True): print('Pedido Eliminado') else: print('La orden renuncio (no esta)') else: print("Cambiale primo, no existe esa opcion.\n") cont= 1
Python
require 'spec_helper' describe 'apt::hold' do let :facts do { :osfamily => 'Debian', :lsbdistid => 'Debian', :lsbrelease => 'wheezy', } end let :title do 'vim' end let :default_params do { :version => '1.1.1', } end describe 'default params' do let :params do default_params end it 'creates an apt preferences file' do should contain_apt__hold(title).with({ :ensure => 'present', :package => title, :version => params[:version], :priority => 1001, }) should contain_apt__pin("hold #{title} at #{params[:version]}").with({ :ensure => 'present', :packages => title, :version => params[:version], :priority => 1001, }) end end describe 'ensure => absent' do let :params do default_params.merge({:ensure => 'absent',}) end it 'creates an apt preferences file' do should contain_apt__hold(title).with({ :ensure => params[:ensure], }) should contain_apt__pin("hold #{title} at #{params[:version]}").with({ :ensure => params[:ensure], }) end end describe 'priority => 990' do let :params do default_params.merge({:priority => 990,}) end it 'creates an apt preferences file' do should contain_apt__hold(title).with({ :ensure => 'present', :package => title, :version => params[:version], :priority => params[:priority], }) should contain_apt__pin("hold #{title} at #{params[:version]}").with({ :ensure => 'present', :packages => title, :version => params[:version], :priority => params[:priority], }) end end describe 'validation' do context 'version => {}' do let :params do { :version => {}, } end it 'should fail' do expect { subject }.to raise_error(/is not a string/) end end context 'ensure => bananana' do let :params do default_params.merge({:ensure => 'bananana',}) end it 'should fail' do expect { subject }.to raise_error(/does not match/) end end context 'package => []' do let :params do default_params.merge({:package => [],}) end it 'should fail' do expect { subject }.to raise_error(/is not a string/) end end context 'priority => bananana' do let :params do default_params.merge({:priority => 'bananana',}) end it 'should fail' do expect { subject }.to raise_error(/must be an integer/) end end end end
Ruby
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * User Engine Model * * @author(s) Tyler Diaz * @version 1.0 * @copyright Tyler Diaz - August 6, 2010 * @last_update: May 2, 2011 by Tyler Diaz **/ class User_engine extends CI_Model { var $update_queue = array(); function __construct() { parent::__construct(); } // -------------------------------------------------------------------- /** * New function * * Description of new function * * @access public * @param none * @return output */ public function get($value = 0, $key = 'user_id') { $user_query = $this->db->get_where('users', array($key => $value)); if($user_query->num_rows() > 0): return $user_query->row_array(); else: return FALSE; endif; } // -------------------------------------------------------------------- /** * New function * * Description of new function * * @access public * @param none * @return output */ public function set($key = '', $value = '', $user_id = 0) { if($user_id == 0): $user_id = $this->system->userdata['user_id']; $this->system->userdata[$key] = $value; $this->session->userdata[$key] = $value; endif; $this->update_queue[$user_id]['user_id'] = $user_id; $this->update_queue[$user_id][$key] = $value; } // -------------------------------------------------------------------- /** * New function * * Description of new function * * @access public * @param none * @return output */ public function remove($key = '', $value = '', $user_id = 0) { if($user_id == 0): $user_id = $this->system->userdata['user_id']; if(isset($this->session->userdata[$key])) $this->session->userdata[$key] -= $value; endif; $this->update_queue[$user_id]['user_id'] = $user_id; $this->update_queue[$user_id][$key] = ($this->system->userdata[$key]-$value); } // -------------------------------------------------------------------- /** * New function * * Description of new function * * @access public * @param none * @return output */ public function add($key = '', $value = '', $user_id = 0) { if($user_id == 0): $user_id = $this->system->userdata['user_id']; if(isset($this->session->userdata[$key])) $this->session->userdata[$key] += $value; endif; $this->update_queue[$user_id]['user_id'] = $user_id; $this->update_queue[$user_id][$key] = ($this->system->userdata[$key]+$value); } // -------------------------------------------------------------------- /** * New function * * Description of new function * * @access public * @param none * @return output */ public function add_item($item_id = 0, $amount = 1, $user_id = 0, $equipped = 0) { if($user_id === 0) $user_id = $this->system->userdata['user_id']; $new_user_item_data = array( 'item_id' => $item_id, 'user_id' => $user_id, 'equipped' => $equipped, 'trying_on' => $equipped, 'soft_deleted' => '0', 'sent_by' => $this->system->userdata['user_id'] ); for ($i=0; $i < $amount; $i++): $new_user_item_id = $this->db->insert('user_items', $new_user_item_data); endfor; return $new_user_item_id; } // -------------------------------------------------------------------- /** * New function * * Description of new function * * @access public * @param none * @return output */ public function remove_item($item_id = 0, $amount = 0, $user_id = 0, $equipped = 0) { if($user_id === 0) $user_id = $this->system->userdata['user_id']; $this->db->limit($amount)->delete('user_items', array('item_id' => $item_id, 'user_id' => $user_id, 'soft_deleted' => 0, 'equipped' => $equipped)); return $this->db->affected_rows(); } // -------------------------------------------------------------------- function __destruct() { if(count($this->update_queue) > 0) $this->db->update_batch('users', $this->update_queue, 'user_id'); } } /* End of file system.php */ /* Location: ./system/application/models/user_engine.php */
PHP
/* * FINBOURNE Identity Service API * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.0.1547 * Contact: [email protected] * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Finbourne.Identity.Sdk.Client.OpenAPIDateConverter; namespace Finbourne.Identity.Sdk.Model { /// <summary> /// Timestamped successful response to grant access to your account /// </summary> [DataContract(Name = "SupportAccessResponse")] public partial class SupportAccessResponse : IEquatable<SupportAccessResponse> { /// <summary> /// Initializes a new instance of the <see cref="SupportAccessResponse" /> class. /// </summary> [JsonConstructorAttribute] protected SupportAccessResponse() { } /// <summary> /// Initializes a new instance of the <see cref="SupportAccessResponse" /> class. /// </summary> /// <param name="id">ID of the support access request (required).</param> /// <param name="duration">The duration for which access is requested (in any ISO-8601 format) (required).</param> /// <param name="description">The description of why the support access has been granted (i.e. support ticket numbers).</param> /// <param name="createdAt">DateTimeOffset at which the access was granted (required).</param> /// <param name="expiry">DateTimeOffset at which the access will be revoked (required).</param> /// <param name="createdBy">Obfuscated UserId of the user who granted the support access (required).</param> /// <param name="terminated">Whether or not that access has been invalidated.</param> /// <param name="terminatedAt">DateTimeOffset at which the access was invalidated.</param> /// <param name="terminatedBy">Obfuscated UserId of the user who revoked the access.</param> public SupportAccessResponse(string id = default(string), string duration = default(string), string description = default(string), DateTimeOffset createdAt = default(DateTimeOffset), DateTimeOffset expiry = default(DateTimeOffset), string createdBy = default(string), bool terminated = default(bool), DateTimeOffset? terminatedAt = default(DateTimeOffset?), string terminatedBy = default(string)) { // to ensure "id" is required (not null) this.Id = id ?? throw new ArgumentNullException("id is a required property for SupportAccessResponse and cannot be null"); // to ensure "duration" is required (not null) this.Duration = duration ?? throw new ArgumentNullException("duration is a required property for SupportAccessResponse and cannot be null"); this.CreatedAt = createdAt; this.Expiry = expiry; // to ensure "createdBy" is required (not null) this.CreatedBy = createdBy ?? throw new ArgumentNullException("createdBy is a required property for SupportAccessResponse and cannot be null"); this.Description = description; this.Terminated = terminated; this.TerminatedAt = terminatedAt; this.TerminatedBy = terminatedBy; } /// <summary> /// ID of the support access request /// </summary> /// <value>ID of the support access request</value> [DataMember(Name = "id", IsRequired = true, EmitDefaultValue = false)] public string Id { get; set; } /// <summary> /// The duration for which access is requested (in any ISO-8601 format) /// </summary> /// <value>The duration for which access is requested (in any ISO-8601 format)</value> [DataMember(Name = "duration", IsRequired = true, EmitDefaultValue = false)] public string Duration { get; set; } /// <summary> /// The description of why the support access has been granted (i.e. support ticket numbers) /// </summary> /// <value>The description of why the support access has been granted (i.e. support ticket numbers)</value> [DataMember(Name = "description", EmitDefaultValue = true)] public string Description { get; set; } /// <summary> /// DateTimeOffset at which the access was granted /// </summary> /// <value>DateTimeOffset at which the access was granted</value> [DataMember(Name = "createdAt", IsRequired = true, EmitDefaultValue = false)] public DateTimeOffset CreatedAt { get; set; } /// <summary> /// DateTimeOffset at which the access will be revoked /// </summary> /// <value>DateTimeOffset at which the access will be revoked</value> [DataMember(Name = "expiry", IsRequired = true, EmitDefaultValue = false)] public DateTimeOffset Expiry { get; set; } /// <summary> /// Obfuscated UserId of the user who granted the support access /// </summary> /// <value>Obfuscated UserId of the user who granted the support access</value> [DataMember(Name = "createdBy", IsRequired = true, EmitDefaultValue = false)] public string CreatedBy { get; set; } /// <summary> /// Whether or not that access has been invalidated /// </summary> /// <value>Whether or not that access has been invalidated</value> [DataMember(Name = "terminated", EmitDefaultValue = true)] public bool Terminated { get; set; } /// <summary> /// DateTimeOffset at which the access was invalidated /// </summary> /// <value>DateTimeOffset at which the access was invalidated</value> [DataMember(Name = "terminatedAt", EmitDefaultValue = true)] public DateTimeOffset? TerminatedAt { get; set; } /// <summary> /// Obfuscated UserId of the user who revoked the access /// </summary> /// <value>Obfuscated UserId of the user who revoked the access</value> [DataMember(Name = "terminatedBy", EmitDefaultValue = true)] public string TerminatedBy { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class SupportAccessResponse {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Duration: ").Append(Duration).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" CreatedAt: ").Append(CreatedAt).Append("\n"); sb.Append(" Expiry: ").Append(Expiry).Append("\n"); sb.Append(" CreatedBy: ").Append(CreatedBy).Append("\n"); sb.Append(" Terminated: ").Append(Terminated).Append("\n"); sb.Append(" TerminatedAt: ").Append(TerminatedAt).Append("\n"); sb.Append(" TerminatedBy: ").Append(TerminatedBy).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as SupportAccessResponse); } /// <summary> /// Returns true if SupportAccessResponse instances are equal /// </summary> /// <param name="input">Instance of SupportAccessResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(SupportAccessResponse input) { if (input == null) return false; return ( this.Id == input.Id || (this.Id != null && this.Id.Equals(input.Id)) ) && ( this.Duration == input.Duration || (this.Duration != null && this.Duration.Equals(input.Duration)) ) && ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.CreatedAt == input.CreatedAt || (this.CreatedAt != null && this.CreatedAt.Equals(input.CreatedAt)) ) && ( this.Expiry == input.Expiry || (this.Expiry != null && this.Expiry.Equals(input.Expiry)) ) && ( this.CreatedBy == input.CreatedBy || (this.CreatedBy != null && this.CreatedBy.Equals(input.CreatedBy)) ) && ( this.Terminated == input.Terminated || this.Terminated.Equals(input.Terminated) ) && ( this.TerminatedAt == input.TerminatedAt || (this.TerminatedAt != null && this.TerminatedAt.Equals(input.TerminatedAt)) ) && ( this.TerminatedBy == input.TerminatedBy || (this.TerminatedBy != null && this.TerminatedBy.Equals(input.TerminatedBy)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Id != null) hashCode = hashCode * 59 + this.Id.GetHashCode(); if (this.Duration != null) hashCode = hashCode * 59 + this.Duration.GetHashCode(); if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.CreatedAt != null) hashCode = hashCode * 59 + this.CreatedAt.GetHashCode(); if (this.Expiry != null) hashCode = hashCode * 59 + this.Expiry.GetHashCode(); if (this.CreatedBy != null) hashCode = hashCode * 59 + this.CreatedBy.GetHashCode(); hashCode = hashCode * 59 + this.Terminated.GetHashCode(); if (this.TerminatedAt != null) hashCode = hashCode * 59 + this.TerminatedAt.GetHashCode(); if (this.TerminatedBy != null) hashCode = hashCode * 59 + this.TerminatedBy.GetHashCode(); return hashCode; } } } }
C#
#!/bin/bash # -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*- # ex: ts=8 sw=4 sts=4 et filetype=sh # # Automation script to create specs to build cc-shim set -e source ../versions.txt source ../scripts/pkglib.sh SCRIPT_NAME=$0 SCRIPT_DIR=$(dirname $0) PKG_NAME="cc-shim" VERSION=$cc_shim_version RELEASE=$(cat release) APPORT_HOOK="source_cc-shim.py" BUILD_DISTROS=(Fedora_26 xUbuntu_16.04) COMMIT=false BRANCH=false LOCAL_BUILD=false OBS_PUSH=false VERBOSE=false GENERATED_FILES=(cc-shim.spec cc-shim.dsc _service debian.control debian.rules) STATIC_FILES=(debian.compat) # Parse arguments cli "$@" [ "$VERBOSE" == "true" ] && set -x || true PROJECT_REPO=${PROJECT_REPO:-home:clearcontainers:clear-containers-3-staging/cc-shim} [ -n "$APIURL" ] && APIURL="-A ${APIURL}" || true function template() { sed -e "s/@VERSION@/$VERSION/g" \ -e "s/@RELEASE@/$RELEASE/g" \ -e "s/@HASH@/$short_hashtag/g" cc-shim.spec-template > cc-shim.spec sed -e "s/@HASH@/$short_hashtag/" debian.rules-template > debian.rules sed -e "s/@VERSION@/$VERSION/g" \ -e "s/@HASH@/$short_hashtag/g" \ -e "s/@RELEASE@/$RELEASE/g" cc-shim.dsc-template > cc-shim.dsc sed -e "s/@VERSION@/$VERSION/g" \ -e "s/@HASH@/$short_hashtag/g" debian.control-template > debian.control # If OBS_REVISION is not empty, which means a branch or commit ID has been passed as argument, # replace It as @REVISION@ it in the OBS _service file. Otherwise, use the VERSION variable, # which uses the version from versions.txt. # This will determine which source tarball will be retrieved from github.com if [ -n "$OBS_REVISION" ]; then sed "s/@REVISION@/$OBS_REVISION/" _service-template > _service else sed "s/@REVISION@/$VERSION/" _service-template > _service fi } verify echo "Verify succeed." get_git_info set_versions $cc_shim_hash changelog_update $VERSION template if [ "$LOCAL_BUILD" == "true" ] && [ "$OBS_PUSH" == "true" ] then die "--local-build and --push are mutually exclusive." elif [ "$LOCAL_BUILD" == "true" ] then checkout_repo $PROJECT_REPO local_build elif [ "$OBS_PUSH" == "true" ] then checkout_repo $PROJECT_REPO obs_push fi echo "OBS working copy directory: ${OBS_WORKDIR}"
Shell
import {DOCUMENT} from '@angular/common'; import {ElementRef, Inject, Injectable} from '@angular/core'; import {getElementPoint} from '@taiga-ui/addon-editor/utils'; import {TuiDestroyService, typedFromEvent} from '@taiga-ui/cdk'; import {TuiPoint} from '@taiga-ui/core'; import {Observable} from 'rxjs'; import {map, startWith, switchMap, takeUntil} from 'rxjs/operators'; // @dynamic @Injectable() export class TuiPickerService extends Observable<TuiPoint> { constructor( @Inject(TuiDestroyService) destroy$: Observable<void>, @Inject(ElementRef) {nativeElement}: ElementRef<HTMLElement>, @Inject(DOCUMENT) documentRef: Document, ) { const point$ = typedFromEvent(nativeElement, 'mousedown').pipe( switchMap(event => { event.preventDefault(); const mouseMove$ = typedFromEvent(documentRef, 'mousemove').pipe( map(({clientX, clientY}) => getElementPoint(clientX, clientY, nativeElement), ), takeUntil(typedFromEvent(documentRef, 'mouseup')), ); return event.target === nativeElement ? mouseMove$.pipe( startWith( getElementPoint( event.clientX, event.clientY, nativeElement, ), ), ) : mouseMove$; }), takeUntil(destroy$), ); super(subscriber => point$.subscribe(subscriber)); } }
TypeScript
type BuildPowersOf2LengthArrays< N extends number, R extends never[][] > = R[0][N] extends never ? R : BuildPowersOf2LengthArrays<N, [[...R[0], ...R[0]], ...R]>; type ConcatLargestUntilDone< N extends number, R extends never[][], B extends never[] > = B["length"] extends N ? B : [...R[0], ...B][N] extends never ? ConcatLargestUntilDone< N, R extends [R[0], ...infer U] ? (U extends never[][] ? U : never) : never, B > : ConcatLargestUntilDone< N, R extends [R[0], ...infer U] ? (U extends never[][] ? U : never) : never, [...R[0], ...B] >; /** * Replaces the types in the Tuple, `R`, with type `T` */ type Replace<R extends any[], T> = { [K in keyof R]: T }; /** * Creates a Tuple type of length `N` and type `T`. */ type TupleOf<T, N extends number> = number extends N ? T[] : { [K in N]: BuildPowersOf2LengthArrays<K, [[never]]> extends infer U ? U extends never[][] ? Replace<ConcatLargestUntilDone<K, U, []>, T> : never : never; }[N]; /** * Returns all but the last element from `T` */ type Head<T extends any[]> = T extends [...infer Head, any] ? Head : any[]; export type RangeOfInclusive<To extends number> = Partial< TupleOf<unknown, To> >["length"]; type UnionToTuple<T> = ( (T extends any ? (t: T) => T : never) extends infer U ? (U extends any ? (u: U) => any : never) extends (v: infer V) => any ? V : never : never ) extends (_: any) => infer W ? [...UnionToTuple<Exclude<T, W>>, W] : []; /** * Generates a unioned range of numbers from 0 to `To` */ export type RangeOf<To extends number> = Partial< Head<TupleOf<unknown, To>> >["length"]; /** * Given a length, computes the union of all lengths after the * index. * * * @example * ```typescript * function slice<T extends unknown[], Size extends number = RangeOf<T["length"]>>( * tuple: T, * index: Size, * length: Remainders<T["length"], typeof index> * ) { * return tuple.slice(index, index + length); * } * const tuple: TupleOf<number, 5> = [1, 2, 3, 4, 5]; * slice(tuple, 0, 6); * ^ // Argument of type '6' is not assignable to parameter of type '0 | 1 | 2' * ``` * * @implementation * 1. generate a union of the numbers 0..Length and 0..Index * 2. exclude from the range `0..Length` all numbers that are also in `0..Index` * 3. convert the remining union into a tuple so we can count the remaining numbers * 4. Use `Partial<Tuple>["length"]` to compute the union of all possible Tuple lengths * 5. Make sure TypeScript remembers that we are a number (`& number`) */ export type Remainders<Length extends number, Index extends number> = // `Partial<Tuple>["length"]` computes the union of all possible Tuple lengths Partial< // convert the union of remaining into a tuple so we can count how many we have left UnionToTuple< // Exclude from the range `0..Length` the numbers thath are also in `0..Index` Exclude<RangeOfInclusive<Length>, RangeOfInclusive<Index>> > >["length"] & number;
TypeScript
in vec2 fTexCoord; layout(binding = 0) uniform sampler2D diffuseTexture; #ifdef BILATERAL layout(binding = 1) uniform sampler2D depthTexture; #endif uniform vec2 blurDirection; uniform float offset[80]; uniform float weight[80]; uniform int kernelSize; #ifdef BLUR_RGB out vec3 color; #endif #ifdef BLUR_RG out vec2 color; #endif #ifdef BLUR_R out float color; #endif void main() { #ifdef BLUR_RGB color = texture(diffuseTexture, fTexCoord).rgb * weight[0]; for(int i = 1; i < kernelSize; i++) color += texture(diffuseTexture, fTexCoord + (vec2(offset[i]) * blurDirection)).rgb * weight[i]; for (int i = 1; i < kernelSize; i++) color += texture(diffuseTexture, fTexCoord - (vec2(offset[i]) * blurDirection)).rgb * weight[i]; #endif #ifdef BLUR_RG color = texture(diffuseTexture, fTexCoord).rg * weight[0]; for(int i = 1; i < kernelSize; i++) color += texture(diffuseTexture, fTexCoord + (vec2(offset[i]) * blurDirection)).rg * weight[i]; for (int i = 1; i < kernelSize; i++) color += texture(diffuseTexture, fTexCoord - (vec2(offset[i]) * blurDirection)).rg * weight[i]; #endif #ifdef BLUR_R float centerColor = texture(diffuseTexture, fTexCoord).r; #ifdef BILATERAL float centerDepth = texture(depthTexture, fTexCoord).r; #endif color = centerColor * weight[0]; float closeness = 1.0f; float totalWeight = weight[0]; for(int i = 1; i < kernelSize; i++) { float texColor = texture(diffuseTexture, fTexCoord + (vec2(offset[i]) * blurDirection)).r; float currentWeight = weight[i]; #ifdef BILATERAL float depth = texture(depthTexture, fTexCoord + (vec2(offset[i]) * blurDirection)).r; closeness = max(0.0f, 1.0f - 1000.0f * abs(centerDepth - depth)); currentWeight *= closeness; totalWeight += currentWeight; #endif color += texColor * currentWeight; } for(int i = 1; i < kernelSize; i++) { float texColor = texture(diffuseTexture, fTexCoord - (vec2(offset[i]) * blurDirection)).r; float currentWeight = weight[i]; #ifdef BILATERAL float depth = texture(depthTexture, fTexCoord - (vec2(offset[i]) * blurDirection)).r; closeness = max(0.0f, 1.0f - 1000.0f * abs(centerDepth - depth)); currentWeight *= closeness; totalWeight += currentWeight; #endif color += texColor * currentWeight; } #ifdef BILATERAL color /= totalWeight; #endif #endif }
GLSL
<div class="jarviswidget jarviswidget-color-darken" id="wid-id-audit" data-widget-editbutton="false" data-widget-deletebutton="false"> <header> <span class="widget-icon"> <i class="fa fa-history"></i> </span> <h2>Audit Trail</h2> </header> <!-- widget div--> <div> <!-- widget content --> <div class="widget-body no-padding"> <table class="table table-hover no-margins"> <thead> <tr> <th>When</th> <th>Who</th> <th>Changes</th> </tr> </thead> <tbody> @foreach($subject->AuditTrail as $change) <tr> <td> <i class="fa fa-clock-o"></i> {{$change->pivot->created_at->diffForHumans()}}<br/> &nbsp;&nbsp;&nbsp; <small>( {{$change->pivot->created_at->format('d M y')}} )</small> </td> <td>{{$change->name}}</td> <td style="padding-top: 0"> {!! tracker\Helpers\HtmlFormating::FormatAuditTrail( $change->pivot->before, $change->pivot->after ) !!} </td> </tr> @endforeach </tbody> </table> </div> </div> </div>
PHP
from django.http import HttpResponse from django.template import RequestContext, loader from photologue.models import Gallery def index(request): template = loader.get_template('under_construction.html') context = RequestContext(request) return HttpResponse(template.render(context)) def gallery(request): photos = Gallery.objects.all() template = loader.get_template('gallery.html') context = RequestContext(request, { 'object_list': photos, 'extra_js_file': ['gallery/fancybox/source/jquery.mousewheel-3.0.6.pack.js', 'gallery/fancybox/source/jquery.fancybox.pack.js', 'gallery/fancybox/source/helpers/jquery.fancybox-buttons.js', 'gallery/fancybox/source/helpers/jquery.fancybox-media.js', 'gallery/fancybox/source/helpers/jquery.fancybox-thumbs.js'], 'extra_css_file': ['gallery/fancybox/source/jquery.fancybox.css', 'gallery/fancybox/source/helpers/jquery.fancybox-buttons.css', 'gallery/fancybox/source/helpers/jquery.fancybox-thumbs.css'], }) return HttpResponse(template.render(context))
Python
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class KeywordsController extends Controller { public function index() { if (\Auth::check()) { // 認証済みの場合 // 認証済みユーザを取得 $user = \Auth::user(); // ユーザのキーワードの一覧を取得 $keywords = $user->keywords()->get(); } return view('news.keywords', [ 'keywords' => $keywords, ]); } public function store(Request $request){ if($request->keyword === null){ return back(); }else{ // 認証済みユーザ(閲覧者)の投稿として作成(リクエストされた値をもとに作成) $request->user()->keywords()->create([ 'keyword' => $request->keyword, ]); // 前のURLへリダイレクトさせる return back(); } } public function destroy($id){ // idの値で投稿を検索して取得 $keyword = \App\Keyword::findOrFail($id); // 認証済みユーザ(閲覧者)がその投稿の所有者である場合は、投稿を削除 if (\Auth::id() === $keyword->user_id) { $keyword->delete(); } // 前のURLへリダイレクトさせる return back(); } }
PHP
export {DateCustomBase as DateCustom} from "../classesBase/DateCustomBase.js";
TypeScript
package mobi import ( "bytes" "encoding/binary" ) func (w *MobiWriter) chapterIsDeep() bool { for _, node := range w.chapters { if node.SubChapterCount() > 0 { return true } } return false } func (w *MobiWriter) writeINDX_1() { buf := new(bytes.Buffer) // Tagx tagx := mobiTagx{} if w.chapterIsDeep() { tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_Pos]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_Len]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_NameOffset]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_DepthLvl]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_Parent]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_Child1]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_ChildN]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_END]) } else { tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_Pos]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_Len]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_NameOffset]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_DepthLvl]) tagx.Tags = append(tagx.Tags, mobiTagxMap[TagEntry_END]) } /*************************************/ /*************************************/ magicTagx.WriteTo(&tagx.Identifier) tagx.ControlByteCount = 1 tagx.HeaderLenght = uint32(tagx.TagCount()*4) + 12 TagX := new(bytes.Buffer) binary.Write(TagX, binary.BigEndian, tagx.Identifier) binary.Write(TagX, binary.BigEndian, tagx.HeaderLenght) binary.Write(TagX, binary.BigEndian, tagx.ControlByteCount) binary.Write(TagX, binary.BigEndian, tagx.Tags) // Indx // IndxBin := new(bytes.Buffer) indx := mobiIndx{} magicIndx.WriteTo(&indx.Identifier) indx.HeaderLen = MOBI_INDX_HEADER_LEN indx.Indx_Type = INDX_TYPE_INFLECTION indx.Idxt_Count = 1 indx.Idxt_Encoding = MOBI_ENC_UTF8 indx.SetUnk2 = 4294967295 indx.Cncx_Records_Count = 1 indx.Idxt_Entry_Count = uint32(w.chapterCount) indx.Tagx_Offset = MOBI_INDX_HEADER_LEN //binary.Write(IndxBin, binary.BigEndian, indx) // Idxt /************/ IdxtLast := len(w.Idxt.Offset) Offset := w.Idxt.Offset[IdxtLast-1] Rec := w.cncxBuffer.Bytes()[Offset-MOBI_INDX_HEADER_LEN:] Rec = Rec[0 : Rec[0]+1] RLen := len(Rec) //w.File.Write(Rec) Padding := (RLen + 2) % 4 //IDXT_OFFSET, := w.File.Seek(0, 1) indx.Idxt_Offset = MOBI_INDX_HEADER_LEN + uint32(TagX.Len()) + uint32(RLen+2+Padding) // Offset to Idxt Record //w.Idxt1.Offset = []uint16{uint16(offset)} /************/ binary.Write(buf, binary.BigEndian, indx) buf.Write(TagX.Bytes()) buf.Write(Rec) binary.Write(buf, binary.BigEndian, uint16(IdxtLast)) for Padding != 0 { buf.Write([]byte{0}) Padding-- } buf.WriteString(magicIdxt.String()) binary.Write(buf, binary.BigEndian, uint16(MOBI_INDX_HEADER_LEN+uint32(TagX.Len()))) //ioutil.WriteFile("TAGX_TEST", TagX.Bytes(), 0644) //ioutil.WriteFile("INDX_TEST", IndxBin.Bytes(), 0644) buf.Write([]uint8{0, 0}) w.Header.IndxRecodOffset = w.AddRecord(buf.Bytes()).UInt32() } func (w *MobiWriter) writeINDX_2() { buf := new(bytes.Buffer) indx := mobiIndx{} magicIndx.WriteTo(&indx.Identifier) indx.HeaderLen = MOBI_INDX_HEADER_LEN indx.Indx_Type = INDX_TYPE_NORMAL indx.Unk1 = uint32(1) indx.Idxt_Encoding = 4294967295 indx.SetUnk2 = 4294967295 indx.Idxt_Offset = uint32(MOBI_INDX_HEADER_LEN + w.cncxBuffer.Len()) indx.Idxt_Count = uint32(len(w.Idxt.Offset)) binary.Write(buf, binary.BigEndian, indx) buf.Write(w.cncxBuffer.Bytes()) buf.WriteString(magicIdxt.String()) for _, offset := range w.Idxt.Offset { //Those offsets are not relative INDX record. //So we need to adjust that. binary.Write(buf, binary.BigEndian, offset) //+MOBI_INDX_HEADER_LEN) } Padding := (len(w.Idxt.Offset) + 4) % 4 for Padding != 0 { buf.Write([]byte{0}) Padding-- } w.AddRecord(buf.Bytes()) w.AddRecord(w.cncxLabelBuffer.Bytes()) }
Go
import {Map} from "immutable"; import {validateSchema} from "../../validateSchema/index"; import {createValidatorErrors} from "@ui-schema/ui-schema/ValidityReporter/ValidatorErrors"; export const ERROR_ADDITIONAL_PROPERTIES = 'additional-properties'; /** * Return false when valid and string for an error * * @param schema * @param value * @return {List} */ export const validateObject = (schema, value) => { let err = createValidatorErrors(); if(schema.get('additionalProperties') === false && schema.get('properties') && typeof value === 'object') { let hasAdditional = false; const keys = Map.isMap(value) ? value.keySeq() : Object.keys(value); const schemaKeys = schema.get('properties').keySeq(); keys.forEach(key => { // todo: add all invalid additional or change to `for key of value` to break after first invalid if(schemaKeys.indexOf(key) === -1) hasAdditional = true; }); if(hasAdditional) { err = err.addError(ERROR_ADDITIONAL_PROPERTIES); } } if(schema.get('propertyNames') && typeof value === 'object') { const keys = Map.isMap(value) ? value.keySeq() : Object.keys(value); keys.forEach(key => { let tmp_err = validateSchema(schema.get('propertyNames').set('type', 'string'), key); if(tmp_err.hasError()) { err = err.addErrors(tmp_err); } /*if(typeof tmp_err === 'string' || (List.isList(tmp_err) && tmp_err.size)) { if(List.isList(tmp_err)) { err = err.concat(tmp_err); } else { err = err.push(tmp_err); } }*/ }); } return err; }; export const objectValidator = { should: ({schema}) => { let type = schema.get('type'); return type === 'object' }, validate: ({schema, value, errors, valid}) => { errors = validateObject(schema, value,); if(errors.hasError()) valid = false; return {errors, valid} } };
JavaScript
using FinCleaner.Model; namespace FinCleaner.Rules; public interface IRule { IEnumerable<Transaction> Apply(Transaction transaction); }
C#
# coding:utf-8 from PyQt5.QtCore import QThread, pyqtSignal, Qt from PyQt5.QtWidgets import * from PyQt5 import QtGui import sys import itchat from itchat.content import * import datetime import time import os import top.api import requests import json import re from urllib.request import urlretrieve import traceback current_path = os.path.dirname(os.path.abspath(__file__)) global chatrooms class MainGUI(QMainWindow): def __init__(self): super().__init__() self.iniUI() ''' 程序默认UI界面信息 ''' def iniUI(self): self.setWindowTitle("淘宝客微信机器人v0.1") self.resize(1200, 600) self.vertical_box_layout() self.chatroom_list = [] self.current_date = datetime.datetime.strftime(datetime.datetime.today(),'%Y-%m-%d') # 设置程序图标 icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("logo.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) # 水平垂直布局 def vertical_box_layout(self): ''' 上层功能盒子 ''' # 创建一个用于存放登录相关按钮的窗口部件 login_buttons = QWidget() login_buttons_box = QVBoxLayout() # 设置窗口部件的布局为垂直盒子布局 login_buttons.setLayout(login_buttons_box) # 创建两个登录相关的按钮 self.refresh_button = QPushButton("点击登录") self.refresh_button.clicked.connect(self.login_wechat) self.exit_button = QPushButton("退出登陆") self.exit_button.clicked.connect(self.logOut) self.exit_button.setEnabled(False) # 将按钮添加到窗口部件中 login_buttons_box.addWidget(self.refresh_button) login_buttons_box.addWidget(self.exit_button) # 创建一个登录按钮的组盒子 login_box = QGroupBox() login_box.setTitle("登陆选项") # 设置登陆盒子布局为网格布局 login_box_layout = QGridLayout() login_box.setLayout(login_box_layout) # 将按钮窗口部件添加到网格布局中 login_box_layout.addWidget(login_buttons,0,1) # 创建群聊列表子盒子 chatroom_box = QGroupBox() chatroom_box.setTitle("群聊列表") # 创建群聊列表的垂直布局层 chatroom_box_layout = QVBoxLayout() # 设置群聊列表子盒子的布局层 chatroom_box.setLayout(chatroom_box_layout) # 创建一个群聊部件 scroll_widget = QWidget() # 创建群聊不见的布局层 self.scroll_widget_layout = QVBoxLayout() # 设置群聊不见的布局层为self.scroll_widget_layout scroll_widget.setLayout(self.scroll_widget_layout) # 创建一个可滚动区域 scroll = QScrollArea() # 在可滚动区域中设置窗口部件为scroll_widget scroll.setWidget(scroll_widget) scroll.setAutoFillBackground(True) scroll.setWidgetResizable(True) # 在群里盒子布局中添加可滚动区域 chatroom_box_layout.addWidget(scroll) # 创建文件及Token子盒子 settings_box = QGroupBox() settings_box.setTitle("配置信息") settings_box_layout = QGridLayout() settings_box.setLayout(settings_box_layout) # 创建输入框 key_name = QLabel("AppKey:") sec_name = QLabel("Secret:") adzone_name = QLabel("Adzone_id:") self.appkey = QLineEdit() self.secret = QLineEdit() self.adzone_id = QLineEdit() file_name = QLabel("优惠券文件路径:") self.coupon_file = QLineEdit() choose_file = QPushButton("选择文件") choose_file.clicked.connect(self.choose_coupon_file) # 添加输入框到settings_box_layout中 settings_box_layout.addWidget(key_name,0,0) settings_box_layout.addWidget(self.appkey,0,1) settings_box_layout.addWidget(sec_name,1,0) settings_box_layout.addWidget(self.secret,1,1) settings_box_layout.addWidget(adzone_name,2,0) settings_box_layout.addWidget(self.adzone_id,2,1) settings_box_layout.addWidget(file_name,3,0) settings_box_layout.addWidget(self.coupon_file,3,1) settings_box_layout.addWidget(choose_file,4,0) # 创建控制按钮盒子 control_box = QGroupBox() control_box.setTitle("控制开关") control_box_layout = QVBoxLayout() control_box.setLayout(control_box_layout) # 创建控制按钮 self.start_run = QPushButton("开启机器人") self.start_run.clicked.connect(self.start_bot) self.end_run = QPushButton("停止机器人") self.end_run.setEnabled(False) self.check_info = QPushButton("检查配置信息") self.check_info.clicked.connect(self.get_check_info) # 将控制按钮添加到控制按钮盒子中 control_box_layout.addWidget(self.start_run,0) # control_box_layout.addWidget(self.end_run,1) control_box_layout.addWidget(self.check_info,2) # 选项盒子 select_box = QGroupBox() select_box.setTitle("功能选项") # 选项盒子布局 select_box_layout = QGridLayout() select_box.setLayout(select_box_layout) # 将群聊列表盒子、配置信息盒子和控制按钮盒子添加到选项盒子中 select_box_layout.addWidget(chatroom_box,0,0) select_box_layout.addWidget(settings_box,0,1) select_box_layout.addWidget(control_box,0,2) # 窗口主部件中上层功能按钮的布局 utils_box = QGridLayout() # 添加登录盒子和选项盒子到上层布局中 utils_box.addWidget(login_box,0,0) utils_box.addWidget(select_box,0,1) ''' 下层控制台盒子 ''' # 创建一个文本框 self.label_1 = QTextEdit() # 设置文本框为只读 self.label_1.setReadOnly(True) # 窗口主部件中下层控制台的布局 console_box = QVBoxLayout() console_box.addWidget(self.label_1) ''' 主窗体的布局 ''' # 窗口主部件 self.Widget = QWidget() # 设置窗口主部件的布局层 widget_box = QVBoxLayout() self.Widget.setLayout(widget_box) # 在窗口主部件的布局层中添加功能按钮层和控制台层 widget_box.addLayout(utils_box) widget_box.addLayout(console_box) '''页面初始化层''' self.setCentralWidget(self.Widget) ''' 功能函数 ''' # 退出登陆 def logOut(self): # 设置登录按钮为激活状态 self.refresh_button.setEnabled(True) # 在文本控制台中输入 self.outputWritten("退出微信登录\n") # 注销微信登录 itchat.logout() # 设置注销按钮为禁用状态 self.exit_button.setEnabled(False) # 选择优惠券文件 def choose_coupon_file(self): try: choose = QFileDialog.getOpenFileName(self,'选择文件','','Excel files(*.xls)') print(choose) if choose: self.coupon_file.setText(choose[0]) except Exception as e: self.outputWritten('{}\n'.format(e)) # 在控制台中写入信息 def outputWritten(self, text=None): # 获取文本框中文本的游标 cursor = self.label_1.textCursor() # 将游标位置移动到当前文本的结束处 cursor.movePosition(QtGui.QTextCursor.End) # 写入文本 cursor.insertText(text) # 设置文本的游标为创建了cursor self.label_1.setTextCursor(cursor) self.label_1.ensureCursorVisible() # 获取输入及选择的参数 def get_check_info(self): try: self.outputWritten("选择的群聊为:{}\n".format(self.chatroom_list)) self.outputWritten("输入的AppKey为:{}\n".format(self.appkey.text())) self.outputWritten("输入的sercet为:{}\n".format(self.secret.text())) self.outputWritten("输入的adzone_id为:{}\n".format(self.adzone_id.text())) self.outputWritten("选择的优惠券文件为:{}\n".format(self.coupon_file.text())) self.outputWritten("++++++++++++++++++++++++++++++++++++++++++++++++++++++\n") except Exception as e: print(e) ''' ItChat登陆功能 ''' @staticmethod def _show_message(message): print('{}'.format(message)) # 生成群聊列表 def generate_chatroom(self,chatrooms): # 清空原有群里列表 while self.scroll_widget_layout.count(): item = self.scroll_widget_layout.takeAt(0) widget = item.widget() widget.deleteLater() # 获取群里字典 chatrooms = chatrooms self.chatroom_dict = dict() try: for c,i in zip(chatrooms, range(len(chatrooms))): print(c['NickName'],c['UserName']) checkbox = QCheckBox(c['NickName']) checkbox.id_ = i self.chatroom_dict[c['NickName']] = c['UserName'] checkbox.stateChanged.connect(self.checkChatRoom) # 1 self.scroll_widget_layout.addWidget(checkbox) self.outputWritten("生成群聊成功!\n") except Exception as e: print(e) # 获取群聊复选框选择状态 def checkChatRoom(self, state): try: checkBox = self.sender() if state == Qt.Unchecked: self.outputWritten(u'取消选择了{0}: {1}\n'.format(checkBox.id_, checkBox.text())) self.chatroom_list.remove(self.chatroom_dict[checkBox.text()]) elif state == Qt.Checked: self.outputWritten(u'选择了{0}: {1}\n'.format(checkBox.id_, checkBox.text())) self.chatroom_list.append(self.chatroom_dict[checkBox.text()]) except Exception as e: self.outputWritten("获取群聊选择状态失败:{}\n".format(e)) # 登录微信 - 线程 def login_wechat(self): try: self.login_wechat_thread = LoginWechat( label=self.label_1, scroll_widget_layout=self.scroll_widget_layout, refresh_button=self.refresh_button, exit_button=self.exit_button, ) self.login_wechat_thread.finished_signal.connect(self.generate_chatroom) self.login_wechat_thread.start() except Exception as e: print("执行登录线程出错:",e) self.outputWritten("执行登录线程出错:{}\n".format(e)) # 启动自动回复和主动发送消息 - 线程 def start_bot(self): try: self.outputWritten("开始自动回复……\n") self.start_boot_thread = StartBot( appkey=self.appkey, secret=self.secret, adzone_id=self.adzone_id, label=self.label_1, start_button=self.start_run, end_button=self.end_run, chatrooms=self.chatroom_list ) self.auto_send_coupon_tread = AutoSend( appkey=self.appkey, secret=self.secret, adzone_id=self.adzone_id, label=self.label_1, start_button=self.start_run, end_button=self.end_run, chatrooms=self.chatroom_list ) self.start_boot_thread.finished_signal.connect(self._show_message) self.auto_send_coupon_tread.finished_signal.connect(self._show_message) self.start_boot_thread.start() self.auto_send_coupon_tread.start() except Exception as e: self.outputWritten('{}\n'.format(e)) # 启动自动回复 class StartBot(QThread): finished_signal = pyqtSignal(str) # 接受一些按钮和文本信息作为参数 def __init__(self,parent=None,appkey=None,secret=None,adzone_id=None,label=None,start_button=None,end_button=None,chatrooms=None): super().__init__(parent) self.appkey = appkey self.secret = secret self.adzone_id = adzone_id self.l = label self.start_button = start_button self.end_button = end_button self.chatrooms = chatrooms # 在控制台中写入信息 def outputWritten(self, text=None): cursor = self.l.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.insertText(text) self.l.setTextCursor(cursor) self.l.ensureCursorVisible() # 通过淘宝客API搜索优惠券 def get_tk_coupon(self,kw,size=5): req = top.api.TbkDgItemCouponGetRequest() req.set_app_info(top.appinfo(self.appkey.text(), self.secret.text())) req.adzone_id = int(self.adzone_id.text()) req.platform = 2 # req.cat = "16,18" req.page_size = size req.q = kw req.page_no = 1 try: resp = req.getResponse()['tbk_dg_item_coupon_get_response']['results']['tbk_coupon'] return resp except Exception as e: self.outputWritten(str(e)) # 通过类目返回优惠券 def get_cat_coupon(self,cate_id): req = top.api.TbkDgItemCouponGetRequest() req.set_app_info(top.appinfo(self.appkey.text(), self.secret.text())) req.adzone_id = int(self.adzone_id.text()) req.platform = 2 req.cat = cate_id req.page_size = 10 req.page_no = 1 try: resp = req.getResponse()['tbk_dg_item_coupon_get_response']['results']['tbk_coupon'] return resp except Exception as e: self.outputWritten(str(e)) # 获取淘口令 def get_token(self,url, text): req = top.api.TbkTpwdCreateRequest() req.set_app_info(top.appinfo(self.appkey.text(), self.secret.text())) req.text = text req.url = url try: resp = req.getResponse()['tbk_tpwd_create_response']['data']['model'] return resp except Exception as e: print(e) return None def run(self): self.start_button.setEnabled(False) self.end_button.setEnabled(True) # 回复群聊搜索 @itchat.msg_register(TEXT, isGroupChat=True) def text_reply(msg): if msg['isAt'] and msg['FromUserName'] in self.chatrooms: searchword = msg['Content'][9:] self.outputWritten('消息来自于:{0},内容为:{1}\n'.format(msg['ActualNickName'], msg['Content'])) response = self.get_tk_coupon(searchword) for r in response: # 商品标题 ordername = r['title'] # 商品当前价 orderprice = r['zk_final_price'] coupon_info = r['coupon_info'] coupon_demonination = int(re.findall(r'(\d+)', coupon_info)[-1]) # 商品图片 orderimg = r['pict_url'] # 获取淘口令 token = self.get_token(url=r['coupon_click_url'], text=r['title']) # 券后价 couponprice = round(float(orderprice) - int(coupon_demonination), 1) # 生成短链 link = r['item_url'] link_resp = requests.get( 'http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=' + link).text link_short = json.loads(link_resp, encoding='utf-8')['urls'][0]['url_short'] msgs = '''/:gift{name}\n/:rose【在售价】{orderprice}元\n/:heart【券后价】{conponprice}元\n/:cake 【抢购链接】{link_short}\n-----------------\n复制这条信息\n{token}打开【手机淘宝】,即可查看\n------------------\n '''.format(name=ordername, orderprice=orderprice, conponprice=couponprice, token=token, link_short=link_short) itchat.send(msg=str(msgs), toUserName=msg['FromUserName']) try: image = urlretrieve(url=orderimg, filename=r'%s' % os.path.join(current_path, 'orderimg.jpg')) itchat.send_image(fileDir=r'%s' % os.path.join(current_path, 'orderimg.jpg'), toUserName=msg['FromUserName']) except Exception as e: self.outputWritten("发送图片失败,{}\n".format(e)) time.sleep(3) itchat.run() # 定时自动发送消息 class AutoSend(QThread): finished_signal = pyqtSignal(str) def __init__(self,parent=None,appkey=None,secret=None,adzone_id=None,label=None,start_button=None,end_button=None,chatrooms=None): super().__init__(parent) self.appkey = appkey self.secret = secret self.adzone_id = adzone_id self.l = label self.start_button = start_button self.end_button = end_button self.chatrooms = chatrooms # 在控制台中写入信息 def outputWritten(self, text=None): cursor = self.l.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.insertText(text) self.l.setTextCursor(cursor) self.l.ensureCursorVisible() # 通过淘宝客API搜索优惠券 def get_tk_coupon(self,kw,size=5): req = top.api.TbkDgItemCouponGetRequest() req.set_app_info(top.appinfo(self.appkey.text(), self.secret.text())) req.adzone_id = int(self.adzone_id.text()) req.platform = 2 # req.cat = "16,18" req.page_size = size req.q = kw req.page_no = 1 try: resp = req.getResponse()['tbk_dg_item_coupon_get_response']['results']['tbk_coupon'] return resp except Exception as e: self.outputWritten(str(e)) # 获取淘口令 def get_token(self,url, text): req = top.api.TbkTpwdCreateRequest() req.set_app_info(top.appinfo(self.appkey.text(), self.secret.text())) req.text = text req.url = url try: resp = req.getResponse()['tbk_tpwd_create_response']['data']['model'] return resp except Exception as e: print(e) return None # 定时自动发送优惠券消息 def send_coupon(self): while True: # 获取选择的群聊列表 for c in self.chatrooms: # 每天早上8点定时推送商品优惠券 if datetime.datetime.today().hour == 8: print('现在时间:', datetime.datetime.today()) try: response = self.get_tk_coupon(kw='精选',size=3) for r in response: # 商品标题 ordername = r['title'] # 商品当前价 orderprice = r['zk_final_price'] coupon_info = r['coupon_info'] coupon_demonination = int(re.findall(r'(\d+)', coupon_info)[-1]) # 商品图片 orderimg = r['pict_url'] # 获取淘口令 token = self.get_token(url=r['coupon_click_url'], text=r['title']) # 券后价 couponprice = round(float(orderprice) - int(coupon_demonination), 1) # 生成短链 link = r['item_url'] link_resp = requests.get( 'http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=' + link).text link_short = json.loads(link_resp, encoding='utf-8')['urls'][0]['url_short'] msgs = '''【清晨特惠精选】\n/:gift{name}\n/:rose【在售价】{orderprice}元\n/:heart【券后价】{conponprice}元\n/:cake 【抢购链接】{link_short}\n-----------------\n复制这条信息\n{token}打开【手机淘宝】,即可查看 '''.format(name=ordername, orderprice=orderprice, conponprice=couponprice, token=token, link_short=link_short) itchat.send(msg=str(msgs), toUserName=c) try: image = urlretrieve(url=orderimg, filename=r'%s' % os.path.join(current_path, 'orderimg.jpg')) itchat.send_image(fileDir=r'%s' % os.path.join(current_path, 'orderimg.jpg'), toUserName=c) except Exception as e: self.outputWritten("发送图片失败,{}\n".format(e)) time.sleep(3) except Exception as e: self.outputWritten("发送失败:{}\n".format(e)) # 晚上六点定时发送使用说明消息 elif datetime.datetime.today().hour == 20: itchat.send(msg="【优惠券搜索使用说明】\n,@我+搜索名称,即可收到5条精选天猫淘宝商品内部优惠券\n", toUserName=c) time.sleep(3600) def run(self): try: self.send_coupon() except Exception as e: self.outputWritten("定时发送消息出错:{}\n".format(e)) print(traceback.print_exc()) # 登陆微信 class LoginWechat(QThread): # 自定义一个信号 finished_signal = pyqtSignal(object) def __init__(self,parent=None,label=None,scroll_widget_layout=None,refresh_button=None,exit_button=None): super().__init__(parent) self.l = label self.scroll_widget_layout = scroll_widget_layout self.refresh_button = refresh_button self.exit_button = exit_button # 在控制台中写入信息 def outputWritten(self, text=None): cursor = self.l.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.insertText(text) self.l.setTextCursor(cursor) self.l.ensureCursorVisible() # 获取uuid def open_qr(self): for get_count in range(1): self.outputWritten('获取uuid中……\n') uuid = itchat.get_QRuuid() while uuid is None: uuid = itchat.get_QRuuid() time.sleep(1) self.outputWritten('成功获取uuid\n') if itchat.get_QR(uuid,picDir=r'%s'%os.path.join(current_path,'qrcode.jpg')): break elif get_count >= 1: self.outputWritten("获取二维码出错,请重启程序\n") sys.exit() return uuid # 二维码登陆 def login_wechat(self): try: uuid = self.open_qr() self.outputWritten("请扫描二维码\n") waitForConfirm = False while 1: status = itchat.check_login(uuid) if status == '200': break elif status == '201': if waitForConfirm: self.outputWritten('请进行确认\n') waitForConfirm = True elif status == '408': self.outputWritten('重新加载二维码\n') time.sleep(3) uuid = self.open_qr() waitForConfirm = False userInfo = itchat.web_init() itchat.show_mobile_login() itchat.get_friends(True) self.outputWritten('登陆成功!账号为:%s\n' % userInfo['User']['NickName']) itchat.start_receiving() self.refresh_button.setText("已登录:{}".format(userInfo['User']['NickName'])) self.exit_button.setEnabled(True) except Exception as e: print("登录出错:",e) self.outputWritten('登陆出错:{}\n'.format(e)) try: # 获取群聊列表 chatrooms = itchat.get_chatrooms() print(type(chatrooms)) return chatrooms except Exception as e: self.outputWritten("获取群聊列表出错:{}\n".format(e)) def run(self): try: self.refresh_button.setEnabled(False) self.exit_button.setEnabled(True) self.finished_signal.emit(self.login_wechat()) except Exception as e: self.outputWritten("运行登录线程出错:{}\n".format(e)) if __name__ == '__main__': app = QApplication(sys.argv) gui = MainGUI() gui.show() sys.exit(app.exec_())
Python
" Vim syntax file " Language: sqlj " Maintainer: Andreas Fischbach <[email protected]> " This file is based on sql.vim && java.vim (thanx) " with a handful of additional sql words and still " a subset of whatever standard " Last change: 31th Dec 2001 " au BufNewFile,BufRead *.sqlj so $VIM/syntax/sqlj.vim " quit when a syntax file was already loaded if exists("b:current_syntax") finish endif " Read the Java syntax to start with source <sfile>:p:h/java.vim " SQLJ extensions " The SQL reserved words, defined as keywords. syn case ignore syn keyword sqljSpecial null syn keyword sqljKeyword access add as asc by check cluster column syn keyword sqljKeyword compress connect current decimal default syn keyword sqljKeyword desc else exclusive file for from group syn keyword sqljKeyword having identified immediate increment index syn keyword sqljKeyword initial into is level maxextents mode modify syn keyword sqljKeyword nocompress nowait of offline on online start syn keyword sqljKeyword successful synonym table then to trigger uid syn keyword sqljKeyword unique user validate values view whenever syn keyword sqljKeyword where with option order pctfree privileges syn keyword sqljKeyword public resource row rowlabel rownum rows syn keyword sqljKeyword session share size smallint syn keyword sqljKeyword fetch database context iterator field join syn keyword sqljKeyword foreign outer inner isolation left right syn keyword sqljKeyword match primary key syn keyword sqljOperator not and or syn keyword sqljOperator in any some all between exists syn keyword sqljOperator like escape syn keyword sqljOperator union intersect minus syn keyword sqljOperator prior distinct syn keyword sqljOperator sysdate syn keyword sqljOperator max min avg sum count hex syn keyword sqljStatement alter analyze audit comment commit create syn keyword sqljStatement delete drop explain grant insert lock noaudit syn keyword sqljStatement rename revoke rollback savepoint select set syn keyword sqljStatement truncate update begin work syn keyword sqljType char character date long raw mlslabel number syn keyword sqljType rowid varchar varchar2 float integer syn keyword sqljType byte text serial " Strings and characters: syn region sqljString start=+"+ skip=+\\\\\|\\"+ end=+"+ syn region sqljString start=+'+ skip=+\\\\\|\\"+ end=+'+ " Numbers: syn match sqljNumber "-\=\<\d*\.\=[0-9_]\>" " PreProc syn match sqljPre "#sql" " Comments: syn region sqljComment start="/\*" end="\*/" syn match sqlComment "--.*" syn sync ccomment sqljComment " The default methods for highlighting. Can be overridden later. hi def link sqljComment Comment hi def link sqljKeyword sqljSpecial hi def link sqljNumber Number hi def link sqljOperator sqljStatement hi def link sqljSpecial Special hi def link sqljStatement Statement hi def link sqljString String hi def link sqljType Type hi def link sqljPre PreProc let b:current_syntax = "sqlj"
Vim Script
// // SBGetUnitList.m // SimplyBookMobile // // Created by Michail Grebionkin on 29.07.15. // Copyright (c) 2015 Capitan. All rights reserved. // #import "SBGetUnitListRequest.h" #import "SBRequestOperation_Private.h" #import "SBPerformer.h" @interface SBGetUnitListResultProcessor : SBResultProcessor @end @implementation SBGetUnitListRequest - (void)initializeWithToken:(NSString *)token comanyLogin:(NSString *)companyLogin endpoint:(NSString *)endpoint { [super initializeWithToken:token comanyLogin:companyLogin endpoint:endpoint]; self.visibleOnly = NO; self.asArray = YES; } - (NSString *)method { return @"getUnitList"; } - (NSArray *)params { return @[@(self.visibleOnly), @(self.asArray)]; } - (SBResultProcessor *)resultProcessor { return [[SBClassCheckProcessor classCheckProcessorWithExpectedClass:[NSArray class]] addResultProcessorToChain:[SBGetUnitListResultProcessor new]]; } @end @implementation SBGetUnitListResultProcessor - (BOOL)process:(id)result { self.result = [[SBPerformersCollection alloc] initWithArray:result builder:[SBPerformerEntryBuilder new]]; return [super process:self.result]; } @end
Objective-C
<?php declare(strict_types = 1); /** * Jyxo PHP Library * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file license.txt. * It is also available through the world-wide-web at this URL: * https://github.com/jyxo/php/blob/master/license.txt */ namespace Jyxo\Beholder\TestCase; use Jyxo\Beholder\Result; use PHPUnit\Framework\TestCase; use function class_exists; use function explode; use function gethostbyaddr; use function sprintf; /** * Tests the \Jyxo\Beholder\TestCase\Memcached class. * * @see \Jyxo\Beholder\TestCase\Memcached * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o. * @license https://github.com/jyxo/php/blob/master/license.txt * @author Jaroslav Hanslík */ class MemcachedTest extends TestCase { /** * Tests connection failure. */ public function testConnectionFailure(): void { if (!class_exists('Memcached')) { $this->markTestSkipped('Memcached not set'); } $ip = '127.0.0.1'; $port = '12345'; $test = new Memcached('Memcached', $ip, $port); // @ on purpose $result = @$test->run(); $this->assertEquals(Result::FAILURE, $result->getStatus()); $this->assertEquals(sprintf('Connection error %s:%s', gethostbyaddr($ip), $port), $result->getDescription()); } /** * Tests working connection. */ public function testAllOk(): void { // Skip the test if no memcache connection is defined if (empty($GLOBALS['memcache'])) { $this->markTestSkipped('Memcached not set'); } $servers = explode(',', $GLOBALS['memcache']); [$ip, $port] = explode(':', $servers[0]); $test = new Memcached('Memcached', $ip, $port); $result = $test->run(); $this->assertEquals(Result::SUCCESS, $result->getStatus()); $this->assertEquals(sprintf('%s:%s', gethostbyaddr($ip), $port), $result->getDescription()); } protected function setUp(): void { if (!class_exists('Memcached')) { $this->markTestSkipped('Memcached not set'); } } }
PHP
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- [assembly: PartId(PartId.Workers)] namespace Z0.Parts { public sealed partial class Workers : Part<Workers> { } } namespace Z0 { using System; using static Root; [ApiHost] public static partial class XTend { const NumericKind Closure = UnsignedInts; } [ApiComplete] partial struct Msg { } }
C#
/* * (C) Copyright 2020 Radix DLT Ltd * * Radix DLT Ltd licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ package com.radixdlt.consensus.bft; import com.radixdlt.consensus.BFTHeader; import com.radixdlt.consensus.Command; import com.radixdlt.consensus.QuorumCertificate; import com.radixdlt.consensus.UnverifiedVertex; import com.radixdlt.crypto.Hash; import java.util.Objects; /** * A vertex which has been verified with hash id */ public final class VerifiedVertex { private final UnverifiedVertex vertex; private final Hash id; public VerifiedVertex(UnverifiedVertex vertex, Hash id) { this.vertex = Objects.requireNonNull(vertex); this.id = Objects.requireNonNull(id); } public UnverifiedVertex toSerializable() { return vertex; } public Command getCommand() { return vertex.getCommand(); } public boolean touchesGenesis() { return this.getView().isGenesis() || this.getParentHeader().getView().isGenesis() || this.getGrandParentHeader().getView().isGenesis(); } public boolean hasDirectParent() { return this.vertex.getView().equals(this.getParentHeader().getView().next()); } public boolean parentHasDirectParent() { return this.getParentHeader().getView().equals(this.getGrandParentHeader().getView().next()); } public BFTHeader getParentHeader() { return vertex.getQC().getProposed(); } public BFTHeader getGrandParentHeader() { return vertex.getQC().getParent(); } public View getView() { return vertex.getView(); } public QuorumCertificate getQC() { return vertex.getQC(); } public Hash getId() { return id; } public Hash getParentId() { return vertex.getQC().getProposed().getVertexId(); } @Override public String toString() { return String.format("%s{view=%s id=%s}", this.getClass().getSimpleName(), this.vertex.getView(), this.id); } }
Java
//DEPRECATED if (false) { if (localStorage.getItem(LOCAL_STORAGE_TAG + "2x-mode") === "true") { localStorage.setItem(LOCAL_STORAGE_TAG + "2x-mode", "false") alert("2X mode disabled") } else { localStorage.setItem(LOCAL_STORAGE_TAG + "2x-mode", "true") alert("2X mode enabled") } window.location.replace("./dashboard") }
JavaScript
package daggerok; import io.vavr.Tuple; import io.vavr.collection.HashMap; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import java.util.Map; import java.util.function.Function; @SpringBootApplication public class App { @Bean Function<Map<String, String>, Map<String, String>> routes() { return map -> HashMap.ofAll(map) .map((s, s2) -> Tuple.of(s, s2.toUpperCase())) .toJavaMap(); } public static void main(String[] args) { SpringApplication.run(App.class, args); } }
Java
package containers; import net.mindview.util.Countries; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Created by IntelliJ IDEA. * User: deko * Date: 1/21/12 * Time: 1:31 AM * To change this template use File | Settings | File Templates. */ public class Exercise1 { public static void main(String[] args){ List<String> countries = new ArrayList<String>(Countries.names()); Collections.sort(countries); System.out.println(countries); List<String> countries2 = new LinkedList<String>(Countries.names()); Collections.sort(countries2); System.out.println(countries2); for(int i=0; i < 3; i++){ Collections.shuffle(countries); Collections.shuffle(countries2); System.out.println("First: " + countries); System.out.println("Second: " + countries2); } } }
Java
#!/usr/bin/env python3 """ Used for doing misc testing """ # rubiks cube libraries from rubikscubennnsolver import RubiksCube, configure_logging from rubikscubennnsolver.RubiksCubeNNNOdd import solved_171717 configure_logging() cube = RubiksCube(solved_171717, "URFDLB") cube.randomize(count=2000) cube.print_cube("playground") print((cube.get_kociemba_string(True)))
Python
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ /* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.idgen.namescope; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.TableGenerator; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.hibernate.testing.transaction.TransactionUtil.doInHibernate; import static org.junit.Assert.assertThat; /** * @author Andrea Boriero */ public class IdGeneratorNamesLocalScopeTest extends BaseCoreFunctionalTestCase { @Override protected Class<?>[] getAnnotatedClasses() { return new Class[] { FirstEntity.class, SecondEntity.class }; } @Test public void testNoSequenceGenratorNameClash() { final FirstEntity first = new FirstEntity(); final SecondEntity second = new SecondEntity(); doInHibernate( this::sessionFactory, session -> { session.persist( first ); session.persist( second ); } ); assertThat( first.getId(), is( 2L ) ); assertThat( second.getId(), is( 11L ) ); } @Entity(name = "FirstEntity") @TableGenerator( name = "table-generator", table = "table_identifier_2", pkColumnName = "identifier", valueColumnName = "value", allocationSize = 5, initialValue = 1 ) public static class FirstEntity { @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "table-generator") private Long id; public Long getId() { return id; } } @Entity(name = "SecondEntity") @TableGenerator( name = "table-generator", table = "table_identifier", pkColumnName = "identifier", valueColumnName = "value", allocationSize = 5, initialValue = 10 ) public static class SecondEntity { @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "table-generator") private Long id; public Long getId() { return id; } } }
Java
namespace RingCentral { public partial class SubscriptionInfo { // Internal identifier of a subscription public string @id { get; set; } // Canonical URI of a subscription public string @uri { get; set; } // Collection of API resources (message-store/presence/detailed presence) corresponding to events the user is subscribed to public string[] @eventFilters { get; set; } // Collection of API resources (message-store/presence/detailed presence) corresponding to events the user is not subscribed to due to certain limitations public DisabledFilterInfo[] @disabledFilters { get; set; } // Subscription expiration datetime in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format including timezone, for example 2016-03-10T18:07:52.534Z public string @expirationTime { get; set; } // Subscription lifetime in seconds public long? @expiresIn { get; set; } // Subscription status public string @status { get; set; } // Subscription creation datetime in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format including timezone, for example 2016-03-10T18:07:52.534Z public string @creationTime { get; set; } // Delivery mode data public NotificationDeliveryMode @deliveryMode { get; set; } // public NotificationBlacklistedData @blacklistedData { get; set; } } }
C#
const newQuote = document.querySelector('#new-quote'); const quote = document.querySelector('#text'); const author = document.querySelector('#author'); let quoteObject; //add quote when page loads window.onload = getQuote; // //change quote when button is clicked // setTimeout('getQuote()', 5000); //function to get and assign quote and author function getQuote() { // //fetch the data // fetch('http://quotable.io/random') // .then((res) => res.json()) //response type // .then((data) => { // quoteObject = data; // assign data to quoteObject //display quote quote.innerHTML = quoteObject.content; //display author author.innerHTML = quoteObject.author; // }); //change quote when button is clicked setTimeout('getQuote()', 5000); }
JavaScript
/* * @lc app=leetcode id=489 lang=java * * [489] Robot Room Cleaner * * https://leetcode.com/problems/robot-room-cleaner/description/ * * algorithms * Hard (71.82%) * Total Accepted: 66.1K * Total Submissions: 92K * Testcase Example: '[[1,1,1,1,1,0,1,1],[1,1,1,1,1,0,1,1],[1,0,1,1,1,1,1,1],[0,0,0,1,0,0,0,0],[1,1,1,1,1,1,1,1]]\n' + '1\n' + '3' * * Given a robot cleaner in a room modeled as a grid. * * Each cell in the grid can be empty or blocked. * * The robot cleaner with 4 given APIs can move forward, turn left or turn * right. Each turn it made is 90 degrees. * * When it tries to move into a blocked cell, its bumper sensor detects the * obstacle and it stays on the current cell. * * Design an algorithm to clean the entire room using only the 4 given APIs * shown below. * * * interface Robot { * // returns true if next cell is open and robot moves into the cell. * // returns false if next cell is obstacle and robot stays on the current * cell. * boolean move(); * * ⁠ // Robot will stay on the same cell after calling turnLeft/turnRight. * // Each turn will be 90 degrees. * void turnLeft(); * void turnRight(); * * ⁠ // Clean the current cell. * ⁠ void clean(); * } * * * Example: * * * Input: * room = [ * ⁠ [1,1,1,1,1,0,1,1], * ⁠ [1,1,1,1,1,0,1,1], * ⁠ [1,0,1,1,1,1,1,1], * ⁠ [0,0,0,1,0,0,0,0], * ⁠ [1,1,1,1,1,1,1,1] * ], * row = 1, * col = 3 * * Explanation: * All grids in the room are marked by either 0 or 1. * 0 means the cell is blocked, while 1 means the cell is accessible. * The robot initially starts at the position of row=1, col=3. * From the top left corner, its position is one row below and three columns * right. * * * Notes: * * * The input is only given to initialize the room and the robot's position * internally. You must solve this problem "blindfolded". In other words, you * must control the robot using only the mentioned 4 APIs, without knowing the * room layout and the initial robot's position. * The robot's initial position will always be in an accessible cell. * The initial direction of the robot will be facing up. * All accessible cells are connected, which means the all cells marked as 1 * will be accessible by the robot. * Assume all four edges of the grid are all surrounded by wall. * * */ /** * // This is the robot's control interface. * // You should not implement it, or speculate about its implementation * interface Robot { * // Returns true if the cell in front is open and robot moves into the cell. * // Returns false if the cell in front is blocked and robot stays in the current cell. * public boolean move(); * * // Robot will stay in the same cell after calling turnLeft/turnRight. * // Each turn will be 90 degrees. * public void turnLeft(); * public void turnRight(); * * // Clean the current cell. * public void clean(); * } */ class Solution { Set<String> set = new HashSet<>(); int[][] dir = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} }; public void cleanRoom(Robot robot) { clean(robot, 0, 0, 0); } void clean(Robot rob, int x, int y, int d) { String str = String.format("%d.%d", x, y); set.add(str); rob.clean(); for (int t = 0; t < 4; t++) { int nd = (d+t)%4; int nx = dir[nd][0]+x; int ny = dir[nd][1]+y; String ns = String.format("%d.%d", nx, ny); if (!set.contains(ns) && rob.move()) { clean(rob, nx, ny, nd); rob.turnRight(); rob.turnRight(); rob.move(); rob.turnRight(); rob.turnRight(); } rob.turnRight(); } } }
Java
"""Supervisr DNS Migration views""" from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import redirect, reverse from django.utils.translation import ugettext as _ from supervisr.core.models import (Domain, ProviderInstance, UserAcquirableRelationship) from supervisr.core.providers.base import get_providers from supervisr.core.views.wizards import BaseWizardView from supervisr.dns.forms.migrate import ZoneImportForm, ZoneImportPreviewForm from supervisr.dns.forms.zones import ZoneForm from supervisr.dns.models import Zone from supervisr.dns.utils import import_bind TEMPLATES = { '0': 'generic/wizard.html', '1': 'generic/wizard.html', '2': 'dns/migrate/preview.html', } # pylint: disable=too-many-ancestors class BindZoneImportWizard(LoginRequiredMixin, BaseWizardView): """Import DNS records from bind zone""" title = _('Import Bind Zone') form_list = [ZoneForm, ZoneImportForm, ZoneImportPreviewForm] def get_form(self, step=None, data=None, files=None): form = super(BindZoneImportWizard, self).get_form(step, data, files) if step is None: step = self.steps.current if step == '0': # This step should be seperated into the DomainNewWizard, which should run before this domains = Zone.objects.filter(users__in=[self.request.user]) unused_domains = Domain.objects.filter(users__in=[self.request.user]) \ .exclude(pk__in=domains.values_list('domain', flat=True)) providers = get_providers(capabilities=['dns'], path=True) provider_instance = ProviderInstance.objects.filter( provider_path__in=providers, useracquirablerelationship__user__in=[self.request.user]) form.fields['domain'].queryset = unused_domains form.fields['providers'].queryset = provider_instance elif step == '2': if '1-zone_data' in self.request.POST: form.records = import_bind(self.request.POST['1-zone_data']) return form def get_template_names(self): return [TEMPLATES[self.steps.current]] def finish(self, zone_form, zone_data_form, accept_form): if accept_form.cleaned_data.get('accept'): records = import_bind(zone_data_form.cleaned_data.get('zone_data'), root_zone=zone_form.cleaned_data.get('domain').domain) m_dom = Zone.objects.create( name=zone_form.cleaned_data.get('domain'), domain=zone_form.cleaned_data.get('domain'), provider=zone_form.cleaned_data.get('provider'), enabled=zone_form.cleaned_data.get('enabled')) UserAcquirableRelationship.objects.create( model=m_dom, user=self.request.user) for rec in records: rec.domain = m_dom rec.save() UserAcquirableRelationship.objects.create( model=rec, user=self.request.user) messages.success(self.request, _('DNS domain successfully created and ' '%(count)d records imported.' % { 'count': len(records)})) return redirect(reverse('supervisr_dns:dns-record-list', kwargs={'uuid': m_dom.uuid})) messages.error(self.request, _('Created nothing')) return redirect(reverse('supervisr_dns:index'))
Python
/** * @param.username * @param.password */ const request = require('request'); function getSt(swc, options){ return new Promise(resolve=>{ var option = { url : 'https://weibo.cn/', headers : { 'cookie' : 'SUB=' + options.sub } } request(option, function(err, res, body){ var stSource = body.substring(body.indexOf('/mblog/sendmblog?st=')); var st = stSource.substring(stSource.indexOf('st=') + 3, stSource.indexOf('"')); resolve(st); }) }) } function getCookie(swc, options){ return new Promise(resolve=>{ var option = { url : options.loginResult.data.loginresulturl } request(option, function(err, res, body){ var cookies = res.headers['set-cookie']; var sub; for(var i=0;i<cookies.length;i++){ if(cookies[i].substring(0, 3) === 'SUB'){ sub = cookies[i].substring(4, cookies[i].indexOf(';')); break; } } resolve(sub); }) }) } function login(swc, options){ return new Promise(resolve=>{ var body = { username : options.username, password : options.password, } var bodyData = []; for(var i in body){ bodyData.push(`${i}=${body[i]}`); } var option = { url : 'https://passport.weibo.cn/sso/login', form : bodyData.join('&'), headers : { 'referer' : 'https://passport.weibo.cn/signin/login?entry=mweibo&r=https%3A%2F%2Fweibo.cn%2F&backTitle=%CE%A2%B2%A9&vt=', 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36', } } request.post(option, function(err, res, body){ if(err || res.statusCode != 200){ swc.log.error(`${options.username} login failed. retrying`); resolve(undefined); return ; } body = JSON.parse(body); setTimeout(()=>{ resolve(body); }, 500); }) }) } module.exports = async function(swc, options){ while(!options.loginResult || options.loginResult.retcode != '20000000') { options.loginResult = await login(swc, options); } options.sub = await getCookie(swc, options); options.st = await getSt(swc, options); swc.log.info(`Login success -- ${options.username}`); return { username : options.username, sub : options.sub, st : options.st, uid : options.loginResult.data.uid } }
JavaScript
import { Component, OnInit } from '@angular/core'; import { stubTrue } from 'lodash'; import { ExploreService, API, ExploreAPI } from '../explore.service'; import { Router } from '@angular/router'; import { TransferState, makeStateKey } from '@angular/platform-browser'; const STATE_KEY_HOME = makeStateKey('home'); @Component({ selector: 'app-home', templateUrl: './home.component.html', }) export class HomeComponent implements OnInit { constructor( public exp: ExploreService, private router: Router, private state: TransferState, ) {} search: string; services: ExploreAPI[]; results: ExploreAPI[]; timeout: any = null; loading = false; ngOnInit() { let services: ExploreAPI[] = this.state.get(STATE_KEY_HOME, <any>[]); if (services.length == 0) { this.loading = true; this.exp .index(50) .then((ss) => { this.services = ss.filter((s) => ['db', 'function', 'geocoding', 'image', 'sms', 'weather'].includes(s.name)); this.state.set(STATE_KEY_HOME, <any>this.services); }) .finally(() => { this.loading = false; }); } else { this.services = services; } } }
TypeScript
# -*- coding: utf-8 -*- # @Time : 2020/12/23 01:59:33 # @Author : ddvv # @Site : https://ddvvmmzz.github.io # @File : __init__.py # @Software: Visual Studio Code from mmpi import processing signatures = [] # Don't include machinery here as its data structure is different from the # other plugins - of which multiple are in use at any time. plugins = { "processing": processing.plugins, "signatures": signatures, } from mmpi.main import mmpi
Python
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. import * as React from 'react'; import formatMessage from 'format-message'; import { Dropdown, IDropdownOption } from '@fluentui/react/lib/Dropdown'; import { Icon } from '@fluentui/react/lib/Icon'; import { Stack } from '@fluentui/react/lib/Stack'; import { TextField } from '@fluentui/react/lib/TextField'; import { useDebounce } from './useDebounce'; const stackStyles = { root: { marginBottom: '6px', ninWidth: '500px', flex: 'auto', alignSelf: 'stretch' } }; const dropdownStyles = { root: { marginBottom: '6px' }, dropdown: { maxWidth: '300px', width: 'auto' }, }; const itemIconStyles = { marginRight: '8px' }; const newNameTextFileStyles = { root: { marginTop: '10px', maxWidth: '300px' } }; const CREATE_NEW_KEY = 'CREATE_NEW'; const createNewOption: IDropdownOption = { key: CREATE_NEW_KEY, data: { iconName: 'Add' }, text: formatMessage('Create new'), }; type ResourceGroupItemChoice = { name: string; isNew: boolean; errorMessage?: string; }; type Props = { /** * If this picker should be disabled. */ disabled?: boolean; /** * The resource groups to choose from. */ resourceGroupNames?: string[]; /** * The selected name of the existing resource. * When undefined, the 'Create new' option will be selected. */ selectedResourceGroupName?: string; /** * The name chosen for a new resource group. * Used when the 'Create new' option is selected. */ newResourceGroupName?: string; /** * Called when the selection or new resource name changes. */ onChange: (choice: ResourceGroupItemChoice) => void; }; export const ResourceGroupPicker = ({ disabled, resourceGroupNames, selectedResourceGroupName: controlledSelectedName, newResourceGroupName: controlledNewName, onChange, }: Props) => { // ----- Hooks -----// const [selectedName, setSelectedName] = React.useState(controlledSelectedName || CREATE_NEW_KEY); const [isNew, setIsNew] = React.useState((controlledSelectedName || CREATE_NEW_KEY) === CREATE_NEW_KEY); const [newName, setNewName] = React.useState(controlledNewName); const debouncedNewName = useDebounce<string>(newName, 300); const [newNameErrorMessage, setNewNameErrorMessage] = React.useState(''); React.useEffect(() => { setSelectedName(controlledSelectedName || CREATE_NEW_KEY); setIsNew((controlledSelectedName || CREATE_NEW_KEY) === CREATE_NEW_KEY); }, [controlledSelectedName]); React.useEffect(() => { setNewName(controlledNewName || ''); }, [controlledNewName]); React.useEffect(() => { const alreadyExists = resourceGroupNames?.some((name) => name === debouncedNewName); if (debouncedNewName && !debouncedNewName.match(/^[-\w._()]+$/)) { setNewNameErrorMessage( formatMessage( 'Resource group names only allow alphanumeric characters, periods, underscores, hyphens and parenthesis and cannot end in a period.' ) ); } else if (alreadyExists) { setNewNameErrorMessage(formatMessage('A resource with this name already exists.')); } else { setNewNameErrorMessage(undefined); } }, [debouncedNewName, resourceGroupNames]); React.useEffect(() => { if (!disabled) { onChange({ isNew, name: isNew ? debouncedNewName : selectedName, errorMessage: isNew ? newNameErrorMessage : undefined, }); } }, [disabled, selectedName, isNew, debouncedNewName, newNameErrorMessage]); const options = React.useMemo(() => { const optionsList: IDropdownOption[] = resourceGroupNames?.map((p) => { return { key: p, text: p }; }) || []; optionsList.unshift(createNewOption); return optionsList; }, [resourceGroupNames]); // ----- Render -----// const onRenderOption = (option) => { return ( <div> {option.data?.iconName && ( <Icon aria-hidden="true" iconName={option.data.iconName} style={itemIconStyles} title={option.text} /> )} <span>{option.text}</span> </div> ); }; return ( <Stack styles={stackStyles}> <Dropdown disabled={disabled} options={options} placeholder={formatMessage('Select one')} selectedKey={selectedName} styles={dropdownStyles} onChange={(_, opt) => { setIsNew(opt.key === CREATE_NEW_KEY); setSelectedName(opt.key as string); }} onRenderOption={onRenderOption} /> {isNew && ( <TextField data-testid={'newResourceGroupName'} disabled={disabled} errorMessage={newNameErrorMessage} id={'newResourceGroupName'} placeholder={formatMessage('New resource group name')} styles={newNameTextFileStyles} value={newName} onChange={(e, val) => { setNewName(val || ''); }} /> )} </Stack> ); };
TSX
const User = require("../models/User"); class UsersDb { constructor(userObject) { ({ userName: this.userName, email: this.email, password: this.password } = userObject); } findByUserName() { return new Promise((resolve, reject) => { User.findOne({ userName: this.userName }).then(foundUser => { foundUser ? resolve(foundUser) : reject({ user: "No user with that User name" }); }); }); } static findByUserId(id) { //console.trace(this.email); return new Promise((resolve, reject) => { User.findById(id) .populate("preferences.nodes.node", "name") .then(foundUser => resolve(foundUser)) .catch(() => reject({ user: "No user with that ID" })); }); } findByUserNameDelete() { return new Promise((resolve, reject) => { User.findOneAndDelete({ email: this.userName }).then(bool => { bool ? resolve({ success: true }) : reject({ user: "No user with that User name" }); }); }); } createUser(hashedPassword, identicon) { return new Promise((resolve, reject) => { const newUser = new User({ email: this.email, userName: this.userName, identicon, password: hashedPassword }); newUser .save() .then(createdUser => { resolve(createdUser); }) .catch(err => reject(err)); }); } updateUser(hashedPassword, id) { return new Promise((resolve, reject) => { User.findById(id).then(foundUser => { foundUser.email = this.email; hashedPassword && (foundUser.password = hashedPassword); foundUser .save() .then(updatedUser => { resolve(updatedUser); }) .catch(err => reject(err)); }); }); } } module.exports = UsersDb;
JavaScript
<?php /* +--------------------------------------------------------------------------+ | Zephir | | Copyright (c) 2013-present Zephir Team (https://zephir-lang.com/) | | | | This source file is subject the MIT license, that is bundled with this | | package in the file LICENSE, and is available through the world-wide-web | | at the following url: http://zephir-lang.com/license.html | +--------------------------------------------------------------------------+ */ namespace Zephir\Cache; use Zephir\CompilationContext; /** * ClassEntryCache * * Classes located in the PHP userland are cached to avoid further relocates */ class ClassEntryCache { protected $cache = array(); /** * Retrieves/Creates a class entry cache * * @param string $className * @param boolean $dynamic * @param CompilationContext $compilationContext */ public function get($className, $dynamic, CompilationContext $compilationContext) { /** * Creates a guard variable if the class name is not dynamic */ if (!$dynamic) { $zendClassEntry = $compilationContext->symbolTable->addTemp('static_zend_class_entry', $compilationContext); $zendClassEntry->setMustInitNull(true); $compilationContext->backend->fetchClass($zendClassEntry, $className, true, $compilationContext); } else { $zendClassEntry = $compilationContext->symbolTable->addTemp('zend_class_entry', $compilationContext); $compilationContext->backend->fetchClass($zendClassEntry, $className, false, $compilationContext); } return $zendClassEntry; } }
PHP
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerHealthController : MonoBehaviour,IHealthUI { [SerializeField,Range(0,100)] float _health; [SerializeField] bool _immortalMode; [SerializeField] GameObject _particles; // Start is called before the first frame update void Start() { _health = 100; _immortalMode = false; } public void TakeDamage(float damageValue) { if (!_immortalMode) { var newValue = _health - damageValue; _health = Mathf.Clamp(newValue, 0, 100); if (_health <= 0) { Destroy(gameObject); } } } private void OnDestroy() { var effect = Instantiate(_particles, transform.position, transform.rotation); Destroy(effect, 2); } public string GetValue() { return _health.ToString("#."); } public float GetFloatValue() { return _health; } }
C#
<?php require_once('SPIL/Loader.php'); class SPIL_DataMapper_FormUrlEncoded_Test extends PHPUnit_Framework_TestCase { function testInput() { $mapper = new SPIL_DataMapper_FormUrlEncoded(); $actual = $mapper->input('a=b&c=d'); $expected = array('a'=>'b', 'c'=>'d'); $this->assertEquals($expected, $actual); } function testOutput() { $mapper = new SPIL_DataMapper_FormUrlEncoded(); $actual = $mapper->output(array('a'=>'b', 'c'=>'d')); $expected = 'a=b&c=d'; $this->assertEquals($expected, $actual); } function testContentType() { $mapper = new SPIL_DataMapper_FormUrlEncoded(); $expected = 'application/x-www-formurlencoded'; $actual = $mapper->getContentType(); $this->assertEquals($expected, $actual); } function testPHPVersion() { $mapper = new SPIL_DataMapper_FormUrlEncoded(); $expected = '4.0.3'; $actual = $mapper->getSupportedPhpVersion(); $this->assertEquals($expected, $actual); } }
PHP
import airService from '@/api/air.service'; /** * Fetch content * @param {*} commit - commit mutations * @param {*} offset - number of rows at the beginning which have to be omit * @param {*} methodName - name of AIR service method */ export default function(commit, offset, methodName) { airService[methodName](offset).then(resp => { commit('addContent', resp.data); commit('setPaginationParams', resp.pagination); }); }
JavaScript
Friend Class TestSignatureHelpSource Implements ISignatureHelpSource
Visual Basic
import React from 'react'; import moment from 'moment'; export interface PickerProps { value?: moment.Moment; prefixCls: string; } export default function createPicker(TheCalendar: any): React.ClassicComponentClass<{ prefixCls: string; }>;
TypeScript
function validateUsr(username) { return /^[0-9a-z_]{4,16}$/.test(username) }
JavaScript
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of asistente_controller * * @author equipo1 */ class AsistenteController extends AppController { //put your code here function asistente1() {//personales Load::model('proveedores'); View::template("asistente/default"); if (Input::hasPost("proveedores")) { $tid = Input::post("tipo_identificacion"); $tci = Input::post("ciudad"); $ten = Input::post("tipo_entidad"); $tpr = Input::post("tipo_proveedor"); $proveedor = new Proveedores(Input::post("proveedores")); $proveedor->tipo_identificacion_id = $tid["tipo_identificacion_id"]; $proveedor->ciudad_id = $tci["ciudad_id"]; $proveedor->tipo_entidad_id = $ten["tipo_entidad_id"]; $proveedor->tipo_proveedor_id = "3"; $proveedor->tipousuario_id = "2"; if ($proveedor->save()) { Session::set("idproveedor", $proveedor->id); Session::set("idtipoproveedor","2"); Flash::success("Creado correctamente"); Router::redirect("asistente/editar/"); } } } function editar() { Load::models("proveedores","actividad_has_proveedores"); View::template('asistente/default_ribbon'); $idproveedor= Session::get("idproveedor"); $this->proveedor = new Proveedores(); $this->proveedor->find_first($idproveedor); $actividades = new ActividadHasProveedores(); if($actividades->count("proveedores_id=$idproveedor")==0){ Flash::notice("No tiene ninguna actividad relacionada."); } if (Input::hasPost("proveedores")) { $tid = Input::post("tipo_identificacion"); $tci = Input::post("ciudad"); $ten = Input::post("tipo_entidad"); $tpr = Input::post("tipo_proveedor"); $proveedor = new Proveedores(Input::post("proveedores")); $proveedor->id = Session::get("idproveedor"); $proveedor->tipo_identificacion_id = $tid["tipo_identificacion_id"]; $proveedor->ciudad_id = $tci["ciudad_id"]; $proveedor->tipo_entidad_id = $ten["tipo_entidad_id"]; $proveedor->tipo_proveedor_id = "3"; if ($proveedor->update()) { Flash::success("Actualizado correctamente"); Router::redirect("asistente/editar/"); } } } function actividades() { View::template("asistente/default_ribbon"); Load::model("actividad_has_proveedores"); $idproveedor = Session::get("idproveedor"); $ap = new ActividadHasProveedores(); $this->actividades = array(); $this->actividades = $ap->find("proveedores_id=$idproveedor"); if (Input::hasPost("actividad")) { $in = Input::post("actividad"); $idactividad = $in["actividad_id"]; $idproveedor = Session::get("idproveedor"); $ap = new ActividadHasProveedores(); if ($ap->count("actividad_id=$idactividad and proveedores_id=$idproveedor") == 0) { $ap->actividad_id = $idactividad; $ap->proveedores_id = $idproveedor; if ($ap->save()) { Flash::success("Actividad agregada correctamente"); Router::redirect("asistente/actividades"); } else { Flash::error("Error agregando actividad"); } } else { Flash::error("La actividad seleccionada ya existe"); } } } function eliminar($idactividad) { View::template("asistente/default_ribbon"); $idproveedor = Session::get("idproveedor"); Load::model("actividad_has_proveedores"); $ap = new ActividadHasProveedores(); $ap->find_first($idactividad); if ($ap->delete()) { Flash::success("Se eliminó la actividad correctamente"); Router::redirect("asistente/actividades"); } else { Flash::error("Se eliminó la actividad correctamente"); Router::redirect("asistente/actividades"); } } //ajax actividades public function getDivisiones() { View::response('view'); Load::model("division"); $division = new Division(); $this->seccion_id = Input::post('seccion_id'); } public function getActividades() { View::response('view'); Load::model("actividad"); $actividad = new Actividad(); $this->division_id = Input::post('division_id'); } //listar contratos del proveedor function contratos($pagina = 1) { View::template("asistente/default_ribbon"); Load::model("contratos"); $idproveedor = Session::get("idproveedor"); $this->contrato = array(); try { $obj = new Contratos(); $this->contrato = $obj->paginar($pagina, $idproveedor); } catch (KumbiaException $e) { View::excepcion($e); } } function repExProvVertical(){ View::template("asistente/default_ribbon"); Load::models("actividad","division","seccion","proveedores","actividad_has_proveedores","tipo_identificacion","tipo_entidad","ciudad","contratos"); Load::lib("PHPExcel/PHPExcel"); $idproveedor = Session::get("idproveedor"); $this->obj = new Proveedores(); $this->obj->find_first($idproveedor); $ap = new ActividadHasProveedores(); $this->actividades = array(); $this->actividades = $ap->find("proveedores_id=$idproveedor"); } } ?>
PHP
// // SKChangePasswordViewController.swift // 365KEY_swift // // Created by 牟松 on 2016/12/14. // Copyright © 2016年 DoNews. All rights reserved. // import UIKit class SKChangePasswordViewController: UIViewController { var navBar: UINavigationBar? var navItem: UINavigationItem? var titleName: String? var newPasswordTF: UITextField? var againPasswordTF: UITextField? var captachTF: UITextField? var fatchCapeachBtn: UIButton? var userShared: SKUserShared? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white addSubView() } } extension SKChangePasswordViewController{ func addSubView() { navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: SKScreenWidth, height: 64)) navBar?.isTranslucent = false navBar?.barTintColor = UIColor().mainColor navBar?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] view.addSubview(navBar!) navItem = UINavigationItem() navItem?.title = "修改\(title!)" navItem?.leftBarButtonItem = UIBarButtonItem(SK_barButtonItem: "取消", tragtic: self, action: #selector(navLeftBarButtonDidClick)) navItem?.rightBarButtonItem = UIBarButtonItem(SK_barButtonItem: "保存", tragtic: self, action: #selector(navRightBarButtonDidClick)) navBar?.items = [navItem!] newPasswordTF = UITextField(frame: CGRect(x: 40, y: 26+64, width: SKScreenWidth-80, height: 40)) newPasswordTF?.placeholder = "新\(title!)" newPasswordTF?.textAlignment = .center newPasswordTF?.borderStyle = .roundedRect newPasswordTF?.delegate = self view.addSubview(newPasswordTF!) againPasswordTF = UITextField(frame: CGRect(x: 40, y: 26+64+10+40, width: SKScreenWidth-80, height: 40)) againPasswordTF?.placeholder = "重复新密码" againPasswordTF?.textAlignment = .center againPasswordTF?.borderStyle = .roundedRect againPasswordTF?.delegate = self view.addSubview(againPasswordTF!) captachTF = UITextField(frame: CGRect(x: 40, y: 26+64+10+40+10+40, width: SKScreenWidth-80, height: 40)) captachTF?.placeholder = "验证码" captachTF?.textAlignment = .center captachTF?.borderStyle = .roundedRect captachTF?.delegate = self view.addSubview(captachTF!) fatchCapeachBtn = UIButton(frame: CGRect(x: SKScreenWidth-80-66, y: 0, width: 66, height: 40)) fatchCapeachBtn?.setTitle("获取", for: .normal) fatchCapeachBtn?.setTitleColor(UIColor.white, for: .normal) fatchCapeachBtn?.setBackgroundImage(UIImage(named: "bg_huoqu"), for: .normal) fatchCapeachBtn?.addTarget(self, action: #selector(fatchCapeachBtnDidClick), for: .touchUpInside) captachTF?.addSubview(fatchCapeachBtn!) } @objc private func fatchCapeachBtnDidClick(button: UIButton){ // 倒计时 var timeout: Int = 60 let queue = DispatchQueue.global() let source = DispatchSource.makeTimerSource(flags: [], queue: queue) source.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.seconds(1), leeway: DispatchTimeInterval.milliseconds(100)) source.setEventHandler{ timeout -= 1 if timeout <= 0 { source.cancel() DispatchQueue.main.async { button.setTitle("获取", for: .normal) button.isUserInteractionEnabled = true } } else { button.isUserInteractionEnabled = false DispatchQueue.main.async { UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(1) button.setTitle("\(timeout)秒", for: .normal) UIView.commitAnimations() } } } source.resume() // 发送请求 NSURLConnection.connection.registerFatchCaptcha(with: (userShared?.userInfo?.tel)!){isSuccess,codeNum in switch codeNum! { case 0:{ SKProgressHUD.setSuccessString(with: "验证码发送成功") }() case 1:{ SKProgressHUD.setErrorString(with: "手机号已被注册") }() default:{ SKProgressHUD.setErrorString(with: "验证码发送失败") }() } } } @objc private func navLeftBarButtonDidClick(){ _ = navigationController?.popViewController(animated: true) } @objc private func navRightBarButtonDidClick(){ if checkEmptyString(string: newPasswordTF?.text) && checkEmptyString(string: againPasswordTF?.text) && checkEmptyString(string: captachTF?.text){ if newPasswordTF?.text == againPasswordTF?.text { var parames = [String: AnyObject]() parames["phone"] = userShared?.userInfo?.tel as AnyObject parames["new_pwd"] = newPasswordTF?.text as AnyObject parames["confirm_pwd"] = againPasswordTF?.text as AnyObject parames["checkcode"] = captachTF?.text as AnyObject NSURLConnection.connection.chengeUserInfo(params: parames, completion: { (bool, codeNum) in if bool { if codeNum == 0{ NSURLConnection.connection.userInfoRequest(compeltion: { (bool) in }) _ = self.navigationController?.popViewController(animated: true) SKProgressHUD.setSuccessString(with: "修改\(self.title!)成功") } else if codeNum == -11 { SKProgressHUD.setErrorString(with: "新密码和原密码相同") } else { SKProgressHUD.setErrorString(with: "修改密码失败") } } else { SKProgressHUD.setErrorString(with: "修改密码失败") } }) } else { SKProgressHUD.setErrorString(with: "两次输入的密码不一样") } } else { SKProgressHUD.setErrorString(with: "信息有误,请从新填写") } } func checkEmptyString(string: String?) -> Bool { if string?.isEmpty == true || string?.characters.count == 0 || string == "" { return false } else { return true } } } extension SKChangePasswordViewController: UITextFieldDelegate{ func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
Swift
RUN apt-get install -y php7.4
Twig
require 'net/http' require 'chef/rest' require 'chef/config' require 'chef/data_bag' require 'chef/encrypted_data_bag_item' bagname = 'nmdproxy' appname = 'upstream' environment = ARGV[4] server = /^([^.]*)/.match(ARGV[5]).to_s sitename = ARGV[6] action = ARGV[7] puts environment puts server puts sitename puts action # Use the same config as knife uses Chef::Config.from_file("#{ENV['JENKINS_HOME']}/workspace/jenkins-scripts/.chef/knife.rb") # Get the encrypted data secret secret = Chef::EncryptedDataBagItem.load_secret(ENV['NMDCHEF_SECRET_FILE']) # Load the client data bag client = Chef::EncryptedDataBagItem.load('nmdhosting', sitename, secret) # Get the server_aliases values we need to move in proxy aliases = client[environment]['server_aliases'] # Load the proxy data bag item = Chef::EncryptedDataBagItem.load(bagname, appname, secret) # Get the environment data we are altering update = item[environment] if action == 'add' aliases.each do |key| puts update[server]['apps'][key] if update[server]['apps'][key].nil? update[server]['apps'][key] = {"maintenance" => true} else update[server]['apps'][key]['maintenance'] = true end puts update[server]['apps'][key] end elsif action == 'remove' aliases.each do |key| puts update[server]['apps'][key] update[server]['apps'][key].delete("maintenance") puts update[server]['apps'][key] end else abort "Invalid action #{action}" end # Construct a new data bag bag_item = Chef::DataBagItem.new bag_item.data_bag(bagname) bag_item['id'] = appname bag_item['_default'] = item['_default'] # Determine which environment we are altering in update bag_item['staging'] = item['staging'] bag_item['staging'] = update unless environment != 'staging' bag_item['production'] = item['production'] bag_item['production'] = update unless environment != 'production' # Encrypt and save new data bag enc_hash = Chef::EncryptedDataBagItem.encrypt_data_bag_item(bag_item, secret) ebag_item = Chef::DataBagItem.from_hash(enc_hash) ebag_item.data_bag(bagname) ebag_item.save exit 0
Ruby
#ifndef PRIOQ_H #define PRIOQ_H #include "datetime.h" #include "gen_alloc.h" struct prioq_elt { datetime_sec dt; unsigned long id; } ; GEN_ALLOC_typedef(prioq,struct prioq_elt,p,len,a) extern int prioq_insert(); extern int prioq_min(); extern void prioq_delmin(); #endif
C
package blcs.lwb.lwbtool.utils; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Matrix; import android.widget.ImageView; import com.google.zxing.BarcodeFormat; import com.google.zxing.BinaryBitmap; import com.google.zxing.DecodeHintType; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatReader; import com.google.zxing.MultiFormatWriter; import com.google.zxing.Result; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.yzq.zxinglibrary.android.CaptureActivity; import com.yzq.zxinglibrary.bean.ZxingConfig; import com.yzq.zxinglibrary.common.Constant; import java.util.Hashtable; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 二维码/条形码工具类 * 1.生成二维码图片 * 2.生成带Logo二维码图片 * 3.生成条形码 * 4.解析图片中的 二维码 或者 条形码 * 5.跳转扫描页面 */ public class LinQrCode { /** * 1.生成二维码图片 */ public static void createQRCode(String content, ImageView view) { createQRCode(content, null,view); } /** * 2.生成带Logo二维码图片 */ public static void createQRCode(String content, Bitmap mBitmap,ImageView view) { view.setImageBitmap(createQRCode(content,500,1,mBitmap)); } /** * 生成带logo的二维码 * @param url 需要生成二维码的文字、网址等 * @param size 需要生成二维码的大小() * @param margin 空白边距 * @param mBitmap logoSize 文件大小 * @param mBitmap logo文件 * @return bitmap */ public static Bitmap createQRCode(String url, int size,int margin, Bitmap mBitmap) { try { int IMAGE_HALFWIDTH = size/10 ; Hashtable<EncodeHintType, Object> hints = new Hashtable<>(); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); /* * 设置容错级别,默认为ErrorCorrectionLevel.L * 因为中间加入logo所以建议你把容错级别调至H,否则可能会出现识别不了 */ hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //空白边距设置 hints.put(EncodeHintType.MARGIN, margin); BitMatrix bitMatrix = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, size, size, hints); int width = bitMatrix.getWidth();//矩阵高度 int height = bitMatrix.getHeight();//矩阵宽度 int halfW = width / 2; int halfH = height / 2; if(mBitmap!=null){ Matrix m = new Matrix(); float sx = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getWidth(); float sy = (float) 2 * IMAGE_HALFWIDTH / mBitmap.getHeight(); m.setScale(sx, sy); //设置缩放信息 //将logo图片按martix设置的信息缩放 mBitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(), mBitmap.getHeight(), m, false); } int[] pixels = new int[size * size]; for (int y = 0; y < size; y++) { for (int x = 0; x < size; x++) { if (mBitmap != null && x > halfW - IMAGE_HALFWIDTH && x < halfW + IMAGE_HALFWIDTH && y > halfH - IMAGE_HALFWIDTH && y < halfH + IMAGE_HALFWIDTH) { //该位置用于存放图片信息 记录图片每个像素信息 pixels[y * width + x] = mBitmap.getPixel(x - halfW + IMAGE_HALFWIDTH, y - halfH + IMAGE_HALFWIDTH); } else { if (bitMatrix.get(x, y)) { pixels[y * size + x] = 0xff000000; } else { pixels[y * size + x] = 0xffffffff; } } } } Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, size, 0, 0, size, size); return bitmap; } catch (WriterException e) { e.printStackTrace(); return null; } } /** * 3.生成条形码 */ public static void createBarCode(String content, ImageView view) { view.setImageBitmap(createBarCode(content)); } public static Bitmap createBarCode(String contents) { return createBarCode(contents, 1000, 300); } public static void createBarCode(String content, int codeWidth, int codeHeight, ImageView view) { view.setImageBitmap(createBarCode(content, codeWidth, codeHeight)); } /** * 生成条形码 * @param content 需要生成的内容 * @param BAR_WIDTH 生成条形码的宽带 * @param BAR_HEIGHT 生成条形码的高度 * @return backgroundColor */ public static Bitmap createBarCode(CharSequence content, int BAR_WIDTH, int BAR_HEIGHT) { if(!isNumberOrAlpha(content+"")){ return null; } // 条形码的编码类型 BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128; final int backColor = 0xFFFFFFFF; final int barCodeColor = 0xFF000000; MultiFormatWriter writer = new MultiFormatWriter(); BitMatrix result = null; try { result = writer.encode(content + "", barcodeFormat, BAR_WIDTH, BAR_HEIGHT, null); } catch (WriterException e) { e.printStackTrace(); } int width = result.getWidth(); int height = result.getHeight(); int[] pixels = new int[width * height]; // All are 0, or black, by default for (int y = 0; y < height; y++) { int offset = y * width; for (int x = 0; x < width; x++) { pixels[offset + x] = result.get(x, y) ? barCodeColor : backColor; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } /** * 4.解析图片中的 二维码 或者 条形码 * @param photo 待解析的图片 * @return Result 解析结果,解析识别时返回NULL */ public static Result decodeFromPhoto(Bitmap photo) { Result rawResult = null; if (photo != null) { Bitmap smallBitmap = zoomBitmap(photo, photo.getWidth() / 2, photo.getHeight() / 2);// 为防止原始图片过大导致内存溢出,这里先缩小原图显示,然后释放原始Bitmap占用的内存 // photo.recycle(); // 释放原始图片占用的内存,防止out of memory异常发生 MultiFormatReader multiFormatReader = new MultiFormatReader(); // 解码的参数 Hashtable<DecodeHintType, Object> hints = new Hashtable<>(2); // 可以解析的编码类型 Vector<BarcodeFormat> decodeFormats = new Vector<>(); if (decodeFormats.isEmpty()) { decodeFormats = new Vector<>(); Vector<BarcodeFormat> PRODUCT_FORMATS = new Vector<>(5); PRODUCT_FORMATS.add(BarcodeFormat.UPC_A); PRODUCT_FORMATS.add(BarcodeFormat.UPC_E); PRODUCT_FORMATS.add(BarcodeFormat.EAN_13); PRODUCT_FORMATS.add(BarcodeFormat.EAN_8); // PRODUCT_FORMATS.add(BarcodeFormat.RSS14); Vector<BarcodeFormat> ONE_D_FORMATS = new Vector<>(PRODUCT_FORMATS.size() + 4); ONE_D_FORMATS.addAll(PRODUCT_FORMATS); ONE_D_FORMATS.add(BarcodeFormat.CODE_39); ONE_D_FORMATS.add(BarcodeFormat.CODE_93); ONE_D_FORMATS.add(BarcodeFormat.CODE_128); ONE_D_FORMATS.add(BarcodeFormat.ITF); Vector<BarcodeFormat> QR_CODE_FORMATS = new Vector<>(1); QR_CODE_FORMATS.add(BarcodeFormat.QR_CODE); Vector<BarcodeFormat> DATA_MATRIX_FORMATS = new Vector<>(1); DATA_MATRIX_FORMATS.add(BarcodeFormat.DATA_MATRIX); // 这里设置可扫描的类型,我这里选择了都支持 decodeFormats.addAll(ONE_D_FORMATS); decodeFormats.addAll(QR_CODE_FORMATS); decodeFormats.addAll(DATA_MATRIX_FORMATS); } hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats); // 设置继续的字符编码格式为UTF8 // hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); // 设置解析配置参数 multiFormatReader.setHints(hints); // 开始对图像资源解码 try { rawResult = multiFormatReader.decodeWithState(new BinaryBitmap(new HybridBinarizer(new BitmapLuminanceSource(smallBitmap)))); } catch (Exception e) { e.printStackTrace(); } smallBitmap.recycle(); } return rawResult; } /** * 5.跳转扫描页面 * @param context * @param requestCode 扫描返回码 */ public static void startScan(Activity context, int requestCode) { Intent intent = new Intent(context, CaptureActivity.class); /*ZxingConfig是配置类 *可以设置是否显示底部布局,闪光灯,相册, * 是否播放提示音 震动 * 设置扫描框颜色等 * 也可以不传这个参数 * */ ZxingConfig config = new ZxingConfig(); // config.setPlayBeep(false);//是否播放扫描声音 默认为true // config.setShake(false);//是否震动 默认为true // config.setDecodeBarCode(false);//是否扫描条形码 默认为true // config.setReactColor(R.color.colorAccent);//设置扫描框四个角的颜色 默认为白色 // config.setFrameLineColor(R.color.colorAccent);//设置扫描框边框颜色 默认无色 // config.setScanLineColor(R.color.colorAccent);//设置扫描线的颜色 默认白色 config.setFullScreenScan(false);//是否全屏扫描 默认为true 设为false则只会在扫描框中扫描 intent.putExtra(Constant.INTENT_ZXING_CONFIG, config); context.startActivityForResult(intent, requestCode); } /** * 压缩 * @param bitmap * @param width * @param height * @return */ public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); Matrix matrix = new Matrix(); float scaleWidth = ((float) width / w); float scaleHeight = ((float) height / h); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true); } /**判断字符类型是否是号码或字母 * @param inputed * @return */ public static boolean isNumberOrAlpha(String inputed) { if (inputed == null) { return false; } Pattern pNumber = Pattern.compile("[0-9]*"); Matcher mNumber; Pattern pAlpha = Pattern.compile("[a-zA-Z]"); Matcher mAlpha; for (int i = 0; i < inputed.length(); i++) { mNumber = pNumber.matcher(inputed.substring(i, i+1)); mAlpha = pAlpha.matcher(inputed.substring(i, i+1)); if(! mNumber.matches() && ! mAlpha.matches()){ return false; } } return true; } }
Java
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <algorithm> #include <random> #include <boost/property_tree/json_parser.hpp> #include <osquery/core.h> #include <osquery/logger.h> #include <osquery/packs.h> #include <osquery/sql.h> #include "osquery/core/conversions.h" namespace pt = boost::property_tree; namespace osquery { FLAG(int32, pack_refresh_interval, 3600, "Cache expiration for a packs discovery queries"); FLAG(string, pack_delimiter, "_", "Delimiter for pack and query names"); FLAG(int32, schedule_splay_percent, 10, "Percent to splay config times"); FLAG(int32, schedule_default_interval, 3600, "Query interval to use if none is provided"); size_t splayValue(size_t original, size_t splayPercent) { if (splayPercent <= 0 || splayPercent > 100) { return original; } float percent_to_modify_by = (float)splayPercent / 100; size_t possible_difference = original * percent_to_modify_by; size_t max_value = original + possible_difference; size_t min_value = std::max((size_t)1, original - possible_difference); if (max_value == min_value) { return max_value; } std::default_random_engine generator; generator.seed( std::chrono::high_resolution_clock::now().time_since_epoch().count()); std::uniform_int_distribution<size_t> distribution(min_value, max_value); return distribution(generator); } size_t restoreSplayedValue(const std::string& name, size_t interval) { // Attempt to restore a previously-calculated splay. std::string content; getDatabaseValue(kPersistentSettings, "interval." + name, content); if (!content.empty()) { // This query name existed before, check the last requested interval. auto details = osquery::split(content, ":"); if (details.size() == 2) { long last_interval, last_splay; if (safeStrtol(details[0], 10, last_interval) && safeStrtol(details[1], 10, last_splay)) { if (last_interval == static_cast<long>(interval) && last_splay > 0) { // This is a matching interval, use the previous splay. return static_cast<size_t>(last_splay); } } } } // If the splayed interval was not restored from the database. auto splay = splayValue(interval, FLAGS_schedule_splay_percent); content = std::to_string(interval) + ":" + std::to_string(splay); setDatabaseValue(kPersistentSettings, "interval." + name, content); return splay; } void Pack::initialize(const std::string& name, const std::string& source, const pt::ptree& tree) { name_ = name; source_ = source; discovery_queries_.clear(); if (tree.count("discovery") > 0) { for (const auto& item : tree.get_child("discovery")) { discovery_queries_.push_back(item.second.get_value<std::string>()); } } discovery_cache_ = std::make_pair<int, bool>(0, false); stats_ = {0, 0, 0}; platform_.clear(); if (tree.count("platform") > 0) { platform_ = tree.get<std::string>("platform", ""); } version_.clear(); if (tree.count("version") > 0) { version_ = tree.get<std::string>("version", ""); } schedule_.clear(); if (tree.count("queries") == 0) { // This pack contained no queries. return; } // If the splay percent is less than 1 reset to a sane estimate. if (FLAGS_schedule_splay_percent <= 1) { FLAGS_schedule_splay_percent = 10; } // Iterate the queries (or schedule) and check platform/version/sanity. for (const auto& q : tree.get_child("queries")) { if (q.second.count("platform")) { if (!checkPlatform(q.second.get<std::string>("platform", ""))) { continue; } } if (q.second.count("version")) { if (!checkVersion(q.second.get<std::string>("version", ""))) { continue; } } ScheduledQuery query; query.query = q.second.get<std::string>("query", ""); query.interval = q.second.get("interval", FLAGS_schedule_default_interval); if (query.interval <= 0 || query.query.empty()) { // Invalid pack query. continue; } query.splayed_interval = restoreSplayedValue(q.first, query.interval); query.options["snapshot"] = q.second.get<bool>("snapshot", false); query.options["removed"] = q.second.get<bool>("removed", true); schedule_[q.first] = query; } } const std::map<std::string, ScheduledQuery>& Pack::getSchedule() const { return schedule_; } const std::vector<std::string>& Pack::getDiscoveryQueries() const { return discovery_queries_; } const PackStats& Pack::getStats() const { return stats_; } const std::string& Pack::getPlatform() const { return platform_; } const std::string& Pack::getVersion() const { return version_; } bool Pack::shouldPackExecute() { return checkVersion() && checkPlatform() && checkDiscovery(); } const std::string& Pack::getName() const { return name_; } const std::string& Pack::getSource() const { return source_; } void Pack::setName(const std::string& name) { name_ = name; } bool Pack::checkPlatform() const { return checkPlatform(platform_); } bool Pack::checkPlatform(const std::string& platform) const { if (platform == "") { return true; } #ifdef __linux__ if (platform.find("linux") != std::string::npos) { return true; } #endif if (platform.find("any") != std::string::npos || platform.find("all") != std::string::npos) { return true; } return (platform.find(kSDKPlatform) != std::string::npos); } bool Pack::checkVersion() const { return checkVersion(version_); } bool Pack::checkVersion(const std::string& version) const { if (version == "") { return true; } auto required_version = split(version, "."); auto build_version = split(kSDKVersion, "."); size_t index = 0; for (const auto& chunk : build_version) { if (required_version.size() <= index) { return true; } try { if (std::stoi(chunk) < std::stoi(required_version[index])) { return false; } else if (std::stoi(chunk) > std::stoi(required_version[index])) { return true; } } catch (const std::invalid_argument& e) { if (chunk.compare(required_version[index]) < 0) { return false; } } index++; } return true; } bool Pack::checkDiscovery() { stats_.total++; int current = (int)getUnixTime(); if ((current - discovery_cache_.first) < FLAGS_pack_refresh_interval) { stats_.hits++; return discovery_cache_.second; } stats_.misses++; discovery_cache_.first = current; discovery_cache_.second = true; for (const auto& q : discovery_queries_) { auto sql = SQL(q); if (!sql.ok()) { LOG(WARNING) << "Discovery query failed (" << q << "): " << sql.getMessageString(); discovery_cache_.second = false; break; } if (sql.rows().size() == 0) { discovery_cache_.second = false; break; } } return discovery_cache_.second; } }
C++
package dao import ( "context" "go-common/app/service/main/relation/model" xtime "go-common/library/time" "time" "testing" "github.com/smartystreets/goconvey/convey" ) func TestDaotagsKey(t *testing.T) { var ( mid = int64(0) ) convey.Convey("tagsKey", t, func(ctx convey.C) { p1 := tagsKey(mid) ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) { ctx.So(p1, convey.ShouldNotBeNil) }) }) } func TestDaofollowingsKey(t *testing.T) { var ( mid = int64(0) ) convey.Convey("followingsKey", t, func(ctx convey.C) { p1 := followingsKey(mid) ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) { ctx.So(p1, convey.ShouldNotBeNil) }) }) } func TestDaoAddFollowingCache(t *testing.T) { var ( c = context.Background() mid = int64(0) following = &model.Following{} ) convey.Convey("AddFollowingCache", t, func(ctx convey.C) { err := d.AddFollowingCache(c, mid, following) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestDaoDelFollowing(t *testing.T) { var ( c = context.Background() mid = int64(0) following = &model.Following{} ) convey.Convey("DelFollowing", t, func(ctx convey.C) { err := d.DelFollowing(c, mid, following) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestDaoencode(t *testing.T) { var ( attribute = uint32(0) mtime = xtime.Time(time.Now().Unix()) tagids = []int64{} special = int32(0) ) convey.Convey("encode", t, func(ctx convey.C) { res, err := d.encode(attribute, mtime, tagids, special) ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) ctx.So(res, convey.ShouldNotBeNil) }) }) } func TestDaofollowingKey(t *testing.T) { var ( mid = int64(0) ) convey.Convey("followingKey", t, func(ctx convey.C) { p1 := followingKey(mid) ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) { ctx.So(p1, convey.ShouldNotBeNil) }) }) } func TestDaotagCountKey(t *testing.T) { var ( mid = int64(0) ) convey.Convey("tagCountKey", t, func(ctx convey.C) { p1 := tagCountKey(mid) ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) { ctx.So(p1, convey.ShouldNotBeNil) }) }) } func TestDaoDelFollowingCache(t *testing.T) { var ( c = context.Background() mid = int64(0) ) convey.Convey("DelFollowingCache", t, func(ctx convey.C) { err := d.DelFollowingCache(c, mid) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestDaodelFollowingCache(t *testing.T) { var ( c = context.Background() key = "" ) convey.Convey("delFollowingCache", t, func(ctx convey.C) { err := d.delFollowingCache(c, key) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestDaoDelTagCountCache(t *testing.T) { var ( c = context.Background() mid = int64(0) ) convey.Convey("DelTagCountCache", t, func(ctx convey.C) { err := d.DelTagCountCache(c, mid) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) } func TestDaoDelTagsCache(t *testing.T) { var ( c = context.Background() mid = int64(0) ) convey.Convey("DelTagsCache", t, func(ctx convey.C) { err := d.DelTagsCache(c, mid) ctx.Convey("Then err should be nil.", func(ctx convey.C) { ctx.So(err, convey.ShouldBeNil) }) }) }
Go
package cn.forgeeks.mybatis.test.dao; import cn.forgeeks.mybatis.test.pojo.Teacher; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.InsertProvider; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.apache.ibatis.annotations.UpdateProvider; import org.apache.ibatis.type.JdbcType; @Mapper public interface TeacherMapper { @Delete({ "delete from teacher", "where tid = #{tid,jdbcType=VARCHAR}" }) int deleteByPrimaryKey(String tid); @Insert({ "insert into teacher (tid, tname, ", "tnumber)", "values (#{tid,jdbcType=VARCHAR}, #{tname,jdbcType=VARCHAR}, ", "#{tnumber,jdbcType=VARCHAR})" }) int insert(Teacher record); @InsertProvider(type=TeacherSqlProvider.class, method="insertSelective") int insertSelective(Teacher record); @Select({ "select", "tid, tname, tnumber", "from teacher", "where tid = #{tid,jdbcType=VARCHAR}" }) @Results({ @Result(column="tid", property="tid", jdbcType=JdbcType.VARCHAR, id=true), @Result(column="tname", property="tname", jdbcType=JdbcType.VARCHAR), @Result(column="tnumber", property="tnumber", jdbcType=JdbcType.VARCHAR) }) Teacher selectByPrimaryKey(String tid); @UpdateProvider(type=TeacherSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(Teacher record); @Update({ "update teacher", "set tname = #{tname,jdbcType=VARCHAR},", "tnumber = #{tnumber,jdbcType=VARCHAR}", "where tid = #{tid,jdbcType=VARCHAR}" }) int updateByPrimaryKey(Teacher record); }
Java
import { createResponse, ConvoyrResponse } from '@convoyr/core'; import { isServerError } from './is-server-error'; describe.each<[ConvoyrResponse, boolean]>([ [ createResponse({ status: 500, statusText: 'Internal Server Error', }), true, ], [ createResponse({ status: 200, statusText: 'Ok', }), false, ], [ createResponse({ status: 400, statusText: 'Bad Request', }), false, ], [ createResponse({ status: 304, statusText: 'Not Modified', }), false, ], ])('isServerError with response: %p => %p', (response, expected) => { it('should check if the response is a server error', () => { expect(isServerError(response)).toBe(expected); }); });
TypeScript
var ZenPen = (function() { 'use strict'; /** * Add trim function to strings * * @return string */ String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g, ''); }; /** * Get text from DOM nodes * * @param object el DOM node element * @return string */ function get_text(el) { var ret = " "; var length = el.childNodes.length; for (var i = 0; i < length; i++) { var node = el.childNodes[i]; if (node.nodeType !== 8) { if (node.nodeType !== 1) { ret += node.nodeValue; } else { ret += get_text(node); } } } return ret.trim(); } /** * Check if element has parent with a special tag name * * @param object element DOM node element * @param string parent Parent's DOM tag name * @return bool */ function hasParent(element, parent) { if (element.tagName.toLowerCase() === 'html') { return false; } if (element.parentNode.tagName.toLowerCase() === parent.toLowerCase()) { return true; } else { return hasParent(element.parentNode, parent); } } /** * Check if element has parent with a special id attribute * * @param object element DOM node element * @param string parent Parent's id * @return bool */ function hasParentWithID(element, parent) { if (element.tagName.toLowerCase() === 'html') { return false; } if (element.parentNode.id.toLowerCase() === parent.toLowerCase()) { return true; } else { return hasParentWithID(element.parentNode, parent); } } /** * Check if object has element * * @param object nodeList Object of node items * @param string name Element's name to search for * * @return bool */ function hasNode(nodeList, name) { return !!nodeList[name]; } /** * Get list of elements in node * * @param object element DOM node element * @return object */ function findNodes(element) { var nodeNames = {}; while (element.parentNode) { nodeNames[element.nodeName] = true; element = element.parentNode; if (element.nodeName === 'A') { nodeNames.url = element.href; } } return nodeNames; } /** * Check if browser has support for HTML storage * * @return bool */ function supportsHtmlStorage() { try { return 'localStorage' in window && window.localStorage !== null; } catch (e) { return false; } } /** * ToolTip Constructor * * @param string id ToolTip's HTML container element ID * @param object editor ZepPen Editor object for bindings */ var ToolTip = function(id, actions, editor) { // Initialize this.id = id; this.editor = editor; this.features = ['bold', 'italic', 'link', 'quote', 'underline']; this.actions = actions; this.active = 0; this.el = document.getElementById(this.id); // Default handlers this.linkSelection = this.timeoutClose = this.isOpen = this.url = null; // Set view mode this.setMode('buttons'); // Listen for events var that = this; this.enableActions(); this.el.addEventListener('click', function(event) { event.stopPropagation(); event.stopImmediatePropagation(); // Check if click on known action if (event.target.attributes['data-action'] && that.features.indexOf(event.target.attributes['data-action'].value) > -1) { var action = event.target.attributes['data-action'].value; // Run action and update bubbles if styles have changed that.runAction(action); that.updatePosition(); // Quit return; } // Check if click on input element if (event.target.tagName.toLowerCase() === 'input') { that.focusInput(); // Quit return; } }); }; ToolTip.prototype.enableActions = function() { this.active = 0; for (var i = 0, m = this.features.length; i < m; i++) { if (this.actions.indexOf(this.features[i]) === -1) { if (this.el.querySelector('button[data-action="' + this.features[i] + '"]')) { this.el.querySelector('button[data-action="' + this.features[i] + '"]').className = 'disabled'; this.el.querySelector('button[data-action="' + this.features[i] + '"]').attributes['data-action'].value = 'none'; } } else { this.active++; } } this.el.querySelector('.options').style.width = this.getWidth() + 'px'; var tmpAttr = document.createAttribute('data-count'); tmpAttr.value = this.active; this.el.querySelector('.options').setAttributeNode(tmpAttr); }; ToolTip.prototype.getWidth = function() { return this.getMode('url') ? 275 : this.active * 28 + this.active * 5 + 5; }; /** * Change focus from URL input field back to content editor */ ToolTip.prototype.blurInput = function() { this.el.querySelector("input").blur(); this.editor.content.focus(); }; /** * Set focus to URL input field */ ToolTip.prototype.focusInput = function() { this.el.querySelector("input").focus(); this.el.querySelector("input").select(); }; /** * Set URL input value * * @param string text URL input value */ ToolTip.prototype.setInput = function(text) { var tmp = text.replace(location.href, ''); this.el.querySelector("input").value = tmp === '#' ? '' : tmp; }; /** * Update basic font styles to current selection */ ToolTip.prototype.applyStyles = function() { if (this.actionStatus('bold')) { this.runAction('bold'); } if (this.actionStatus('italic')) { this.runAction('italic'); } if (this.actionStatus('uderline')) { this.runAction('uderline'); } }; /** * Run action * * @param string action Action key */ ToolTip.prototype.runAction = function(action) { switch (action) { // Run native font style actions case 'bold': case 'italic': case 'underline': document.execCommand(action, false); this.actionToggle(action); break; // Run blockquote action case 'quote': var nodeNames = findNodes(window.getSelection().focusNode); if (hasNode(nodeNames, 'BLOCKQUOTE')) { document.execCommand('formatBlock', false, 'p'); } else { document.execCommand('formatBlock', false, 'blockquote'); } this.actionToggle(action); break; // Run link action case 'link': var curURL = '#'; var selection = window.getSelection(); var range = document.createRange(); var that = this; nodeNames = findNodes(window.getSelection().focusNode); /** * Select text and update styles */ var __updateLinkStyles = function() { range.selectNodeContents(document.getElementById('current-link')); selection.removeAllRanges(); selection.addRange(range); that.applyStyles(); }; /** * Update link in editor * * @param string url URL * @param string name Label */ var __updateLink = function(url, name) { document.execCommand('insertHTML', false, '<a href="' + url + '" id="current-link">' + name + '</a>'); __updateLinkStyles(); }; // Get current URL anchor if selection already is a link if (hasNode(nodeNames, "A")) { curURL = nodeNames.url; } if (this.getMode('buttons')) { // Switch from button view to expanded URL view this.setMode('url'); // Update input value and focus input field __updateLink(curURL, window.getSelection().toString()); this.setInput(curURL); this.focusInput(); // Swtich active state if needed if (!this.actionStatus(action)) { this.actionOn(action); } } else if (this.getMode('url') && this.actionStatus(action)) { // Switch from expanded URL view to button view this.setMode('buttons'); // Update text styles if needed __updateLinkStyles(); if (this.el.querySelector('input').value === '') { // Link has no URL, so it will be unlinked this.actionOff(action); document.execCommand('unLink', false); this.applyStyles(); } else { // Link as URL, set state to active and change HTML content this.actionOn(action); that.updateButtonStates(); curURL = this.el.querySelector('input').value; __updateLink(curURL, window.getSelection().toString()); } // Update button states that.updateButtonStates(); // Remove temp element attributes if set if (document.getElementById('current-link')) { document.getElementById('current-link').removeAttribute('id'); } } break; } // Update HTML storage this.editor.writeStorage(); }; /** * Set ToolTip view mode * * @param string mode View mode */ ToolTip.prototype.setMode = function(mode) { this.el.setAttribute('data-mode', mode); if (mode === 'url') { this.el.querySelector('.options').style.width = this.getWidth() + 'px'; // this.updatePosition(); } else { this.enableActions(); } }; /** * Get current ToolTip view mode or compare with given view mode * * @param string comp Optional view name to compare with * @param string or bool */ ToolTip.prototype.getMode = function(comp) { if (!comp) { return this.el.attributes['data-mode'].value; } else { return comp === this.el.attributes['data-mode'].value; } }; /** * Toogle ToolTip option button * * @param string action Action name */ ToolTip.prototype.actionToggle = function(action) { if (this.actionStatus(action)) { this.actionOff(action); } else { this.actionOn(action); } }; /** * Get action status * * @param string action Action name * @return bool */ ToolTip.prototype.actionStatus = function(action) { if (this.actions.indexOf(action) === -1) { return; } return document.querySelector('button[data-action="' + action + '"]').className === 'active'; }; /** * Switch action on * * @param string action Action name */ ToolTip.prototype.actionOn = function(action) { if (this.actions.indexOf(action) === -1) { return; } document.querySelector('button[data-action="' + action + '"]').className = 'active'; }; /** * Switch action off * * @param string action Action name */ ToolTip.prototype.actionOff = function(action) { if (this.actions.indexOf(action) === -1) { return; } document.querySelector('button[data-action="' + action + '"]').className = ''; }; /** * Update button states */ ToolTip.prototype.updateButtonStates = function() { var currentNodeList = findNodes(window.getSelection().focusNode); var nodeMapping = {b: 'bold', i: 'italic', u: 'underline', blockquote: 'quote', a: 'link'}; for (var n in nodeMapping) { if (hasNode(currentNodeList, n.toUpperCase())) { this.actionOn(nodeMapping[n]); } else { this.actionOff(nodeMapping[n]); } } }; /** * Show ToolTip */ ToolTip.prototype.show = function() { if (this.timeoutClose) { clearTimeout(this.timeoutClose); } this.el.querySelector('input').value = ''; this.updatePosition(); this.updateButtonStates(); this.el.className = "text-options active"; this.isOpen = true; }; /** * Close ToolTip */ ToolTip.prototype.close = function() { if (this.timeoutClose) { clearTimeout(this.timeoutClose); } if (document.getElementById('current-link')) { document.getElementById('current-link').removeAttribute('id'); } this.setMode('buttons'); this.el.className = "text-options fade"; var that = this; // Maybe set to display: none? this.timeoutClose = setTimeout(function() { that.el.style.top = "100%"; that.el.style.left = "100%"; }, 260); this.isOpen = false; }; /** * Update ToolTip position */ ToolTip.prototype.updatePosition = function() { var selection = window.getSelection(); try { var range = selection.getRangeAt(0); var boundary = range.getBoundingClientRect(); var newTop = parseFloat(boundary.top - 5 + window.pageYOffset); var newLft = parseFloat(boundary.width/2 + (boundary.left + 63) - this.getWidth()/2); if (newTop === -5 && boundary.left === 0) { return; } this.el.style.top = newTop + "px"; this.el.style.left = newLft + "px"; } catch (e) { } }; /** * ZenPen Editor constructor */ var ZenPen = function(id, actions) { this.id = id; this.lastSelection = null; this.downOnOption = false; this.watcher = []; this.content = document.getElementById(this.id).querySelector('[data-type="content"]'); this.bar = new ToolTip(this.id + '-bar', actions, this); this.watchForSelection(); }; ZenPen.prototype.insertPreview = function(pic) { pic.hash = Math.random().toString(36).substr(2, 15); document.execCommand('insertHTML', false, '<img class="preview loading" id="preview-' + pic.hash + '" />'); pic.previewElement.querySelector('.preview').addEventListener('load', function() { var img = document.getElementById('preview-' + pic.hash); if (img.src) { return; } else { img.src = pic.previewElement.querySelector('.preview').src; } }); this.bar.close(); }; ZenPen.prototype.updatePicture = function(pic, url) { pic.url = url; // Full picture is uploaded and url is received document.getElementById('preview-' + pic.hash).src = pic.url; document.getElementById('preview-' + pic.hash).className = "preview"; }; ZenPen.prototype.enableDropzone = function(Dropzone, url, handleUpload) { var that = this; Dropzone.autoDiscover = false; Dropzone.options.editor = { previewTemplate: '<div class="dz-preview dz-file-preview" style="display: none;"><div class="dz-details"><div class="dz-filename"><span data-dz-name></span></div><div class="dz-size" data-dz-size></div><img class="preview" data-dz-thumbnail /></div><div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div><div class="dz-success-mark"><span>✔</span></div><div class="dz-error-mark"><span>✘</span></div><div class="dz-error-message"><span data-dz-errormessage></span></div></div>', init: function() { /** // Upload Multiple FileS? this.on("complete", function() { if (this.filesQueue && this.filesQueue.length == 0 && this.filesProcessing && this.filesProcessing.length == 0) { console.log("complete", arguments); } }); **/ this.on("success", function(file, text) { that.updatePicture(file, handleUpload(text)); }); this.on("addedfile", function(file) { that.insertPreview(file); }); } }; this.dropzone = new Dropzone("#editor", { url: url || "/file/post"}); }; /** * Add callback for change event * * @param function callback Callback */ ZenPen.prototype.focus = function() { this.content.focus(); }; /** * Add callback for change event * * @param function callback Callback */ ZenPen.prototype.change = function(callback) { this.watcher.push(callback); }; /** * Count words in ZenPen without headline * * @return int */ ZenPen.prototype.countWords = function() { var text = get_text(this.content); if (text === "") { return 0; } return text.split(/\s+/).length; }; /** * Update ToolTip position */ ZenPen.prototype.updatePosition = function() { this.bar.updatePosition(); }; /** * Bind needed elements */ ZenPen.prototype.watchForSelection = function() { var that = this; // Click on ToolTip document.addEventListener("mousedown", function(ev) { if (that.clickIsOnBar(ev)) { ev.preventDefault(); } }); // Starting to select text in content box. This will be called after // mousedown if no 'preventDefault' is called before if (this.content) { this.content.addEventListener("selectstart", function() { that.bar.close(); }); } // Maybe needed for some future magic this.content.addEventListener("selectionchange", function() { }); // Show ToolTip if mouse button is released after selecting text. Needs to // have a little timeout to wait for the user's browser to update the // current text selection. window.addEventListener("mouseup", function(event) { setTimeout(function() { if (that.clickIsOnBar(event)) { } else if (that.hasSelection() && that.clickIsInside(event)) { that.bar.show(); } else { that.bar.close(); } }, 10); }); // Close ToolTip if key is pressed someout outside the ToolTip's input and // save changes to HTML storage document.addEventListener("keydown", function() { // TODO: Just close if content is chanegd if (window.getSelection().focusNode && window.getSelection().focusNode.tagName && window.getSelection().focusNode.tagName.toLowerCase() === 'span') { return; } // Close ToolTip and update HTML storage that.bar.close(); that.writeStorage(); }); // Update ToolTip position after browser is resized window.addEventListener('resize', function() { that.bar.updatePosition(); }); // Update ToolTip position if text is scrolled var scrollEnabled = true; document.body.addEventListener( 'scroll', function() { if ( !scrollEnabled ) { return; } scrollEnabled = true; that.bar.updatePosition(); // Smooth scrolling return setTimeout(function() { scrollEnabled = true; }, 250); }); }; /** * Check if user clicked inside ZenPen content editor * * @param object event Click event * @return bool */ ZenPen.prototype.clickIsInside = function(event) { return event.target.tagName.toLowerCase() === 'article' || hasParent(event.target, 'article'); }; /** * Check if user clicked on ToolTip * * @param object event Click event * @return bool */ ZenPen.prototype.clickIsOnBar = function(event) { return event.target.id.toLowerCase() === 'article' || hasParentWithID(event.target, this.bar.id); }; /** * Check if user has selected text * * @return bool */ ZenPen.prototype.hasSelection = function() { return Math.abs(window.getSelection().focusOffset - window.getSelection().baseOffset) > 0; }; /** * Check local HTML storage for saved artcile */ ZenPen.prototype.checkStorage = function() { if (!supportsHtmlStorage()) { return; } if (localStorage.content) { this.content.innerHTML = localStorage.content; } }; /** * Update local HTML storage */ ZenPen.prototype.writeStorage = function() { if (!supportsHtmlStorage()) { return; } localStorage.content = this.content.innerHTML; this.updateWatchers(); }; /** * Update watcher for changes */ ZenPen.prototype.updateWatchers = function() { for (var i = 0, m = this.watcher.length; i < m; i++) { this.watcher[i](this); } }; return ZenPen; })();
JavaScript
package raft import ( "sync" "github.com/sidecus/raft/pkg/util" ) const targetAny = int(^uint(0) >> 1) type replicationReq struct { targetID int reqwg *sync.WaitGroup } // batchReplicator processes incoming requests (best effort) while at the same time tries to batch them for better efficency. // For each request in the request queue: // 1. If request id is less than lastMatch, signal done direclty (already replicated) // 2. If request id is larger than lastMatch, trigger a new replicate (a few items in batch). signal done afterwards regardless // whether the target id is satisfied or not. // In short, each request in the queue will trigger at most 1 replicate type batchReplicator struct { replicateFn func() int requests chan replicationReq wg sync.WaitGroup } // newBatchReplicator creates a new batcher func newBatchReplicator(replicate func() int) *batchReplicator { return &batchReplicator{ replicateFn: replicate, requests: make(chan replicationReq, maxAppendEntriesCount), } } // start starts the batchReplicator func (b *batchReplicator) start() { b.wg.Add(1) go func() { lastMatch := -1 for r := range b.requests { if r.targetID > lastMatch { // invoke new batch operation to see whether we can process up to targetID lastMatch = b.replicateFn() } if r.reqwg != nil { r.reqwg.Done() } } b.wg.Done() }() } // stop stops the batcher and wait for finish func (b *batchReplicator) stop() { close(b.requests) b.wg.Wait() } // requestReplicateTo requests a process towards the target id. // It'll block if current request queue is full. // true - if the targetID is processed within one batch after the request has been picked up by the batcher // false - otherwise func (b *batchReplicator) requestReplicateTo(targetID int, wg *sync.WaitGroup) { if targetID < 0 || targetID == targetAny { util.Panicln("invalid target index") } b.requests <- replicationReq{ targetID: targetID, reqwg: wg, } } // tryRequestReplicate request a batch process with no target. // It won't block if request queue is full. wg is optional func (b *batchReplicator) tryRequestReplicate(wg *sync.WaitGroup) { select { case b.requests <- replicationReq{targetID: targetAny, reqwg: wg}: default: } }
Go
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
69