text:
package com.minecraftmarket.minecraftmarket.common.stats;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;

import com.minecraftmarket.minecraftmarket.common.api.MCMarketApi;
import com.minecraftmarket.minecraftmarket.common.api.models.PlayerSession;
import com.minecraftmarket.minecraftmarket.common.api.models.ServerInfo;
import com.minecraftmarket.minecraftmarket.common.api.models.ServerPlayer;
import com.minecraftmarket.minecraftmarket.common.api.models.ServerPlugin;
import com.minecraftmarket.minecraftmarket.common.utils.Ping;
import com.minecraftmarket.minecraftmarket.common.utils.TPS;

public class BukkitStats extends MCMarketStats {
    private final JavaPlugin plugin;

    public BukkitStats(MCMarketApi marketApi, JavaPlugin plugin) {
        super(marketApi);
        this.plugin = plugin;

        plugin.getServer().getPluginManager().registerEvents(new Listener() {
            @EventHandler
            public void onPlayerJoin(PlayerJoinEvent e) {
                playerJoins.put(e.getPlayer().getUniqueId(), getTime());
            }

            @EventHandler
            public void onPlayerQuit(PlayerQuitEvent e) {
                if (playerJoins.containsKey(e.getPlayer().getUniqueId())) {
                    playerSession.add(getPlayerSession(e.getPlayer()));
                    playerJoins.remove(e.getPlayer().getUniqueId());
                }
            }
        }, plugin);

        Timer timer = new Timer(true);
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                if (!plugin.isEnabled()) {
                    timer.cancel();
                    return;
                }

                plugin.getServer().getScheduler().runTask(plugin, () -> runEventsSender());
            }
        }, 1000 * 10, 1000 * 60);
    }

    @Override
    ServerInfo getServerInfo() {
        Map<String, Object> system = getSystemStats();

        String version = plugin.getServer().getVersion();
        version = version.substring(version.indexOf("MC: ") + 4, version.length() - 1);

        return new ServerInfo(
                0,
                getTime(),
                "Bukkit",
                version,
                plugin.getServer().getOnlineMode(),
                plugin.getServer().getIp(),
                plugin.getServer().getPort(),
                TPS.getTPS(0),
                (String) system.get("javaVersion"),
                (String) system.get("osName"),
                (String) system.get("osArch"),
                (String) system.get("osVersion"),
                (long) system.get("maxMemory"),
                (long) system.get("totalMemory"),
                (long) system.get("freeMemory"),
                (long) system.get("cores"),
                (double) system.get("cpuUsage"),
                getOnlinePlayers(),
                getPlugins()
        );
    }

    @SuppressWarnings("deprecation")
    private List<ServerPlayer> getOnlinePlayers() {
        List<ServerPlayer> players = new ArrayList<>();
        for (Player player : plugin.getServer().getOnlinePlayers()) {
            players.add(new ServerPlayer(
                    0,
                    player.getName(),
                    player.getUniqueId().toString(),
                    player.getAddress().getAddress().getHostAddress(),
                    Ping.getPing(player),
                    Optional.of(player.isOp()),
                    Optional.of(player.getWorld().getName()),
                    Optional.of((long) player.getLocation().getBlockX()),
                    Optional.of((long) player.getLocation().getBlockY()),
                    Optional.of((long) player.getLocation().getBlockZ()),
                    Optional.of(player.getGameMode().name()),
                    Optional.of(round(player.getHealth())),
                    Optional.of(round(player.getMaxHealth())),
                    Optional.of((long) player.getLevel()),
                    Optional.of(round(player.getExp())),
                    Optional.of((long) player.getFoodLevel()),
                    Optional.empty(),
                    Optional.empty()
            ));
        }
        return players;
    }

    private List<ServerPlugin> getPlugins() {
        List<ServerPlugin> plugins = new ArrayList<>();
        for (Plugin plugin : plugin.getServer().getPluginManager().getPlugins()) {
            plugins.add(new ServerPlugin(
                    0,
                    plugin.getName(),
                    plugin.getDescription().getVersion(),
                    Optional.ofNullable(plugin.getDescription().getDescription()),
                    Optional.ofNullable(String.join(", ", plugin.getDescription().getAuthors())),
                    Optional.ofNullable(plugin.getDescription().getWebsite())
            ));
        }
        return plugins;
    }

    private PlayerSession getPlayerSession(Player player) {
        return new PlayerSession(
                0,
                player.getName(),
                player.getUniqueId().toString(),
                playerJoins.get(player.getUniqueId()),
                getTime(),
                player.getAddress().getAddress().getHostAddress()
        );
    }
}


text:
<table data-side-pagination="server" data-page-list="[5, 10, 15, 30, 50, 100]" class="table table-striped" id="datagrid_hot" data-toolbar="#custom-toolbar" data-pagination="true" data-toggle="table"  data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" data-url="<?php echo base_url();?>index.php/prospect/hotdatagrid" data-cache="false">

           RATING
           Fonte
           Nome
           Produto
           Data Cadastro
           Data Atribuição
           Descrição Contato
           Ações

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 <img src=" <?php echo base_url() . 'resources/theme/' . THEME . '/img/logo_modal.png'; ?> "> PROSPECT

            <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <link href='http://fonts.googleapis.com/css?family=Permanent+Marker|Rock+Salt|Open+Sans:300italic,400italic,600italic,400,300,600' rel='stylesheet' type='text/css'>

    <title>Steph Lopez</title>

    <link type="text/css" rel="stylesheet" href="../stylesheets/blog-stylesheet.css" />

        Steph Lopez

          Home/
          About/
          Github/
          Projects/
          Blog/
          Contact

        Write to me.

        Tweets by @SNLSF

We Know There is a Lack of Women in Tech

Consider this.

12.31.2014.

              Tavi Gevinson.  Michelle Phan.  Tracy Dinunzio.  Probably not the first names that come to mind when you think women in tech.  Scrap-booking.  Shopping.  Makeup.  Probably the last things you think of when you think of tech.  But, these women have taken their passions, leveraged technology, and created very successful businesses.

              Stereotypes of the roles women play in technology form in the most obvious place- media.  What happens when we finally get an empowered hack-master leading female role in a movie? Oh that's right, we get The Girl With The Dragon Tattoo, a total outcast manrepeller.  Or what about 1995's The Net- heroine debugs a fatal system and saves the day?  Turns out the heroine, though beautiful, devotes her life to her computer and mother, otherwise an antisocial shut-in.  There aren't many more movies or television shows that I can reference to point out good or bad representations of women in tech because, frankly, it's still a man's world.

              Misconceptions about how women fit in tech also play a part in the under respresentation of women in the industry.  A woman is doing herself and her company a disservice by attempting to do a man's job.  In media we see women pictured in power suits, stifling their emotions, drinking whiskey and smoking cigars to "fit in" with the men.  Women offer unique skills and under no circumstance should downplay their identities.  By empowering the inherent attributes of a woman, we diversify skills, teams, and products. And thus Tavi created Rookie Magazine, Michelle ipsy, and Tracy Tradesy.  These are the types of women that should be present in media.  I would take this opportunity to bash Keeping Up With The Kardashians, BUT Kim K did turn out a damn successful video game!

              Regardless of the huge gender gap, women are playing a prominent role in technology- we just need to showcase their successes to younger generations. As James Brown put it, it's a man's world, but it would be nothing without a woman or a girl.


text:
#region Includes

using System.ServiceProcess;

#endregion

namespace Daishi.Microservices {
    partial class QueueWatchMicroserviceContainer : ServiceBase {
        public QueueWatchMicroserviceContainer() {
            InitializeComponent();
        }

        protected override void OnStart(string[] args) {
            // TODO: Add code here to start your service.
        }

        protected override void OnStop() {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
        }
    }
}


text:
CREATE TABLE with_trigger(a int primary key, b varchar(20), c int);
INSERT INTO with_trigger VALUES (1, 'AAA', 11), (2, 'BBB', 22), (3, 'CCC', 33);
SELECT a, b, c FROM with_trigger order by 1;

CREATE TABLE trigger_actions1(id int auto_increment, a smallint primary key, b string, c numeric);
CREATE TABLE trigger_actions2(id int auto_increment, a bigint, b varchar(20), c monetary unique);

CREATE TABLE trigger_actions3(id int auto_increment, a int, b char(20));

CREATE TRIGGER trig_bef_del BEFORE DELETE ON with_trigger EXECUTE
	INSERT INTO trigger_actions1 (a, b, c) VALUES (11, 'BEFORE DELETE', 11);
CREATE TRIGGER trig_aft_del AFTER DELETE ON with_trigger EXECUTE
	REPLACE INTO trigger_actions1 (a, b, c) VALUES (11, 'AFTER DELETE', 22);
CREATE TRIGGER trig_bef_ins BEFORE INSERT ON with_trigger EXECUTE
	INSERT INTO trigger_actions2 (a, b, c) VALUES (33, 'BEFORE INSERT', 33);
CREATE TRIGGER trig_aft_ins AFTER INSERT ON with_trigger EXECUTE
	REPLACE INTO trigger_actions2 (a, b, c) VALUES (44, 'AFTER INSERT', 33);

--NESTED TRIGGERS
CREATE TRIGGER trig_bef_del2 BEFORE DELETE ON trigger_actions1 EXECUTE
	INSERT INTO trigger_actions3 (a, b) VALUES (11, 'BEFORE DELETE');
CREATE TRIGGER trig_aft_del2 AFTER DELETE ON trigger_actions1 EXECUTE
	INSERT INTO trigger_actions3 (a, b) VALUES (22, 'AFTER DELETE');
CREATE TRIGGER trig_bef_ins2 BEFORE INSERT ON trigger_actions2 EXECUTE
	INSERT INTO trigger_actions3 (a, b) VALUES (33, 'BEFORE INSERT');
CREATE TRIGGER trig_aft_ins2 AFTER INSERT ON trigger_actions2 EXECUTE
	INSERT INTO trigger_actions3 (a, b) VALUES (44, 'AFTER INSERT');

REPLACE INTO with_trigger VALUES (3, 'DDD', 44);
SELECT *FROM with_trigger order by 1;
SELECT * FROM trigger_actions1 order by 1;
SELECT * FROM trigger_actions2 order by 1;
SELECT * FROM trigger_actions3 order by 1;

--error, unique violation
REPLACE INTO with_trigger VALUES (4, 'FFF', 55);
--SELECT * FROM with_trigger;
--SELECT * FROM trigger_actions1;
--SELECT * FROM trigger_actions2;
--SELECT * FROM trigger_actions3;

DROP TRIGGER trig_bef_del;
DROP TRIGGER trig_aft_del;
DROP TRIGGER trig_bef_ins;
DROP TRIGGER trig_aft_ins;

DROP TRIGGER trig_bef_del2;
DROP TRIGGER trig_aft_del2;
DROP TRIGGER trig_bef_ins2;
DROP TRIGGER trig_aft_ins2;

DROP TABLE with_trigger;
DROP TABLE trigger_actions1;
DROP TABLE trigger_actions2;
DROP TABLE trigger_actions3;


text:
<?php

namespace Qustodio\Domain\Entity;

class Rental
{
    /**
     * @var Movie
     */
    private $movie;

    /**
     * @var int
     */
    private $daysRental;

    /**
     * @param Movie $movie
     * @param $daysRental int
     */
    public function __construct(Movie $movie, $daysRental)
    {
        $this->movie = $movie;
        $this->daysRental = $daysRental;
    }

    /**
     * @return int
     */
    public function getDaysRental()
    {
        return $this->daysRental;
    }

    /**
     * @return Movie
     */
    public function getMovie()
    {
        return $this->movie;
    }

}


text:
div#tree{
    margin-left: 30px;
}

form div#operations{
    clear: none;
}


text:
FROM qnib/u-java8

ENV KM_VER=1.3.0.8 \
    ZOOKEEPER_HOSTS=zookeeper.service.consul:2181
RUN apt-get install -y wget nmap \
 && wget -qO /tmp/kafka-manager_${KM_VER}_all.deb https://github.com/qnib/kafka-manager/releases/download/${KM_VER}/kafka-manager_${KM_VER}_all.deb \
 && dpkg -i /tmp/kafka-manager_${KM_VER}_all.deb \
 && rm -f /tmp/kafka-manager_${KM_VER}_all.deb
ADD etc/supervisord.d/kafka-manager.ini /etc/supervisord.d/
ADD opt/qnib/kafka/manager/bin/start.sh \
    opt/qnib/kafka/manager/bin/healthcheck.sh \
    /opt/qnib/kafka/manager/bin/
ADD etc/consul.d/kafka-manager.json /etc/consul.d/
ADD etc/consul-templates/kafka/manager/application.conf.ctmpl /etc/consul-templates/kafka/manager/


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit39015951475fd66548011bb4b99edbd4::getLoader();


text:
<?php

namespace TreeHouse\QueueBundle\Tests\Consumer\Limiter;

use PHPUnit\Framework\TestCase;
use TreeHouse\QueueBundle\Consumer\Consumer;
use TreeHouse\QueueBundle\Consumer\Limiter\LimitReachedException;
use TreeHouse\QueueBundle\Consumer\Limiter\TimeLimiter;

class TimeLimiterTest extends TestCase
{
    /**
     * @test
     */
    public function it_can_reach_a_limit()
    {
        $limiter = new TimeLimiter(10);

        /** @var Consumer $consumer */
        $consumer = $this->prophesize(Consumer::class);
        $consumer->getDuration()->willReturn(10);

        $this->expectException(LimitReachedException::class);

        $limiter->limitReached($consumer->reveal());
    }

    /**
     * @test
     */
    public function it_must_reach_a_limit()
    {
        $limiter = new TimeLimiter(10);

        /** @var Consumer $consumer */
        $consumer = $this->prophesize(Consumer::class);
        $consumer->getDuration()->willReturn(9);

        $this->assertNull($limiter->limitReached($consumer->reveal()));
    }
}


text:
// Copyright 2017-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#import "MaterialHeaderStackView.h"
#import "MaterialThemes.h"

#import <Foundation/Foundation.h>

#pragma mark - Soon to be deprecated

/**
 A color themer for instances of MDCHeaderStackView.

 @warning This class will soon be deprecated. There will be no replacement API. Consider theming
 your flexible header view or app bar instead. Learn more at
 components/schemes/Color/docs/migration-guide-semantic-color-scheme.md
 */
@interface MDCHeaderStackViewColorThemer : NSObject

@end

@interface MDCHeaderStackViewColorThemer (ToBeDeprecated)

/**
 Applies a color scheme's properties to an MDCHeaderStackView.

 @warning This class will soon be deprecated. There will be no replacement API. Consider theming
 your flexible header view or app bar instead. Learn more at
 components/schemes/Color/docs/migration-guide-semantic-color-scheme.md

 @param colorScheme The color scheme to apply to the component instance.
 @param headerStackView A component instance to which the color scheme should be applied.
 */
+ (void)applyColorScheme:(nonnull id<MDCColorScheme>)colorScheme
       toHeaderStackView:(nonnull MDCHeaderStackView *)headerStackView;

@end


text:
require_relative '../JsonBuilder'
class AccessLevels
    include JsonBuilder
    # @!parse attr_accessor :id, :label
    attr_accessor :id, :label

    # Creates an AccessLevels object
    #
    # @param data [Hash, nil] Takes a JSON object/Hash or no argument
    # @return [AccessLevels object]
    #
    # @example
    #         access_level = AccessLevels.new
    def initialize(data=nil)
        json_obj = Validator.validate_argument(data,'AccessLevels')
        @id      = json_obj['id']
        @label   = json_obj['label']
    end
end


text:
#ifndef __STREAM_HPP__
#define __STREAM_HPP__

/*
// for Information of TFO flag

sysctl net.ipv4.tcp_fastopen
or
file:////proc/sys/net/ipv4/tcp_fastopen

// Bit Flags for sysctl_tcp_fastopen
#define TFO_CLIENT_ENABLE       1
#define TFO_SERVER_ENABLE       2

// Data in SYN w/o cookie option
#define TFO_CLIENT_NO_COOKIE    4

// Process SYN data but skip cookie validation
#define TFO_SERVER_COOKIE_NOT_CHKED     0x100

//Accept SYN data w/o any cookie option
#define TFO_SERVER_COOKIE_NOT_REQD      0x200

// Force enable TFO on all listeners, i.e., not requiring the
// TCP_FASTOPEN socket option. SOCKOPT1/2 determine how to set
// max_qlen. Always create TFO child sockets on a TFO listener
// even. when cookie/data not present. (For testing purpose!)
#define TFO_SERVER_WO_SOCKOPT1  0x400
#define TFO_SERVER_WO_SOCKOPT2  0x800

// All listen socket to use tfo
#define TFO_SERVER_ALWAYS       0x1000
*/

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/errno.h>
#include <err.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

#include <iostream>
#include <map>

#ifdef __linux__
#include <netinet/tcp.h>
#include <x86_64-linux-gnu/bits/socket.h>
#endif

#include "common.hpp"

#ifdef DEBUG
#define STREAM_PERROR(func) do {                                \
    if (debug) {                                                \
    char s[BUFSIZ];                                             \
    memset(s, 0, BUFSIZ);                                       \
    snprintf(s, BUFSIZ, "%s(%d):%s", __FILE__, __LINE__, func); \
    perror(s);                                                  \
    }                                                           \
} while (false)
#else
#define STREAM_PERROR(func) do {} while (false)
#endif

#define STREAM_UNUSED  0
#define STREAM_CONNECT 1
#define STREAM_LISTEN  2

class stream {

public:
    stream() {
        signal(SIGPIPE, SIG_IGN);
        stream_family    = 0;
        stream_fd = -1;
        stream_accept_fd = -1;
        stream_status = STREAM_UNUSED;
        memset(&stream_peer_sockaddr, 0, sizeof(stream_peer_sockaddr));
    };
    virtual ~stream() {
        if (stream_fd != -1) {
            stream_close();
        }
        if (stream_accept_fd != -1) {
            stream_accept_close();
        }

    };

    void stream_init();

    int stream_open(const char* type);
    int stream_open(const std::string& type);

    ssize_t stream_send(const void* buf, size_t length, int flag);
    ssize_t stream_recv(void* buf, size_t length);

#ifdef __linux__
    ssize_t stream_sendto(const void* buf, size_t length,
                          const std::string& dest_host,
                          const std::string& dest_port);
    ssize_t stream_re_sendto(const void* buf, size_t length);
#endif

    bool stream_close();
    bool stream_accept_close();
    bool stream_reconnect();

    bool stream_connect(const std::string& dest_host, const std::string& dest_port);
    bool stream_connect(const char* dest_host, const char* dest_port);
    bool stream_connect(const struct sockaddr* dest_addr, socklen_t dest_length);

    bool stream_listen(const std::string& host, const std::string& port);
    int stream_accept();

    struct sockaddr* stream_get_peer_sockaddr();
    std::string stream_get_peer_host();
    std::string stream_get_peer_port();

    int get_fd();

private:
    int stream_fd;
    int stream_accept_fd;
    int stream_family;
    int stream_status;

    char stream_buf[BUFSIZ];

    struct sockaddr_storage stream_peer_sockaddr;
    socklen_t stream_peer_addr_length;
    struct sockaddr_storage stream_accept_sockaddr;
    socklen_t stream_accept_addr_length;
};

#ifdef __linux__
ssize_t
stream::stream_sendto(const void* buf, size_t length,
                      const std::string& dest_host,
                      const std::string& dest_port)
{
    int error;
    struct addrinfo *res;
    struct addrinfo hints;

    if (stream_family == 0) {
        return false;
    }

    memset(&hints, 0, sizeof(hints));

    hints.ai_family = stream_family;
    hints.ai_socktype = SOCK_STREAM;
#ifdef __FreeBSD__
    hints.ai_flags = 0;
#else
    hints.ai_flags = AI_ALL | AI_ADDRCONFIG;
#endif

    error = getaddrinfo(dest_host.c_str(), dest_port.c_str(), &hints, &res);
    if (error) {
#ifdef DEBUG
        if (debug) {
        fprintf(stderr, "%s(%d):getaddrinfo: %s\n", __FILE__, __LINE__, gai_strerror(error));
        }
#endif
        return -1;
    }

    ssize_t size;
    size = sendto(stream_fd, buf, length, MSG_FASTOPEN, res->ai_addr, res->ai_addrlen);
    if (size < 0) {

        STREAM_PERROR("sendto");
        freeaddrinfo(res);
        stream_close();
        return -1;

    } else if (size == 0) {

        freeaddrinfo(res);
        stream_close();
        return size;

    } else {

        stream_status = STREAM_CONNECT;
        stream_get_peer_sockaddr();
        freeaddrinfo(res);
        return size;

    }

    return size;
}

ssize_t
stream::stream_re_sendto(const void* buf, size_t length)
{

    if (stream_family == AF_INET) {
        stream_open("AF_INET");
    } else if (stream_family == AF_INET6){
        stream_open("AF_INET6");
    } else if (stream_family == 0) {
        return -1;
    } else {
        return -1;
    }

    if (stream_status == STREAM_CONNECT) {
        ssize_t size;
        size = sendto(stream_fd, buf, length, MSG_FASTOPEN,
                      (struct sockaddr*)&stream_peer_sockaddr,
                      stream_peer_addr_length);

        if (size <= 0) {

            STREAM_PERROR("sendto");
            stream_close();
            return -1;

        } else {

            stream_status = STREAM_CONNECT;
            stream_get_peer_sockaddr();
            return size;

        }

    } else {

        stream_close();
        return -1;

    }

    return -1;
}
#endif

ssize_t
stream::stream_send(const void* buf, size_t length, int flag)
{
    ssize_t ret;

    if (stream_status == STREAM_CONNECT) {

        ret = send(stream_fd, buf, length, flag);
        if (ret < 0) {
            STREAM_PERROR("sendto");
            stream_close();
        } else if (ret == 0) {
            stream_close();
        }
        return ret;

    } else if (stream_status == STREAM_LISTEN) {

        ret = send(stream_accept_fd, buf, length, flag);
        if (ret < 0) {
            STREAM_PERROR("sendto");
            stream_accept_close();
        } else if (ret == 0) {
            stream_accept_close();
        }
        return ret;

    } else {

        return -1;

    }
}

ssize_t
stream::stream_recv(void* buf, size_t length)
{
    if (stream_status == STREAM_CONNECT) {

        ssize_t ret = recv(stream_fd, buf, length, 0);
        if (ret < 0) {
            STREAM_PERROR("recv");
            stream_close();
        } else if (ret == 0) {
            //stream_close();
        }
        return ret;

    } else if (stream_status == STREAM_LISTEN) {

        ssize_t ret = recv(stream_accept_fd, buf, length, 0);
        if (ret < 0) {
            STREAM_PERROR("recv");
            stream_accept_close();
        } else if (ret == 0) {
            //stream_accept_close();
        }
        return ret;

    } else {

        return -1;

    }

}

bool
stream::stream_close()
{
    int ret;
    ret = close(stream_fd);
    if (ret < 0) {
        return false;
    } else {
        stream_fd = -1;
        return true;
    }
}

void stream::stream_init()
{
    if(stream_fd) {
        stream_close();
    }
    if (stream_accept_fd) {
        stream_accept_close();
    }
    stream_family = 0;
    stream_status = STREAM_UNUSED;
    memset(&stream_peer_sockaddr, 0, sizeof(stream_peer_sockaddr));
    return;
}

bool
stream::stream_accept_close()
{
    int ret;
    ret = close(stream_accept_fd);
    if (ret < 0) {
        return false;
    } else {
        stream_accept_fd = -1;
        return true;
    }
}

bool
stream::stream_reconnect()
{
STREAM_RECONNECT_LOOP:
    if (stream_family == AF_INET) {
        stream_open("AF_INET");
    } else if (stream_family == AF_INET6){
        stream_open("AF_INET6");
    } else if (stream_family == 0) {
        return false;
    } else {
        return false;
    }

    if (stream_status == STREAM_CONNECT) {
        if (connect(stream_fd,
                    (struct sockaddr*)&stream_peer_sockaddr,
                    stream_peer_addr_length) < 0) {
            STREAM_PERROR("connect");
            sleep(1);
            goto STREAM_RECONNECT_LOOP;

        } else {

            stream_status = STREAM_CONNECT;
            stream_get_peer_sockaddr();
            return true;

        }

    } else {

        return false;

    }
}

bool
stream::stream_connect(const std::string& dest_host, const std::string& dest_port)
{
    int error;
    struct addrinfo *res;
    struct addrinfo hints;

    if (stream_family == 0) {
        return false;
    }

    memset(&hints, 0, sizeof(hints));

    hints.ai_family = stream_family;
    hints.ai_socktype = SOCK_STREAM;
#ifdef __FreeBSD__
    hints.ai_flags = 0;
#else
    hints.ai_flags = AI_ALL | AI_ADDRCONFIG;
#endif

    error = getaddrinfo(dest_host.c_str(), dest_port.c_str(), &hints, &res);
    if (error) {
#ifdef DEBUG
        if (debug) {
        fprintf(stderr, "%s(%d):getaddrinfo: %s\n", __FILE__, __LINE__, gai_strerror(error));
        }
#endif
        return false;
    }

    /*
    // non-block
    if (0) {
        fcntl(sock, F_SETFL, O_NONBLOCK);
    }
    */

    if (connect(stream_fd, res->ai_addr, res->ai_addrlen) < 0) {
        if(errno == EINPROGRESS) {

            // non-block
            return true;

        } else {

            STREAM_PERROR("connect");
            stream_close();
            return false;

        }

    } else {

        freeaddrinfo(res);
        stream_status = STREAM_CONNECT;
        stream_get_peer_sockaddr();
        return true;

    }

    freeaddrinfo(res);
    stream_close();
    return false;
}

bool
stream::stream_connect(const char* dest_host, const char* dest_port)
{
    const std::string str_dest_host = std::string(dest_host);
    const std::string str_dest_port = std::string(dest_port);
    return stream_connect(str_dest_host, str_dest_port);
}

bool
stream::stream_connect(const struct sockaddr* dest_addr, socklen_t dest_length)
{
    if (dest_length > sizeof(struct sockaddr_storage)) { return false; }
    /*
    // non-block
    if (0) {
        fcntl(sock, F_SETFL, O_NONBLOCK);
    }
    */
    if (connect(stream_fd, dest_addr, dest_length) < 0) {
        if(errno == EINPROGRESS) {

            // non-block
            stream_status = STREAM_CONNECT;
            return true;

        } else {

            STREAM_PERROR("connect");
            stream_close();
            return false;

        }

    } else {

        stream_status = STREAM_CONNECT;
        stream_get_peer_sockaddr();
        return true;

    }

    stream_close();
    return false;
}

bool
stream::stream_listen(const std::string& host, const std::string& port)
{
    int error;
    struct addrinfo *res;
    struct addrinfo hints;

    if (stream_family == 0) {
        return false;
    }

    memset(&hints, 0, sizeof(hints));

    hints.ai_family = stream_family;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;

    error = getaddrinfo(host.c_str(), port.c_str(), &hints, &res);
    if (error) {
#ifdef DEBUG
        if (debug) {
        fprintf(stderr, "%s(%d):getaddrinfo: %s\n", __FILE__, __LINE__, gai_strerror(error));
        }
#endif
        return false;
    }

    if (bind(stream_fd, res->ai_addr, res->ai_addrlen) < 0) {
        STREAM_PERROR("bind");
        stream_close();
        return false;
    }

    if (listen(stream_fd, SOMAXCONN) < 0) {
        STREAM_PERROR("bind");
        stream_close();
        return false;
    }

    stream_status = STREAM_LISTEN;
    return true;
}

int
stream::stream_accept()
{
    stream_accept_addr_length = sizeof(stream_accept_sockaddr);
    //memset(&stream_accept_sockaddr, 0, sizeof(stream_accept_sockaddr));

    stream_accept_fd = accept(stream_fd,
                              (struct sockaddr*)&stream_accept_sockaddr,
                              &stream_accept_addr_length);

    if (stream_accept_fd < 0) {
        STREAM_PERROR("accept");
    }

    return stream_accept_fd;
}

struct sockaddr* stream::stream_get_peer_sockaddr()
{
    if (stream_status == STREAM_CONNECT) {

        stream_peer_addr_length = sizeof(stream_peer_sockaddr);
        if (getpeername(stream_fd, (struct sockaddr*)&stream_peer_sockaddr, &stream_peer_addr_length) < 0) {
            STREAM_PERROR("getpeername");
            return NULL;

        }

        return (struct sockaddr*)&stream_peer_sockaddr;

    } else if (stream_status == STREAM_LISTEN) {

        stream_peer_addr_length = sizeof(stream_peer_sockaddr);
        if (getpeername(stream_accept_fd,
                        (struct sockaddr*)&stream_peer_sockaddr,
                        &stream_peer_addr_length) < 0) {
            STREAM_PERROR("getpeername");
            return NULL;
        }
        return (struct sockaddr*)&stream_peer_sockaddr;
    } else {
        return NULL;
    }
}

std::string
stream::stream_get_peer_host()
{
    stream::stream_get_peer_sockaddr();
    memset(stream_buf, 0, BUFSIZ);
    int error = 0;
    error = getnameinfo((const sockaddr*)&stream_peer_sockaddr, sizeof(stream_peer_sockaddr),
                stream_buf, BUFSIZ, NULL, 0,  NI_NUMERICHOST);
    if (error != 0) {
#ifdef DEBUG
        if (debug) {
        fprintf(stderr, "%s(%d):getnameinfo: %s\n", __FILE__, __LINE__, gai_strerror(error));
        //fprintf(stderr, "%d\n", error);
        }
#endif
        return std::string("(null)");
    }
    return std::string(stream_buf);
}

std::string
stream::stream_get_peer_port()
{
    stream::stream_get_peer_sockaddr();
    memset(stream_buf, 0, BUFSIZ);
    if (stream_family == AF_INET) {
        sprintf(stream_buf, "%hu", ntohs(((struct sockaddr_in*)&stream_peer_sockaddr)->sin_port));
        return std::string(stream_buf);
    } else if (stream_family == AF_INET6) {
        sprintf(stream_buf, "%hu", ntohs(((struct sockaddr_in6*)&stream_peer_sockaddr)->sin6_port));
        return std::string(stream_buf);
    } else {
        return std::string("(null)");
    }
    return std::string(stream_buf);
}

int
stream::stream_open(const char* type)
{
    std::string str_type = type;
    return stream_open(str_type);
}

int
stream::stream_open(const std::string& type)
{
    if (type.compare("AF_INET") == 0) {

        stream_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (stream_fd == -1) {
            STREAM_PERROR("socket");
            return -1;
        }
        stream_family = AF_INET;

    } else if (type.compare("udp4") == 0) {

        stream_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (stream_fd == -1) {
            STREAM_PERROR("socket");
            return -1;
        }
        stream_family = AF_INET;

    } else if (type.compare("UDP4") == 0) {

        stream_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (stream_fd == -1) {
            STREAM_PERROR("socket");
            return -1;
        }
        stream_family = AF_INET;

    } else if (type.compare("AF_INET6") == 0) {

        stream_fd = socket(AF_INET6, SOCK_STREAM, 0);
        if (stream_fd == -1) {
            STREAM_PERROR("socket");
            return -1;
        }
        stream_family = AF_INET6;

    } else if (type.compare("udp6") == 0) {

        stream_fd = socket(AF_INET6, SOCK_STREAM, 0);
        if (stream_fd == -1) {
            STREAM_PERROR("socket");
            return -1;
        }
        stream_family = AF_INET6;

    } else if (type.compare("UDP6") == 0) {

        stream_fd = socket(AF_INET6, SOCK_STREAM, 0);
        if (stream_fd == -1) {
            STREAM_PERROR("socket");
            return -1;
        }
        stream_family = AF_INET6;

    } else {

        return -1;

    }

    int on = 1;
    if (setsockopt(stream_fd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on)) < 0) {
        STREAM_PERROR("setsockopt");
        stream_close();
        return -1;
    }

    /*
    int opt;
    socklen_t optlen = sizeof(opt);
    if (getsockopt(stream_fd, SOL_SOCKET, SO_RCVBUF, (void *)&opt, &optlen) < 0) {
        STREAM_PERROR("setsockopt");
        close(stream_fd);
        stream_fd = -1;
    } else {
        //printf("REVBUF:%d\n", opt);
        ;
    }

    if (getsockopt(stream_fd, SOL_SOCKET,  SO_SNDBUF, (void *)&opt, &optlen) < 0) {
        STREAM_PERROR("setsockopt");
        close(stream_fd);
        stream_fd = -1;
    } else {
        //printf("SNDBUF:%d\n", opt);
        ;
    }
    */

    return stream_fd;
}

int stream::get_fd()
{
    return stream_fd;
}

#endif


text:
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/style.less';

import { Provider } from 'react-redux';

import Reducers from './reducers';
import { createStore, applyMiddleware } from 'redux';
import { Router, hashHistory } from 'react-router';

import Routes from './routes';

import MainMiddleWare from './middlewares/mainMiddleWare';

const createStoreWithMiddleware = applyMiddleware(
    MainMiddleWare
)(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(Reducers) }>
        <Router history={hashHistory} routes={Routes}/>
    </Provider>,
    document.getElementById('root')
);


text:
package org.apache.camel.core.osgi;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.spi.DataFormatResolver;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ResolverHelper;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OsgiDataFormatResolver implements DataFormatResolver {
    private static final Logger LOG = LoggerFactory.getLogger(OsgiDataFormatResolver.class);

    private final BundleContext bundleContext;

    public OsgiDataFormatResolver(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }

    public DataFormat resolveDataFormat(String name, CamelContext context) {
        // lookup in registry first
        DataFormat dataFormatReg = ResolverHelper.lookupDataFormatInRegistryWithFallback(context, name);
        if (dataFormatReg != null) {
            return dataFormatReg;
        }

        return getDataFormat(name, context);
    }

    protected DataFormat getDataFormat(String name, CamelContext context) {
        LOG.trace("Finding DataFormat: {}", name);
        try {
            ServiceReference<?>[] refs = bundleContext.getServiceReferences(DataFormatResolver.class.getName(), "(dataformat=" + name + ")");
            if (refs != null) {
                for (ServiceReference<?> ref : refs) {
                    Object service = bundleContext.getService(ref);
                    if (DataFormatResolver.class.isAssignableFrom(service.getClass())) {
                        DataFormatResolver resolver = (DataFormatResolver) service;
                        return resolver.resolveDataFormat(name, context);
                    }
                }
            }
            return null;
        } catch (InvalidSyntaxException e) {
            throw ObjectHelper.wrapRuntimeCamelException(e);
        }
    }

}


text:
using Org.Apache.REEF.Wake.Remote.Proto;

namespace Org.Apache.REEF.Wake.Remote.Impl
{
    public class RemoteEventDecoder<T> : IDecoder<IRemoteEvent<T>>
    {
        private readonly IDecoder<T> _decoder;

        public RemoteEventDecoder(IDecoder<T> decoder)
        {
            _decoder = decoder;
        }

        public IRemoteEvent<T> Decode(byte[] data)
        {
            WakeMessagePBuf pbuf = WakeMessagePBuf.Deserialize(data);
            return new RemoteEvent<T>(null, null, pbuf.seq, _decoder.Decode(pbuf.data));
        }
    }
}


text:
import { VolumeDownFilledAlt20 } from "../../";

export = VolumeDownFilledAlt20;


text:
'use strict';

// dependency declaration
var express = require('express'),
    mongoClient = require('mongodb').MongoClient,
    multer = require('multer'),
    utils = require('./utils'),
    async = require('async'),
    uuid = require('uuid'),
    fs = require('fs'),
    config = require('./config');

// instance variable
var server = express(),
    upload = multer({storage: multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, config.storage_location)
        },
        filename: function (req, file, cb) {
            cb(null, utils.getRandomString(4)+
                Date.now()+
                utils.getRandomString(9)+
                utils.getExtension(file.originalname))
        }
    })}),
    port = process.env.port || config.port;

run();

function run(){

    mongoClient.connect(config.db_url, (err, db)=> {
        if (err) {
            throw err
        } else {
            var collection = db.collection(config.db_collection);

            //get request
            server.get('/', (req, res)=> {
                var reference = req.query.r;
                var query = req.query.q;
                var type = req.query.t;

                console.log(req.ip + " GET ");

                if(reference != undefined){
                    if(type == "data"){
                        collection.find({reference:reference}).toArray((err,docs)=>{
                            if(err){
                                res.send({
                                    error:true,
                                    data:"failed to query reference"
                                });
                            } else {
                                res.send({
                                    err:false,
                                    data:docs[0]
                                });
                            }
                        });
                    } else {
                        collection.find({reference:reference}).toArray((err,docs)=>{
                            if(err){
                                res.send({
                                    error:true,
                                    data:"failed to query reference"
                                });
                            } else {
                                var file = docs[0].filename;
                                res.sendFile(__dirname+"/"+config.storage_location+file, (err)=>{
                                   if(err){
                                       console.log(err);
                                   }
                                });
                            }
                        });
                    }
                } else if (query != undefined){
                    collection.find().toArray((err,docs)=>{
                        if(err){
                            res.send({
                                error:true,
                                data:"failed to query reference"
                            });
                        } else {
                            res.send({
                                error:false,
                                data:docs
                            });
                        }
                    });
                } else {
                    res.send({
                        error: true,
                        data: "reference or query not set"
                    });
                }

            });

            // post request
            server.post('/', upload.single('media'), (req, res)=> {
                var body = JSON.parse(req.body.metainfo);
                if (req.file == {} || req.file == null) {
                    res.send({
                        error: true,
                        data: "no file found"
                    });
                } else {
                    var reference = req.query.r || uuid({rng: uuid.nodeRNG});
                    console.log(req.ip + " POST uuid:"+reference);
                    var insertData = schemaConstructor(body, req.file, reference);

                    collection.insertOne(insertData, (err)=> {
                        if (err) {
                            res.send({
                                error: true,
                                data: "failed to insert reference to record"
                            });
                        } else {
                            res.send({
                                error: false,
                                data: reference
                            });
                        }
                    });

                }
            });

            // put request
            server.put('/', upload.single('media'), (req,res)=>{
                var reference = req.query.r;
                var query = req.query.q;
                var body = JSON.parse(req.body.metainfo);
                var filter = {};

                var c = false;

                if(reference != undefined){
                    filter = {reference:reference};
                    c = true;
                } else if(query != undefined){
                    filter = query;
                    c = true;
                } else {
                    res.send({
                        error:true,
                        data: "reference or query not set"
                    });
                }

                if(c){
                    console.log(req.ip + " POST filter:"+filter);

                    collection.updateMany(filter, {$set: body}, (err, docs)=>{
                        if(err){
                            res.send({
                                error: true,
                                data: "error on updating docs"
                            });
                        } else {
                            res.send({
                                error: false,
                                data: docs
                            });
                        }
                    });
                }
            });

            // del request
            server.delete('/',(req,res)=>{
                var reference = req.query.r;
                var query = req.query.q;
                var filter = {};

                var c = false;

                if(reference != undefined){
                    filter = {reference:reference};
                    c = true;
                } else if(query != undefined){
                    filter = query;
                    c = true;
                } else {
                    res.send({
                        error:true,
                        data: "reference or query not set"
                    });
                }

                if(c){
                    console.log(req.ip + " POST filter:"+filter);
                    collection.find(filter).toArray((err, docs)=>{
                        if(err){
                            res.send({
                                error:true,
                                data: "error on querying info"
                            });
                        } else {
                            var file ="";

                            try{
                                file = docs[0].filename;
                                async.parallel([
                                    function(callback){
                                        fs.unlink(__dirname+'/'+config.storage_location+file, (err, result)=>{
                                            callback(err, result);
                                        });
                                    },
                                    function(callback){
                                        collection.deleteMany(filter,(err, docs)=>{
                                            callback(err, docs);
                                        });
                                    }
                                ],(err,result)=>{
                                    if(err){
                                        res.send({
                                            error:true,
                                            data: err
                                        });
                                    } else {
                                        res.send({
                                            error:false,
                                            data: result[1]
                                        });
                                    }
                                });
                            } catch(err){
                                res.send({
                                    error:true,
                                    data:"file location not found"
                                });
                            }
                        }
                    });
                }
            });

        }
    });

    server.listen(port, (err)=>{
        if(err) throw err;
        console.log("server listening on port: "+port);
    });
}

function schemaConstructor(body,file, reference){
    var time = new Date();
    return {
        reference: reference,
        filename: file.filename,
        author: body.author || null,
        time: {
            timestamp: body.time.timestamp || time.getTime(),
            year: body.time.year || time.getFullYear(),
            month: body.time.month || time.getMonth(),
            date: body.time.date || time.getDate(),
            day: body.time.day || time.getDay(),
            hour: body.time.hour || time.getHours(),
            minute: body.time.minute || time.getMinutes(),
            second: body.time.second || time.getSeconds(),
            offset: body.time.offset || time.getTimezoneOffset()
        },
        size: file.size,
        tags: body.tags || [],
        description: body.description || null
    }
}


text:
package com.orientechnologies.orient.etl.transformer;

import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.etl.ETLBaseTest;
import com.tinkerpop.blueprints.Vertex;
import org.junit.Test;

import java.util.Iterator;

/**
 * Tests ETL Flow Transformer.
 *
 * @author Luca Garulli
 */
public class OFlowTransformerTest extends ETLBaseTest {
  @Test
  public void testSkip() {
    process("{source: { content: { value: 'name,surname\nJay,Miner\nJay,Test' } }, extractor : { row: {} },"
        + " transformers: [{csv: {}}, {vertex: {class:'V'}}, {flow:{operation:'skip',if: 'name <> \'Jay\''}},{field:{fieldName:'name', value:'3'}}"
        + "], loader: { orientdb: { dbURL: 'memory:ETLBaseTest', dbType:'graph' } } }");

    assertEquals(2, graph.countVertices("V"));

    Iterator<Vertex> it = graph.getVertices().iterator();

    Vertex v1 = it.next();
    Object value1 = v1.getProperty("name");
    assertEquals("3", value1);

    Vertex v2 = it.next();
    Object value2 = v2.getProperty("name");
    assertEquals("3", value2);
  }

  @Test
  public void testSkipNever() {
    process("{source: { content: { value: 'name,surname\nJay,Miner\nTest,Test' } }, extractor : { row: {} },"
        + " transformers: [{csv: {}}, {vertex: {class:'V'}}, {flow:{operation:'skip',if: 'name = \'Jay\''}},{field:{fieldName:'name', value:'3'}}"
        + "], loader: { orientdb: { dbURL: 'memory:ETLBaseTest', dbType:'graph'} } }");

    assertEquals(2, graph.countVertices("V"));

    Iterator<Vertex> it = graph.getVertices().iterator();

    Vertex v1 = it.next();
    Object value1 = v1.getProperty("name");
    assertEquals("Jay", value1);

    Vertex v2 = it.next();
    Object value2 = v2.getProperty("name");
    assertEquals("3", value2);
  }
}


text:
<?php

return [
    'interfaces' => [
        'google.ads.googleads.v12.services.RecommendationService' => [],
    ],
];


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equif="X-UA-Compatible" content="IE=edge, chrome=1">
		<title><?php echo $page_title ?></title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width">
		<link rel="stylesheet" href="<?php echo base_url(); ?>template/css/bootstrap.css">
		<link rel="stylesheet" href="<?php echo base_url(); ?>template/css/style.css">
		<link rel="stylesheet" href="<?php echo base_url(); ?>template/css/detail-ticket.css">
		<link rel="stylesheet" href="<?php echo base_url(); ?>template/css/fonts.css">

<a href="<?php echo base_url(); ?>"><img src="<?php echo base_url(); ?>template/img/logo-white.png" width="160px">


text:
<?php

declare(strict_types=1);

namespace Browscap\Data;

/**
 * @phpstan-type BrowserType 'application'|'bot'|'bot-syndication-reader'|'bot-trancoder'|'browser'|'email-client'|'feed-reader'|'library'|'multimedia-player'|'offline-browser'|'tool'|'transcoder'|'useragent-anonymizer'|'unknown'
 * @phpstan-type BrowserProperties array{Browser?: string, Browser_Maker?: string}
 * @phpstan-type BrowserData array{properties?: BrowserProperties, standard: bool, lite: bool, type: BrowserType}
 */
class Browser
{
    /** @phpstan-var BrowserType */
    private string $type;

    /**
     * @var array<string, string>
     * @phpstan-var BrowserProperties
     */
    private array $properties = [];

    private bool $isLite = false;

    private bool $isStandard = false;

    /**
     * @param array<string, string> $properties
     * @phpstan-param BrowserProperties $properties
     * @phpstan-param BrowserType $type
     *
     * @throws void
     */
    public function __construct(array $properties, string $type, bool $isLite, bool $standard)
    {
        $this->type       = $type;
        $this->properties = $properties;
        $this->isLite     = $isLite;
        $this->isStandard = $standard;
    }

    /**
     * @phpstan-return BrowserType
     *
     * @throws void
     */
    public function getType(): string
    {
        return $this->type;
    }

    /**
     * @return array<string, string>
     * @phpstan-return BrowserProperties
     *
     * @throws void
     */
    public function getProperties(): array
    {
        return $this->properties;
    }

    /**
     * @throws void
     */
    public function isLite(): bool
    {
        return $this->isLite;
    }

    /**
     * @throws void
     */
    public function isStandard(): bool
    {
        return $this->isStandard;
    }
}


text:
package com.twitter.scalding.db.extensions

import com.twitter.scalding.db._

object VerticaExtensions {
  def verticaMutator: PartialFunction[DBColumnDefinition, DBColumnDefinition] = {
    case t @ DBColumnDefinition(BIGINT, _, _, None, _, _)   => t.copy(sizeOpt = None)
    case t @ DBColumnDefinition(INT, _, _, None, _, _)      => t.copy(sizeOpt = None)
    case t @ DBColumnDefinition(SMALLINT, _, _, None, _, _) => t.copy(sizeOpt = None)
    case t @ DBColumnDefinition(BOOLEAN, _, _, None, _, _)  => t.copy(sizeOpt = None)
    case t @ DBColumnDefinition(TINYINT, _, _, None, _, _)  => t.copy(sizeOpt = None)
    case t @ DBColumnDefinition(DOUBLE, _, _, _, _, _) => t.copy(sqlType = SqlTypeName("DOUBLE PRECISION"))
  }
}


text:
namespace engine {

class RemoveComponentsOnDeathSystem : public System
{
public:
    DEFINE_SYSTEM_BASE( RemoveComponentsOnDeathSystem )
    RemoveComponentsOnDeathSystem();
protected:
    virtual void Init();
    virtual void Update( double DeltaTime );
private:
    Scene& mScene;
};

} // namespace engine

#endif//INCLUDED_ENGINE_REMOVE_COMPONENTS_ON_DEATH_SYSTEM_H

//command:  "classgenerator" -g "system" -c "remove_components_on_death_system" -t "remove_components_on_death"


text:
jest.mock(`../../../utils/sidebar/item-list`, () => {
  return {
    itemListContributing: {
      title: `Contributing`,
      items: [
        {
          title: `Why Contribute to Gatsby?`,
          link: `/contributing/why-contribute-to-gatsby/`,
        },
        {
          title: `Gatsby's Governance Model*`,
          link: `/contributing/gatsby-governance-model/`,
        },
      ],
    },
    itemListDocs: {
      title: `Documentation`,
      items: [
        {
          title: `Introduction`,
          link: `/docs/`,
        },
      ],
    },
  }
})
jest.mock(`react-modal`, () => {
  const modal = jest.fn().mockImplementation(({ children }) => children)
  modal.setAppElement = jest.fn()
  return modal
})
import React from "react"
import { useStaticQuery } from "gatsby"
import { render } from "react-testing-library"

import StubList from "../stub-list"

let location
beforeEach(() => {
  useStaticQuery.mockReturnValueOnce({
    site: {
      siteMetadata: {
        title: `GatsbyJS`,
      },
    },
  })
  location = {
    pathname: `/contributing/stub-list`,
  }
})

describe(`StubList`, () => {
  it(`shows a title`, () => {
    const { getByText } = render(<StubList location={location} />)
    const element = getByText(`Stub List`)

    expect(element).toBeVisible()
  })

  it(`shows a call to action to edit stubs`, () => {
    const { getByText } = render(<StubList location={location} />)

    expect(getByText(`How to Write a Stub`)).toBeVisible()
  })

  describe(`stubs`, () => {
    let stubs
    beforeEach(() => {
      const { getByTestId } = render(<StubList location={location} />)
      stubs = getByTestId(`list-of-stubs`).querySelectorAll(`li`)
    })

    it(`renders stubs`, () => {
      expect(stubs.length).toBeGreaterThan(0)
    })

    it(`renders links to stubs`, () => {
      Array.from(stubs).forEach(stub => {
        const anchor = stub.firstChild
        expect(anchor.nodeName).toBe(`A`)
        expect(anchor.getAttribute(`href`)).toMatch(/^\//)
      })
    })

    it(`removes the asterisks`, () => {
      Array.from(stubs).forEach(stub => {
        expect(stub.textContent).not.toContain(`*`)
      })
    })
  })
})


text:
import { matches } from "./dom"

const toArray = e => Array.prototype.slice.call(e)

const serializeElement = (element, additionalParam) => {
  let inputs = [element]
  if (matches(element, "form")) { inputs = toArray(element.elements) }
  const params = []

  inputs.forEach(function(input) {
    if (!input.name || input.disabled) { return }
    if (matches(input, "fieldset[disabled] *")) { return }
    if (matches(input, "select")) {
      toArray(input.options).forEach(function(option) {
        if (option.selected) { params.push({name: input.name, value: option.value}) }
      })
    } else if (input.checked || (["radio", "checkbox", "submit"].indexOf(input.type) === -1)) {
      params.push({name: input.name, value: input.value})
    }
  })

  if (additionalParam) { params.push(additionalParam) }

  return params.map(function(param) {
    if (param.name) {
      return `${encodeURIComponent(param.name)}=${encodeURIComponent(param.value)}`
    } else {
      return param
    }}).join("&")
}

// Helper function that returns form elements that match the specified CSS selector
// If form is actually a "form" element this will return associated elements outside the from that have
// the HTML form attribute set
const formElements = (form, selector) => {
  if (matches(form, "form")) {
    return toArray(form.elements).filter(el => matches(el, selector))
  } else {
    return toArray(form.querySelectorAll(selector))
  }
}

export { serializeElement, formElements }


text:
using System;
using System.ServiceModel;
using Common;

namespace SyncService
{
    [MessageContract]
    public class RemoteFileInfo : IDisposable
    {
        [MessageHeader(MustUnderstand = true)]
        public ItemMetadata Metadata;

        [MessageHeader(MustUnderstand = true)]
        public long Length;

        [MessageBodyMember(Order = 1)]
        public System.IO.Stream FileByteStream;

        public void Dispose()
        {
            if (FileByteStream != null)
            {
                FileByteStream.Close();
                FileByteStream = null;
            }
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN
@interface HexUtil : NSObject

+ (NSString *) format:(NSData *)aData;
+ (NSString *) prettyFormat:(NSData *)aData;

+ (NSData * _Nullable) parse:(NSString *)aHex __deprecated NS_SWIFT_UNAVAILABLE("");
+ (NSData *) parse:(NSString *)aHex error:(NSError **)error;

+ (NSString *)format:(NSData *)data offset:(uint)offset len:(NSUInteger)len;
@end
NS_ASSUME_NONNULL_END


text:
#include "wsinit.h"
#include "../exception.h"

namespace basin {

	class WinSockInit : public WSADATA {
	public:
		WinSockInit() {
			WORD wVersionRequested;
			int err;

			wVersionRequested = MAKEWORD(2, 2);
			err = WSAStartup(wVersionRequested, this);
			if (err != 0) {
				/* Tell the user that we could not find a usable */
				/* WinSock DLL.                                  */
				throw SystemException("Unable to initialize WinSock interface", err);
			}

			if (LOBYTE(wVersion) != 2 ||
				HIBYTE(wVersion) != 2) {
				/* Tell the user that we could not find a usable */
				/* WinSock DLL.                                  */
				WSACleanup();
				throw SystemException("WinSock version 2.2 or better is required", 2);
			}
		}

		~WinSockInit() {
			WSACleanup();
		}
	};

	const WSADATA &initWinSock() {
		static WinSockInit data;
		return data;

	}

}


text:
@implementation MHSelectPickerView

- (void)awakeFromNib{
    [super awakeFromNib];
    _lineWidth.constant = 1;
    _lineHeight.constant = 0.5;
}

@end


text:
package bpmntoconstant.generator.annotations.provider;

import org.apache.maven.model.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.util.*;

public class BpmnResourceScanningProvider {

    private final PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
    private List<org.springframework.core.io.Resource> bpmnFiles = new ArrayList<>();

    public BpmnResourceScanningProvider(List<Resource> resources) {
        Optional.of(resources).ifPresent(resourceList -> {
            resourceList.forEach(resource -> {
                try {
                    org.springframework.core.io.Resource[] matchingResources = resourcePatternResolver.getResources(buildLocationPattern(resource));
                    bpmnFiles.addAll(Arrays.asList(matchingResources));
                } catch (Exception e) {
                    throw new IllegalArgumentException(e);
                }
            });
        });
    }

    private String buildLocationPattern(Resource resource) {
        return "file:///" + resource.getDirectory() + "/**/*.bpmn";
    }

    public Collection<org.springframework.core.io.Resource> getCandidates() {
        return bpmnFiles;
    }
}


text:
import re
import string
import utility
from commands import Command

def system_status(product_id, store_id):
	# Fetch the web page
	url = "http://systembolaget.se/SokDrycker/Produkt?VaruNr=" + product_id + \
			"&Butik=" + store_id
	response = utility.read_url(url)
	if response:
		data = response["data"].replace("\r", "")
	else:
		return "Ingen produkt med det artikelnumret hittades."

	# Look for title
	title_pattern = "class=\"rubrikstor\"\>(.+)\n"
	title_match = re.search(title_pattern, data)

	if not title_match:
		# Failure
		return "Hittade inte produktinfon :("

	# Set product info and store name variables
	title_text = title_match.group(1)

	origin_pattern = "class=\"text_tabell_rubrik\"\>Land\<\/td\>[\n\s]+\(\\)?([\w\s]+)(\<\/A\>\<\/B\>)?\<\/td\>"
	origin_text = re.search(origin_pattern, data).group(2)

	percentage_pattern = "class=\"text_tabell_rubrik\"\>Alkoholhalt\<\/td\>[\n\s]+\(.+?)\<\/td\>"
	percentage_text = re.search(percentage_pattern, data).group(1).replace(",", ".")

	store_pattern = "\<option selected=\"selected\" value=\"" + store_id + "\"\>(.+?)\<\/option\>"
	store_text = re.search(store_pattern, data).group(1)

	# Look for available packaging options for this product
	product_pattern = "\<img src=\"\/images\/button_plus\.gif\" class=\"LaggTillMinaVaror\" " + \
			"align=\"absmiddle\" onMouseover=\"ddrivetip\(\'L.gg till i \Mina varor\<\/b\>\'\)\" " + \
			"onMouseout=\"hideddrivetip\(\)\" onClick=\"LaggTillEnArtikel\(\'\d+\'\);\"\>" + \
			"(.+?)" + "\<\/td\>\" + \
			"([\w\s]+)" + "\<\/td\>\" + \
			"\((.+?)\)" + "\<\/td\>\" + \
			"(.+?)" + "\<\/td\>\.*?\<\/td\>" + \
			"\" + \
			"\Lagersaldo: \<\/strong\>(\d+) st   \" + \
			"Plats i butiken: \<\/strong\>(.+?)\<\/td\>"
	product_iterator = re.finditer(product_pattern, data)
	product_list = []

	for match in product_iterator:
		# An available packaging option has been found, let's calculate the APK value.
		apk_value = float(percentage_text[:-2]) / 100  # He
		apk_value *= float(match.group(2)[:-3])        # V (expected to be in ml)
		apk_value /= float(match.group(4))             # P

		# Add it to the list...
		format_string = "%s %s: %s kr (%s kr/l, APK " + str(round(apk_value, 2)) + \
				"), %s st, hylla %s"
		product_list.append(format_string % match.group(1, 2, 4, 3, 5, 6))

	if not product_list:
		# No available packaging options found
		product_list.append("Varan finns inte i denna butik.")

	# Assemble string
	result_string = "#%s: %s, %s, %s | %s | %s | %s" % \
			(product_id, title_text, origin_text, percentage_text, store_text, " | ".join(product_list), url)

	# Unescape things like
	return utility.unescape(result_string)

class SystembolagetCommand(Command):
	usage = "Användning: .system id <artikelnummer>"

	def __init__(self):
		pass

	def trig_system(self, bot, source, target, trigger, argument):
		"""Information om systembolagets produkter. Mer funktionalitet kommer framöver!"""

		argument = argument.strip().lower()
		args = argument.split(' ', 1)

		if not args[0]:
			return self.usage

		elif args[0] == 'id':
			if (len(args) < 2) or (not args[1].isdigit()):
				return "Du måste ange ett artikelnummer!"
			else:
				return system_status(args[1], str(110)) # TODO: more stores

		else:
			return "Mer funktioner kommer framöver! " + self.usage


text:
package migrations

import com.datastax.spark.connector.SomeColumns
import com.mongodb.spark.MongoSpark
import com.mongodb.spark.rdd.MongoRDD
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.bson.Document
import com.datastax.spark.connector._
import utils.HybridSparkContext

/**
  * Created by jyothi on 12/12/16.
  */
object ComplexMigration extends HybridSparkContext{

  def main(args: Array[String]): Unit = {
    val db = "jyothi"

    /**
      * users schema: {
            "_id" : String,
            "sdk_version" : 1.0,
            "app_info" : {
                "bundle_id" : String,
                "app_name" : String,
                "app_version" : String,
                "app_mode" : String
            },
            "device_info" : {
                "device_uuid" : String,
                "custom_user_id" : String,
                "hardware_model" : String,
                "os_version" : String,
                "device_dimensions" : {
                    "height" : Int,
                    "width" : Int
                }
            },
            "user_info" : {
                "countryId" : String,
                "langId" : String,
                "stateId" : String
            }
        }
      */
    val collection = "users"

    println("getting Hybrid Spark Context")
    val sparkContext = getHybridSparkContext(db, collection) // uses default host

    println("Retrieving data from Mongo...")
    val users = MongoSpark.load(sparkContext)

    println("****************From Mongo Spark Context*****************")
    println("NO: of User Records:: " + users.count())

    println("User Record:: " + users.first.toJson)

    //Migration of samples collection to Cassandra Samples Table
    val keySpace = "jyothi"
    /**
      * //Schema is FLATTEN STRUCTURE in Cassandra Table
      * CREATE TABLE users(
      *   id text PRIMARY KEY,
      *   sdk_version float,
      *   -_-_-_-_-_-_-_-_-_--_-_-_- APP_INFO
      *   app_bundle_id text,
      *   app_name text,
      *   app_version text,
      *   app_mode text,
      *   -_-_-_-_-_-_-_-_-_--_-_-_- DEVICE_INFO
      *   device_uuid text,
      *   custom_user_id text,
      *   hardware_model text,
      *   os_version text,
      *   device_height int,
      *   device_width int,
      *   -_-_-_-_-_-_-_-_-_--_-_-_- USER_INFO
      *   countryId text,
      *   langId text,
      *   stateId text
      *
      * )
      */
    val table = "users"

    val mongoCassandraKeyMapper = Map[String, String]( //FIXME: use it properly
      "_id" -> "id",
      "sdk_version" -> "sdk_version",

      "app_info.bundle_id" -> "app_bundle_id",
      "app_info.app_name" -> "app_name",
      "app_info.app_version" -> "app_version",
      "app_info.app_mode" -> "app_mode",

      "device_info.device_uuid" -> "device_uuid",
      "device_info.custom_user_id" -> "custom_user_id",
      "device_info.hardware_model" -> "hardware_model",
      "device_info.os_version" -> "os_version",
      "device_info.device_dimensions.height" -> "device_height",
      "device_info.device_dimensions.width" -> "device_width",

      "user_info.countryId" -> "countryId",
      "user_info.langId" -> "langId",
      "user_info.stateId" -> "stateId"
    )

    val tableColumns = SomeColumns(
      "id",
      "sdk_version",
      "app_bundle_id",
      "app_name",
      "app_version",
      "app_mode",
      "device_uuid",
      "custom_user_id",
      "hardware_model",
      "os_version",
      "device_height",
      "device_width",
      "countryid",
      "langid",
      "stateid"
    )

    try {
      saveRDDToCassandra(users, sparkContext, keySpace, table, tableColumns)
    } catch {
      case e: Exception => Seq[String](); println("Exception raised....> " + e)
      case _ => println("****************Other Exception*****************")
    }
    println("Saving RDD to cassandra table...")

    val cassandraUsers = sparkContext.cassandraTable(keySpace, table)

    println("****************From Cassandra Spark Context*****************")
    println("NO: of User Records inserted:: " + cassandraUsers.count())

    println("User Record:: " + cassandraUsers.first)

  }

  /**
    * Converts MongoRDD into Cassandra Context supporting RDD (Applicable for small length records)
    * @param mongoRDD MongoRDD
    * @param sc cassandra Context
    * @return
    */
  def saveRDDToCassandra(mongoRDD: MongoRDD[Document], sc: SparkContext, keySpace: String, table: String, tableColumns: SomeColumns) {

    val emptyDocument = Document.parse("{}")
    mongoRDD.map(document => { //FIXME: need elegant code here to reduce this boilerplate
      val appInfo = document.getOrDefault("app_info", emptyDocument).asInstanceOf[Document]
      val deviceInfo = document.getOrDefault("device_info", emptyDocument).asInstanceOf[Document]
      val userInfo = document.getOrDefault("user_info", emptyDocument).asInstanceOf[Document]
      val deviceDimensions = deviceInfo.getOrDefault("device_dimensions", emptyDocument).asInstanceOf[Document]
      (
        document.getString("_id"),
        document.getDouble("sdk_version").toFloat,
        appInfo.getString("bundle_id"),
        appInfo.getString("app_name"),
        appInfo.getString("app_version"),
        appInfo.getString("app_mode"),
        deviceInfo.getString("device_uuid"),
        deviceInfo.getString("custom_user_id"),
        deviceInfo.getString("hardware_model"),
        deviceInfo.getString("os_version"),
        deviceDimensions.getInteger("height"),
        deviceDimensions.getInteger("width"),
        userInfo.getString("countryId"),
        userInfo.getString("langId"),
        userInfo.getString("stateId")
      )
    }).saveToCassandra(keySpace, table, tableColumns)
  }

}


text:
package io.github.benas.unixstream;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.function.Supplier;

/**
 * Supplier that generates an infinite stream from the standard input.
 *
 * @author Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
 */
class StandardInputSupplier implements Supplier<String> {

    private BufferedReader bufferedReader;

    StandardInputSupplier(BufferedReader bufferedReader) {
        this.bufferedReader = bufferedReader;
    }

    @Override
    public String get() {
        try {
            return bufferedReader.readLine();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
from PIL import Image, ImageSequence
with Image.open('111.gif') as im:
	if im.is_animated:
		frames = [f.copy() for f in ImageSequence.Iterator(im)]
		frames.reverse()
		frames[0].save('222.gif', save_all=True, append_images=frames[1:])


text:
function vl_sift(img::AbstractImageDirect;
                 verbose = false,
                 octaves = -1, # Maximum possible
                 levels = 3,
                 firstOctave = 0,
                 edgeThreshold = -1.0,
                 peakThreshold = -1.0,
                 normThreshold = -1.0,
                 magnif = -1.0,
                 windowSize = -1.0,
                 floatDescriptors = false)
  imgData = data(float32(convert(Array, convert(Image{Gray}, img))))

  frames = Array(Float64, 4, 0)
  if floatDescriptors
    descriptors = Array(Float32, 128, 0)
  else
    descriptors = Array(UInt8, 128, 0)
  end

  filterPtr = vl_sift_new(height(img), width(img), octaves, levels, firstOctave)
  filter = unsafe_load(filterPtr)
  if peakThreshold >= 0 filter.peak_thresh = peakThreshold end
  if edgeThreshold >= 0 filter.edge_thresh = edgeThreshold end
  if normThreshold >= 0 filter.norm_thresh = normThreshold end
  if magnif        >= 0 filter.magnif      = magnif end
  if windowSize    >= 0 filter.windowSize = windowSize end
  unsafe_store!(filterPtr, filter)
  if verbose
    println("vl_sift: filter settings:")
    println("vl_sift:   octaves      (O)      = $(filter.O)")
    println("vl_sift:   levels       (S)      = $(filter.S)")
    println("vl_sift:   first octave (o_min)  = $(filter.o_min)")
    println("vl_sift:   edge thresh           = $(filter.edge_thresh)")
    println("vl_sift:   peak thresh           = $(filter.peak_thresh)")
    println("vl_sift:   norm thresh           = $(filter.norm_thresh)")
    println("vl_sift:   magnif                = $(filter.magnif)")
    println("vl_sift:   window size           = $(filter.windowSize)")
  end
  # Process each octave
  noctaves = filter.O
  for o = filter.o_min:filter.O-1
    if verbose
      println("vl_sift: processing octave $o");
    end
    if o == filter.o_min
      err = vl_sift_process_first_octave(filterPtr, pointer(imgData))
    else
      err = vl_sift_process_next_octave(filterPtr)
    end
    if err != VL_ERR_OK
      break
    end
    if verbose
      println("vl_sift: GSS octave $(unsafe_load(filterPtr).o_cur) computed");
    end
    vl_sift_detect(filterPtr)
    filter = unsafe_load(filterPtr)
    if verbose
      println("vl_sift: detected $(filter.nkeys) (unoriented) keypoints")
    end
    # Process each keypoint
    for i = 1:filter.nkeys
      keypoint = unsafe_load(filter.keys, i)
      keypointPtr = filter.keys + (i-1)*sizeof(VlSiftKeypoint)
      orientations = Array(Float64, 4)
      norientations = vl_sift_calc_keypoint_orientations(filterPtr, orientations, keypointPtr)
      # Process each orientation
      for q = 1:norientations
        # Compute descriptor (if necessary)
        # if nout > 1
        rdescriptor = Array(vl_sift_pix, 128, 1)
        vl_sift_calc_keypoint_descriptor(filterPtr, rdescriptor, keypointPtr, orientations[q])
        descriptor = Array(vl_sift_pix, 128, 1)
        transpose_descriptor(descriptor, rdescriptor)
        # end
        frame = [keypoint.y+1; keypoint.x+1; keypoint.sigma; pi/2-orientations[q]]
        frames = [frames frame]
        descriptor = 512.0*descriptor
        if !floatDescriptors
          descriptor[descriptor .> 255] = 255.0
          descriptor = uint8(descriptor)
        end
        descriptors = [descriptors descriptor]
      end
    end
  end
  vl_sift_delete(filterPtr)
  if verbose
    println("vl_sift: found $(size(frames,2)) keypoints")
  end
  (frames, descriptors)
end

function transpose_descriptor(dst::Array, src::Array)
  BO = 8 # number of orientation bins
  BP = 4 # number of spatial bins

  for j = 0:BP-1
    jp = BP - 1 - j
    for i = 0:BP-1
      o  = BO * i + BP*BO * j
      op = BO * i + BP*BO * jp
      dst[op + 1] = src[o + 1]
      for t = 1:BO-1
        dst[BO - t + op + 1] = src[t + o + 1]
      end
    end
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <wicket:head>
    	<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <title>yahoo-bbauth</title>
    </wicket:head>

Welcome  log inlog off

        <wicket:child/>


text:
A CouchDB Client for Node.js

[![Build Status](https://travis-ci.org/CompassitesSoftware/charpoy.svg?branch=development)](https://travis-ci.org/CompassitesSoftware/charpoy)


text:
<?php

	class Institution extends AppModel
	{
		var $name="Institution";
		public $hasMany = 'Event';
	}

?>


text:
module TransamAccounting
  VERSION = "2.10.0-rc.2"
end


text:
set -x

# Fail script on error.
set -e

pkgname=linuxbrew
basedir=/opt
profiledir=/etc/profile.d
pkginstalldir=${basedir}/${pkgname}
installprefix=${pkginstalldir}

cd ${basedir}
git clone https://github.com/Linuxbrew/brew.git ${pkginstalldir}

cat <<- _END_ > ${profiledir}/${pkgname}.sh
export PATH=${installprefix}/bin:\$PATH
export MANPATH=${installprefix}/share/man:\$MANPATH
export INFOPATH=${installprefix}/share/info:\$INFOPATH
_END_

. ${profiledir}/${pkgname}.sh

# add repositories
# homebrew/science provides r, rstudio-server
brew tap homebrew/science
brew tap linuxbrew/xorg

# install common codes
brew install cmake
brew install boost
brew install r
brew install rstudio-server
brew install python
#brew install libffi


text:
import os, pytz, settings , re
from datetime import datetime, timedelta
from dateparser import parse

from nltk import word_tokenize
from .pull_schedule_utils import format_time, parse_schedule_json

from datetimes_utils import getTodayDatetime, getTodayString, converDatetimeToHumanReadable
from messages import stanfordcorenlpServerFailed, failedParsingMsg, databaseFailed, avail_update_message, pull_schedule_single_notification

from nlp_parsing.normalize_text import pre_parse_normalize
from nlp_parsing.standcorenlp import stanfordcorenlp

from querying_requests.utils import send_data_server, print_green, print_red

from bot_programs.schedule_interface import *
from bot_programs.request_user_schedule import pull_user_schedule
from slack_response_messages import send_slack_response
from .jobs import addJob, getCurrentUserJob, deleteCurrentUserInJobs

from querying_requests.utils import send_data_server

followUpAvailByDay = 0
lastAvailMsg = ""
t_day = "friday" #default

def isAvailByDayRequest(userInput):
	toked = word_tokenize(userInput)
	if len(toked) < 2 or (toked[0] != "avail" and toked[0] != "update"):
		return False

	targetDay = toked[1]
	for day in settings.weekdays:
		if targetDay in day:
			return True
	return False

def isUpdateAvailRequest(currentUserSlackId, userInput):
	retvalJob = getCurrentUserJob(currentUserSlackId)

	if "update" in userInput or isAvailByDayRequest(userInput) or (retvalJob != None and retvalJob.currentJob == "update day"):
		if retvalJob != None and retvalJob.currentJob != "update day": # delete if not this program
			deleteCurrentUserInJobs(currentUserSlackId)
		return True
	return False

def sendChannelUpdateNotification(currentUserSlackId, schedule_text, schedule_attach):
	# find channel this user is in and send notification
	for channel in settings.channel_list:
		members = settings.channel_list[channel]
		if currentUserSlackId in members and "team" in channel:
			settings.slack_client.api_call("chat.postMessage", channel="#"+channel, text=schedule_text, attachments=schedule_attach, as_user=True)

def sendScheduleUpdateNotificationToAdmins(currentUserSlackId, inputChannel, update_info):
	if currentUserSlackId == "U5F4CLYCA":
		return # dont send dev notifcations

	# send to management
	management_slackids = settings.get_management_slackids()
	for slackid in management_slackids:
		if currentUserSlackId == slackid: # do not send a notif to the same user
			continue
		send_slack_response(slackid, None, pull_schedule_single_notification(update_info))

def avail_init(currentUserSlackId, userInput, channel):
    global t_day
    global followUpAvailByDay
    global lastAvailMsg

    retvalJob = getCurrentUserJob(currentUserSlackId)
    if retvalJob != None and retvalJob.currentJob == "update day":#if followUpAvailByDay: # check for job
        try:
            avail_by_day_response(currentUserSlackId, userInput, channel)
            deleteCurrentUserInJobs(currentUserSlackId)
            return None, None, None, None
        except:
            return None, None, None, "Try Again!\n\n" + "When will you be here " + lastAvailMsg.capitalize() + "'s?"

    if isAvailByDayRequest(userInput): # user wants to change only a specific day
        toked = word_tokenize(userInput)
        target_day = toked[1]
        target_day = pre_parse_normalize(target_day)
        t_day = target_day.strip()
        lastAvailMsg = target_day.strip()
        addJob(currentUserSlackId, "update day", target_day.strip())
        text_response = "What time will you be here " + (target_day.strip()).capitalize() + "'s?"
        send_slack_response(channel, text_response, avail_update_message)
        return None, None, None, None
    else: # user wants to change by the week
        delete_user(currentUserSlackId)
        retval_dates, retval_users, retval_actions, retval_errors, retval_msg = \
        interface(userInput, currentUserSlackId, channel)
        lastAvailMsg = retval_msg
        return retval_dates, retval_users, retval_actions, retval_msg

def convert_datetimes_and_hours(datetimes):
	if datetimes[0][0] == datetimes[0][1]:
		return "Absent", 0.0

	retval_hours = 0.0
	retval_times = ""
	for times in datetimes:
		startTime = parse(times[0])
		endTime = parse(times[1])

		retval_times += format_time(startTime) + ' - ' + format_time(endTime)

		startTimeFloat = float(startTime.hour) + float("{0:.2f}".format(startTime.minute/60))
		endTimeFloat = float(endTime.hour) + float("{0:.2f}".format(endTime.minute/60))
		retval_hours += endTimeFloat - startTimeFloat

	return retval_times, "{0:.2f}".format(retval_hours)

def get_update_info(currentUserSlackId, inputChannel, new_time):
	d = {}

	# get name
	d["name"] = settings.get_user_full_name(currentUserSlackId)

	# target day
	d["target_day"] = str(t_day.capitalize())

	# get last updated datetime
	current_dtime = getTodayDatetime()
	d["update_datetime"] = current_dtime.strftime('%A \n %h %d at %-I:%M%P')

	# get new time and total hours
	string_times, total_hours = convert_datetimes_and_hours(new_time)
	# set
	d["new_time"] = string_times
	d["total hours"] = str(total_hours)

	# get previous time
	ret1, ret2 = pull_user_schedule("is <@"+currentUserSlackId+"> here " + t_day, currentUserSlackId, None)
	normalize_previous_time = ret2[0]['text'].replace("~", "")
	d["previous_time"] = '~'+ normalize_previous_time +'~'

	# color
	if d["total hours"] == "0.0":
		d["color"] = '#ff0000'
	else:
		d["color"] = '#33cc33'

	# get profile url
	d["profile_url"] = settings.slack_users_metadata[currentUserSlackId][3]

	return d

def avail_by_day_response(currentUserSlackId, userInput, channelInput):
    global followUpAvailByDay
    retval = []
    user_mdata = settings.get_user_by_slackid(currentUserSlackId)

    absent = ['none', 'absent', 'gone']
    if userInput in absent or "" == userInput:
        in_time = '00:00:00'
        out_time = '00:00:00'
        retval.append([in_time, out_time])
    else:
         toked_times = userInput.split(',')

         for time_period in toked_times:
             retval_dates, retval_users, retval_actions, retval_errors =\
             stanfordcorenlp(time_period)
             if retval_dates == None:
                 # delete job
                 print_red("\t[ ERROR ]\t" + "[ request_avail_update.py ]\t" + "[ " + userInput + " ]")
                 deleteCurrentUserInJobs(currentUserSlackId)
                 send_slack_response(channelInput, None, stanfordcorenlpServerFailed)
                 return None, None, None, None #"stanfordcorenlp server down, try again later"

             in_time = (retval_dates[0])[0].strftime("%H:%M") + ':00'
             out_time = (retval_dates[0])[1].strftime("%H:%M") + ':00'
             retval.append([in_time, out_time])

    current_dtime = str(getTodayDatetime())

    # get update information
    update_info = get_update_info(currentUserSlackId, channelInput, retval)

    # database error
    if update_info == None:
	    # delete job
        print_red("\t[ ERROR ]\t" + "[ request_avail_update.py ]\t" + "[ " + userInput + " ]")
        deleteCurrentUserInJobs(currentUserSlackId)
        send_slack_response(channelInput, None, databaseFailed)
        return None, None, None, None

    post_payload = "{\"query\":\"mutation stuff($id: UserUpdateInput){\\n  updateUser(input: $id){\\n    id\\n  }\\n}\",\"variables\":{\"id\":{\"id\":" + str(user_mdata[1]) + ",\"data\":{\"updatedAt\":\"" + current_dtime + " GMT+0000 (UTC)\",\"trelloId\":\"nothing\",\"createdAt\":\"Tue May 01 2018 01:00:19 GMT+0000 (UTC)\",\"slackId\":\"" + str(currentUserSlackId) + "\",\"Schedule\":{\"" + str(t_day) + "\":[\""

    settings.log.debug(retval)

    i = 1
    for time_period in retval:
        delim = "\",\""
        if i == len(retval):
            delim = ""

        post_payload += str(time_period[0]) + "\",\"" + str(time_period[1]) + delim
        i += 1

    post_payload += "\"]}}}},\"operationName\":\"stuff\"}"

    serverResponse = try_to_send_mutation_to_server(post_payload)

    followUpAvailByDay = 0

    sendScheduleUpdateNotificationToAdmins(currentUserSlackId, channelInput, update_info)
    send_slack_response(currentUserSlackId, None, pull_schedule_single_notification(update_info))

    return None, None, None, None

def tryToUpdateAvailByWeek(currentUserSlackId, userInput, channelInput):
	# update for week, NEED to add to job.py array

	global lastAvailMsg
	if "quit" in userInput or "stop" in userInput or "q" in userInput:
		delete_user(currentUserSlackId)
		send_slack_response(channelInput, "Okay, will do!", None)
		return None, None, None, None

	user_mdata = get_user(currentUserSlackId)
	user_state = user_mdata[1]
	if user_state != -1:
		retval_dates, retval_users, retval_actions, retval_errors, retval_msg = \
		interface(userInput, currentUserSlackId, channelInput)
		lastAvailMsg = retval_msg

		# this should be a temporary trigger... need to refactor
		if retval_msg != None and ":fire:" in retval_msg:
			sendScheduleUpdateNotificationToAdmins(currentUserSlackId, channelInput, None)

		return retval_dates, retval_users, retval_actions, retval_msg


text:
package com.viki.crawlConfig.mapper;

import com.viki.crawlConfig.bean.WebsiteConfig;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.HashMap;
import java.util.List;

/**
 * Created by Viki on 2017/5/26.
 */
@Mapper
public interface WebsiteConfigMapper {

    @Select("select * from t_website_config order by domain desc")
    public abstract List<WebsiteConfig> getList(HashMap<String,Object> params);

    @Insert("insert into t_website_config(\n" +
            "entranceUrl,titleXpath,postdateXpath,postdateFormat,contentXpath,encoding," +
            "webName,groupName,domain,crawling_interval,stopSeconds,urlSourceNorm,urlPattern," +
            "urlREPOrigin,urlREPReplacement,urlPrefix,`status`,postDate_is_from_url,crawlDepth, sampleUrl" +
            ")values(#{cfg.entranceUrl}, #{cfg.titleXpath}, #{cfg.postdateXpath}, #{cfg.postdateFormat}, #{cfg.contentXpath}, #{cfg.encoding}, " +
            "#{cfg.webName}, #{cfg.groupName}, #{cfg.domain}, #{cfg.crawling_interval}, #{cfg.stopSeconds}, #{cfg.urlSourceNorm}, #{cfg.urlPattern}," +
            " #{cfg.urlREPOrigin}, #{cfg.urlREPReplacement}, #{cfg.urlPrefix}, #{cfg.status}, #{cfg.postDate_is_from_url}, #{cfg.crawlDepth}, #{cfg.sampleUrl})")
    public int insert(@Param("cfg") WebsiteConfig websiteConfig);

    @Insert("insert into t_website_config(\n" +
            "entranceUrl,titleXpath,postdateXpath,postdateFormat,contentXpath,encoding," +
            "webName,groupName,domain,crawling_interval,stopSeconds,urlSourceNorm,urlPattern," +
            "urlREPOrigin,urlREPReplacement,urlPrefix,`status`,postDate_is_from_url,crawlDepth, sampleUrl, checked_status" +
            ")values(#{cfg.entranceUrl}, #{cfg.titleXpath}, #{cfg.postdateXpath}, #{cfg.postdateFormat}, #{cfg.contentXpath}, #{cfg.encoding}, " +
            "#{cfg.webName}, #{cfg.groupName}, #{cfg.domain}, #{cfg.crawling_interval}, #{cfg.stopSeconds}, #{cfg.urlSourceNorm}, #{cfg.urlPattern}," +
            " #{cfg.urlREPOrigin}, #{cfg.urlREPReplacement}, #{cfg.urlPrefix}, #{cfg.status}, #{cfg.postDate_is_from_url}, #{cfg.crawlDepth}, #{cfg.sampleUrl}, #{cfg.checked_status})" +
            "on duplicate key update " +
            "entranceUrl = values(entranceUrl),  titleXpath = values(titleXpath), " +
            "postdateXpath = values(postdateXpath),  postdateFormat = values(postdateFormat), " +
            "contentXpath = values(contentXpath),  encoding = values(encoding), " +
            "webName = values(webName),  groupName = values(groupName), " +
            "domain = values(domain),  crawling_interval = values(crawling_interval), " +
            "stopSeconds = values(stopSeconds),  urlSourceNorm = values(urlSourceNorm), " +
            "urlPattern = values(urlPattern),  urlREPOrigin = values(urlREPOrigin), " +
            "urlREPReplacement = values(urlREPReplacement),  urlPrefix = values(urlPrefix), " +
            "`status` = values(`status`),  postDate_is_from_url = values(postDate_is_from_url), " +
            "crawlDepth = values(crawlDepth), sampleUrl = values(sampleUrl) , checked_status = values(checked_status) "
    )
    public int update(@Param("cfg") WebsiteConfig websiteConfig);
}


text:
using Sodium;

namespace Royale_Proxy
{
    public class ServerState : State
    {
        public byte[] ClientKey, Nonce, SessionKey, SharedKey;
        public ClientState ClientState;
        public KeyPair ServerKey;
    }
}


text:
package com.pivotal.gemfirexd.internal.impl.sql.compile;

import com.pivotal.gemfirexd.internal.iapi.error.StandardException;
import com.pivotal.gemfirexd.internal.iapi.sql.execute.ConstantAction;

/**
 * Statement Node for DROP GATEWAYRECEIVER DDL
 *
 * @author Yogesh Mahajan
 * @since 1.0
 *
 */
public class DropGatewayReceiverNode extends DDLStatementNode {

  private String id;
  private Boolean onlyIfExists;

  public DropGatewayReceiverNode() {
  }

  @Override
  public void init(Object arg1, Object arg2) throws StandardException {
    this.id = (String)arg1;
    this.onlyIfExists = ((Boolean)arg2).booleanValue();
  }

  @Override
  public String statementToString() {
    return "DROP GATEWAYRECEIVER";
  }

  @Override
  public ConstantAction makeConstantAction() {
	  return getGenericConstantActionFactory().getDropGatewayReceiverConstantAction(
			  id,onlyIfExists);
  }

  public static void dummy() {
  }
}


text:
package org.softuni;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class _10_ExtractWords {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        System.out.print("Input: ");
        String input = in.nextLine();

        List<String> words = new ArrayList<String>();
        Matcher wordFinder = Pattern.compile("[A-Za-z]+").matcher(input);
        while (wordFinder.find()) {
            words.add(wordFinder.group());
        }
        System.out.println(String.join(" ", words));
    }
}


text:
How to use PikaDeck

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                ...


text:
package buildcraft.api.fuels;

import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidStack;

public interface ISolidCoolant {
	FluidStack getFluidFromSolidCoolant(ItemStack stack);
}


text:
package com.zobot.client.packet.definitions.clientbound.play

import com.zobot.client.packet.Packet

case class CraftRecipeResponse(windowId: Any, recipe: Int) extends Packet {
  override lazy val packetId = 0x2B

  override lazy val packetData: Array[Byte] =
    fromAny(windowId) ++
    fromVarInt(recipe)
}