text:
package org.apache.jackrabbit.oak.plugins.document.mongo;

import com.mongodb.ReadPreference;

import org.apache.jackrabbit.oak.plugins.document.AbstractMongoConnectionTest;
import org.apache.jackrabbit.oak.plugins.document.DocumentMK;
import org.apache.jackrabbit.oak.plugins.document.LeaseCheckMode;
import org.apache.jackrabbit.oak.plugins.document.MongoUtils;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.apache.jackrabbit.oak.stats.Clock;
import org.junit.After;
import org.junit.Test;

import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES;
import static org.apache.jackrabbit.oak.plugins.document.Collection.SETTINGS;
import static org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore.DocumentReadPreference;
import static org.apache.jackrabbit.oak.plugins.document.util.Utils.getIdFromPath;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

public class ReadPreferenceIT extends AbstractMongoConnectionTest {

    private MongoDocumentStore mongoDS;

    private DocumentMK mk2;

    private Clock clock;

    @Override
    public void setUpConnection() {
        clock = new Clock.Virtual();
        setRevisionClock(clock);
        setClusterNodeInfoClock(clock);
        mongoConnection = connectionFactory.getConnection();
        assertNotNull(mongoConnection);
        MongoUtils.dropCollections(mongoConnection.getDBName());
        mk = new DocumentMK.Builder()
                .clock(clock)
                .setClusterId(1)
                .setClientSessionDisabled(true)
                .setMongoDB(mongoConnection.getMongoClient(), mongoConnection.getDBName())
                .setLeaseCheckMode(LeaseCheckMode.DISABLED)
                .open();
        mongoDS = (MongoDocumentStore) mk.getDocumentStore();

        // use a separate connection for cluster node 2
        MongoConnection mongoConnection2 = connectionFactory.getConnection();
        mk2 = new DocumentMK.Builder()
                .clock(clock)
                .setClusterId(2)
                .setClientSessionDisabled(true)
                .setMongoDB(mongoConnection2.getMongoClient(), mongoConnection2.getDBName())
                .setLeaseCheckMode(LeaseCheckMode.DISABLED)
                .open();
    }

    @After
    public void tearDown() {
        // reset readWrite mode before shutting down
        mongoDS.setReadWriteMode("");
        mk2.dispose();
    }

    @Test
    public void testMongoReadPreferencesDefault() {
        // start with read preference set to primary
        mongoDS.setReadWriteMode(rwMode(ReadPreference.primary()));

        assertEquals(ReadPreference.primary(),
                mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PRIMARY));

        assertEquals(ReadPreference.primaryPreferred(),
                mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_PRIMARY));

        //By default Mongo read preference is primary
        assertEquals(ReadPreference.primary(),
                mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_SECONDARY));

        //Change the default and assert again
        mongoDS.setReadWriteMode(rwMode(ReadPreference.secondary()));
        assertEquals(ReadPreference.secondary(),
                mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_SECONDARY));

        //for case where parent age cannot be determined the preference should be primary
        assertEquals(ReadPreference.primary(),
                mongoDS.getMongoReadPreference(NODES,"foo", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH));

        //For collection other than NODES always primary
        assertEquals(ReadPreference.primary(),
                mongoDS.getMongoReadPreference(SETTINGS,"foo", DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH));

    }

    @Test
    public void testReadWriteMode() {
        mongoDS.setReadWriteMode(rwMode(ReadPreference.primary()));
        assertEquals(ReadPreference.primary(), mongoDS.getConfiguredReadPreference(NODES));

        mongoDS.setReadWriteMode("readPreference=secondary&w=2&safe=true&j=true");

        assertEquals(ReadPreference.secondary(), mongoDS.getDBCollection(NODES).getReadPreference());
        assertEquals(2, mongoDS.getDBCollection(NODES).getWriteConcern().getW());
        Boolean journal = mongoDS.getDBCollection(NODES).getWriteConcern().getJournal();
        assertNotNull(journal);
        assertTrue(journal);

        assertEquals(ReadPreference.secondary(), mongoDS.getConfiguredReadPreference(NODES));
    }

    @Test
    public void getMongoReadPreference() {
        String id = getIdFromPath("/does/not/exist");
        mongoDS.setReadWriteMode(rwMode(ReadPreference.secondaryPreferred()));
        mongoDS.find(NODES, id);
        ReadPreference readPref = mongoDS.getMongoReadPreference(NODES, id,
                DocumentReadPreference.PREFER_SECONDARY_IF_OLD_ENOUGH);
        assertEquals(ReadPreference.primary(), readPref);
    }

    private static String rwMode(ReadPreference preference) {
        return "readpreference=" + preference.getName();
    }
}


text:
package irssibot.core;

/**
 * Represents simple timer counting downwards from the given value
 * and dying when reaching zero.
 *
 * @author Matti Dahlbom
 */
public class Timer extends Thread {
    protected int timeToLive = 0;

    public Timer(int seconds)
    {
	timeToLive = seconds;
    }

    /**
     * The actual life cycle
     *
     */
    protected void doRun()
    {
	while( timeToLive > 0 ) {
	    try {
		sleep(1000);
	    } catch( InterruptedException ie ) {}
	    timeToLive--;
	}
    }

    public void run()
    {
	doRun();
    }

    public void kill()
    {
	timeToLive = 0;
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Session context for commands.  This provides singular state mgmt for a tree
of commands as well as the implementation for interactive mode.
"""

import ast
import configparser
import contextlib
import os.path
import pdb
import readline
import shutil
import sys
import traceback
from . import eventing, rendering

def _vprinterr(*args, **kwargs):
    return rendering.vtmlprint(*args, file=sys.stderr, **kwargs)

class SessionExit(BaseException):
    pass

class Session(eventing.Eventer):
    """ The session manager for a tree of commands. """

    var_dir = os.path.expanduser('~')
    command_error_verbosity = 'traceback'
    default_prompt_format = '[{name}] $'
    intro = 'Type "help" or "?" to list commands and "exit" to quit.'
    completer_delim_includes = frozenset()
    completer_delim_excludes = frozenset('-+@:/~*')
    pad_completion = True
    allow_pager = bool(os.environ.get('PAGER', True))

    @property
    def config_file(self):
        return '.%s_config' % self.name

    @property
    def history_file(self):
        return '.%s_history' % self.name

    def __init__(self, root_command, name=None):
        self.root_command = root_command
        self.name = name or root_command.name
        self.config = self.load_config()
        self.add_events(['precmd', 'postcmd'])
        raw_prompt = self.config['ui']['prompt_format']
        self.prompt_format = ast.literal_eval("'%s '" % raw_prompt)
        super().__init__()

    def default_config(self):
        pager = os.environ.get('PAGER')
        if not pager:
            pager = "less -i -X -R -F -P's{desc}, line %l" \
                    "(press h for help or q to quit)'"
        return {
            "ui": {
                "prompt_format": self.default_prompt_format
            },
            "core": {
                "pager": pager
            }
        }

    def load_config(self):
        filename = os.path.join(self.var_dir, self.config_file)
        config = configparser.ConfigParser(interpolation=None)
        config.read_dict(self.default_config())
        config.read_dict(self.command_default_configs())
        config.read(filename)
        return config

    def load_history(self):
        filename = os.path.join(self.var_dir, self.history_file)
        try:
            readline.read_history_file(filename)
        except FileNotFoundError:
            pass
        return filename

    def exit(self):
        """ Can be called by commands to stop an interactive session. """
        raise SessionExit()

    def map_subcommands(self, func):
        """ Run `func` against all the subcommands attached to our root
        command. """

        def crawl(cmd):
            for sc in cmd.subcommands.values():
                yield from crawl(sc)
            yield cmd
        return map(func, crawl(self.root_command))

    def command_default_configs(self):
        getconfig = lambda cmd: (cmd.config_section(), cmd.default_config())
        return dict(self.map_subcommands(getconfig))

    def execute(self, command, args):
        """ Event firing and exception conversion around command execution.
        Common exceptions are run through our exception handler for
        pretty-printing or debugging and then converted to SystemExit so the
        interpretor will exit without further ado (or be caught if
        interactive). """
        self.fire_event('precmd', command, args)
        try:
            try:
                result = command.run_wrap(args)
            except BaseException as e:
                self.fire_event('postcmd', command, args, exc=e)
                raise e
            else:
                self.fire_event('postcmd', command, args, result=result)
                return result
        except BrokenPipeError as e:
            _vprinterr('<dim><red>...broken pipe...</red></dim>')
            raise SystemExit(1) from e
        except KeyboardInterrupt as e:
            _vprinterr('<dim><red>...interrupted...</red></dim>')
            raise SystemExit(1) from e
        except SystemExit as e:
            if e.args and not isinstance(e.args[0], int):
                _vprinterr("<red>%s</red>" % e)
                raise SystemExit(1) from e
            raise e
        except Exception as e:
            self.handle_command_error(command, args, e)
            raise SystemExit(1) from e

    def handle_command_error(self, command, args, exc):
        """ Depending on how the session is configured this will print
        information about an unhandled command exception or possibly jump
        to some other behavior like a debugger. """
        verbosity = self.command_error_verbosity
        if verbosity == 'traceback':
            self.pretty_print_exc(command, exc, show_traceback=True)
        elif verbosity == 'debug':
            pdb.set_trace()
        elif verbosity == 'raise':
            raise exc
        elif verbosity == 'pretty':
            self.pretty_print_exc(command, exc)
        else:
            raise ValueError('Unexpected exception_verbosity: %s' %
                             verbosity)

    def pretty_print_exc(self, command, exc, show_traceback=False):
        cmdname = command.prog or command.name
        if not show_traceback:
            _vprinterr("<red>Command '%s' error: %s - %s</red>" % (cmdname,
                       type(exc).__name__, exc))
        else:
            _vprinterr("<red>Command '%s' error, traceback...</red>" %
                       cmdname)
            rendering.print_exception(exc, file=sys.stderr)

    @property
    def prompt(self):
        raw = self.prompt_format.format(**self.prompt_info())
        return rendering.vtmlrender(raw)

    def prompt_info(self):
        """ Return a dictionary of items that can be substituted into the
        prompt_format by the subclass or its user if customized in the
        config file. """
        return {
            "name": self.name,
        }

    def cmd_split(self, line):
        """ Get the command associated with this input line. """
        cmd, *args = line.lstrip().split(' ', 1)
        return self.root_command.subcommands[cmd], ' '.join(args)

    def completer_hook(self, text, state):
        if state == 0:
            linebuf = readline.get_line_buffer()
            line = linebuf.lstrip()
            stripped = len(linebuf) - len(line)
            begin = readline.get_begidx() - stripped
            end = readline.get_endidx() - stripped
            if begin > 0:
                try:
                    cmd, args = self.cmd_split(line)
                except KeyError:
                    return None
                cfunc = cmd.complete
            else:
                cfunc = self.complete_names
            if self.pad_completion:
                pad = lambda x: x + ' ' if not x.endswith(' ') or \
                    x.endswith(r'\ ') else x
            else:
                pad = lambda x: x
            choices = self.complete_wrap(cfunc, text, line, begin, end)
            self.completer_cache = list(map(pad, choices))
        try:
            return self.completer_cache[state]
        except IndexError:
            return None

    def complete_wrap(self, func, *args, **kwargs):
        """ Readline eats exceptions raised by completer functions. """
        # Workaround readline's one-time-read of terminal width.
        termcols = shutil.get_terminal_size()[0]
        readline.parse_and_bind('set completion-display-width %d' % termcols)
        try:
            return func(*args, **kwargs)
        except:
            traceback.print_exc()
            raise

    def complete_names(self, text, line, begin, end):
        choices = set(self.root_command.subcommands)
        return [x for x in choices if x.startswith(line)]

    @contextlib.contextmanager
    def setup_readline(self):
        """ Configure our tab completion settings for a context and then
        restore them to previous settings on exit. """
        readline.parse_and_bind('tab: complete')
        completer_save = readline.get_completer()
        delims_save = readline.get_completer_delims()
        delims = set(delims_save)
        delims |= self.completer_delim_includes
        delims -= self.completer_delim_excludes
        readline.set_completer(self.completer_hook)
        try:
            readline.set_completer_delims(''.join(delims))
            try:
                yield
            finally:
                readline.set_completer_delims(delims_save)
        finally:
            readline.set_completer(completer_save)

    def run_loop(self):
        """ Main entry point for running in interactive mode. """
        self.root_command.prog = ''
        history_file = self.load_history()
        rendering.vtmlprint(self.intro)
        try:
            self.loop()
        finally:
            readline.write_history_file(history_file)

    def loop(self):
        """ Inner loop for interactive mode.  Do not call directly. """
        while True:
            with self.setup_readline():
                try:
                    line = input(self.prompt)
                except EOFError:
                    _vprinterr('^D')
                    break
                except KeyboardInterrupt:
                    _vprinterr('^C')
                    continue
            if not line.strip():
                continue
            try:
                cmd, args = self.cmd_split(line)
            except KeyError as e:
                _vprinterr('<red>Invalid command: %s</red>' % e)
                continue
            try:
                cmd(argv=args)
            except SessionExit:
                break
            except SystemExit as e:
                pass


text:
import os
import json
import logging

from website import settings

logger = logging.getLogger(__name__)

def load_asset_paths():
    if settings.DEBUG_MODE:
        logger.warn('Skipping load of "webpack-assets.json" in DEBUG_MODE.')
        return
    asset_paths = None
    try:
        with open(settings.ASSET_HASH_PATH) as fp:
            asset_paths = json.load(fp)
    except IOError:
        logger.error('No "webpack-assets.json" file found. You may need to run webpack.')
        pass
    return asset_paths

asset_paths = load_asset_paths()
base_static_path = '/static/public/js/'
def webpack_asset(path, asset_paths=asset_paths, debug=settings.DEBUG_MODE):
    """Mako filter that resolves a human-readable asset path to its name on disk
    (which may include the hash of the file).
    """
    if not asset_paths:
        logger.warn('webpack-assets.json has not yet been generated. Falling back to non-cache-busted assets')
        return path
    if not debug:
        key = path.replace(base_static_path, '').replace('.js', '')
        hash_path = asset_paths[key]['js']
        return os.path.join(base_static_path, hash_path)
    else:  # We don't cachebust in debug mode, so just return unmodified path
        return path

def resolve_addon_path(addon_config, file_name):
    """Check for addon asset in source directory (e.g. website/addons/dropbox/static');
    if file is found, return path to webpack-built asset.

    :param AddonConfig config: Addon config object
    :param str file_name: Asset file name (e.g. "files.js")
    """
    source_path = os.path.join(
        settings.ADDON_PATH,
        addon_config.short_name,
        'static',
        file_name,
    )
    if os.path.exists(source_path):
        return os.path.join(
            '/',
            'static',
            'public',
            'js',
            addon_config.short_name,
            file_name,
        )
    return None


text:
<?xml version="1.0" encoding="UTF-8"?>

<document xmlns="http://maven.apache.org/XDOC/2.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/XDOC/2.0 http://maven.apache.org/xsd/xdoc-2.0.xsd">

  <properties>
    <title>MyBatis-Spring | Sample Code</title>
    <author email="eduardo.macarron@gmail.com">Eduardo Macarron</author>
  </properties>

      	JPetStore 6 is a full web application built on top of MyBatis 3,
      	Spring 3 and Stripes.
        It is available for download in the
        downloads
        section of MyBatis project site.
        In this section we will walk through this sample to understand how is it built and learn how to run it.

      <subsection name="Purpose">

      	This new JPetStore comes with the same idea in mind than its predecessors: keep it simple.
      	The purpose of JPetStore 6 is to demonstrate how to build a web application with very few classes and no advanced coding skills.
      	You just need to know plain Java and SQL.

      	The 6th version of JPetStore is the smallest of the family, 20% smaller than its predecessor.
      	It uses just 24 java classes while keeping a good design and program structure.

eduardo@nomada ~ $ ./cloc-1.60.pl ~/git/jpetstore-6/src/main/
      60 text files.
      60 unique files.
       3 files ignored.

http://cloc.sourceforge.net v 1.60  T=0.28 s (209.8 files/s, 17722.9 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Java                            24            480            462           1429
JSP                             20            148              0            984
XML                              9             79            120            405
CSS                              1             46              0            277
SQL                              2             26             30            226
HTML                             2             44              0            143
-------------------------------------------------------------------------------
SUM:                            58            823            612           3464
-------------------------------------------------------------------------------

      	As we will see later on, you will find no code to deal with JDBC, to create objects or bind them or to handle transactions.
      	What is more impressive is that you will not find any call to the MyBatis API.
      	Although this sounds magical, you will see that the combination of MyBatis mappers and dependency injection lets you
      	build applications without dependencies.

      </subsection>
      <subsection name="Program Structure">

 JPetStore 6 follows the typical maven project structure

/jpetstore                    <tt><-- Maven pom.xml goes here.</tt>
  /src
    /main/
      /java                   <tt><-- Java code goes here.</tt>
        /org/
          /mybatis
            /jpetstore
              /domain         <tt><-- Business domain objects go here.</tt>
              /persistence    <tt><-- Mapper interfaces go here.</tt>
              /service        <tt><-- Application logic goes here.</tt>
              /web
                /actions      <tt><-- Presentation logic (actions) goes here.</tt>
      /resources              <tt><-- Non java files go here.</tt>
        /org
          /mybatis
            /jpetstore
              /persistence    <tt><-- Mapper XML files go here.</tt>
        /database
      /webapp
        /css
        /images
        /WEB-INF              <tt><-- web.xml and applicationContext.xml go here.</tt>
          /jsp                <tt><-- JSP files go here.</tt>

      </subsection>

      <subsection name="Configuration files">

      Configuration files are read during application startup. Their purpose is to configure the three
      frameworks composing the application: Stripes, Spring and MyBatis. We will need to configure just
      two files: web.xml and applicationContext.xml.

web.xml

      First of all we need to start Stripes, so we will follow the Stripes manual to do so. The manual says that
      we should set up a dispatcher servlet and a filter, so let's go:

<source><![CDATA[
<filter>
  <display-name>Stripes Filter</display-name>
  <filter-name>StripesFilter</filter-name>
  <filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>StripesFilter</filter-name>
  <servlet-name>StripesDispatcher</servlet-name>
  <dispatcher>REQUEST</dispatcher>
</filter-mapping>
<servlet>
  <servlet-name>StripesDispatcher</servlet-name>
  <servlet-class>net.sourceforge.stripes.controller.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>StripesDispatcher</servlet-name>
  <url-pattern>*.action</url-pattern>
</servlet-mapping>
]]></source>

Stripes is able to search for ActionBean classes, for that purpose we must set up the
	base package it should search in.

<source><![CDATA[
<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
  <init-param>
    <param-name>ActionResolver.Packages</param-name>
    <param-value>org.mybatis.jpetstore.web</param-value>
  </init-param>
</filter>
]]></source>

We are done with Stripes. Let's move on to the Spring side. According to Spring's reference manual
	we should add a Context listener to start up Spring. Let's add it:

<source><![CDATA[
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
]]></source>

By default Spring will use /WEB-INF/applicationContext.xml if we don't specify
	a different file. The default is fine for us.

Now we have to let Stripes know that it will be running with Spring. This way we will be able
	to inject Spring beans directly into Stripes ActionBeans. For that purpose, following once
	again the Stripes manual, we set up an interceptor as follows below:

<source><![CDATA[
<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
  ...
  <init-param>
    <param-name>Interceptor.Classes</param-name>
    <param-value>net.sourceforge.stripes.integration.spring.SpringInterceptor</param-value>
  </init-param>
</filter>
]]></source>

We are done with web.xml. As you may have noticed, we have not set up any MyBatis 3 configuration yet.
      That configuration goes into the Spring's applicationContext.xml that we will see in the following section.

applicationContext.xml

As you already know, applicationContext.xml is the Spring's configuration file. Spring is a dependency
      injection framework and it has to know which beans it must create and how to bind them together and that is
      what applicationContext.xml file is for. Let's have a deeper look into it.

      The first and easiest thing we have to do is let Spring know where are our service beans. We will let Spring
      search them in our classpath so we just need to provide it the base package to search in:

<source><![CDATA[
<context:component-scan base-package="org.mybatis.jpetstore.service" />
]]></source>

	  NOTE Spring's component scan feature is not able to find MyBatis mappers.
	  A mapper is not a plain bean and Spring would not know how to instantiate it. We will see how to search for mappers soon.

We will also need a DataSource and a TransactionManager. Given that this is a demo application
	  we will use a test Spring DataSource that will create an HSQL in-memory database and load
	  our database scripts into it and the standard Spring's DataSourceTransactionManager
	  to handle transactions.

<source><![CDATA[
<jdbc:embedded-database id="dataSource">
  <jdbc:script location="classpath:database/jpetstore-hsqldb-schema.sql"/>
  <jdbc:script location="classpath:database/jpetstore-hsqldb-dataload.sql"/>
</jdbc:embedded-database>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
</bean>
]]></source>

So far, all we have done is standard Stripes and Spring configuration and now it is time to
	  move on to the MyBatis part. As you have learned in this manual to set up MyBatis with Spring you need
	  at least two things: an SqlSessionFactoryBean and, at least, one mapper class.
	  So let's go hands on. First define a SqlSessionFactoryBean:

<source><![CDATA[
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>
]]></source>

And now we need to setup our mappers. For that purpose we will use the MapperScannerConfigurer
      that works similar to Spring standard component scan. It will search our classpath for mapper classes
      and register them to MyBatis. Similar to Spring's component scan we must configure the base
      package to search in.

<source><![CDATA[
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="org.mybatis.jpetstore.persistence" />
</bean>
]]></source>

To save some writing when building our mapper xml files we would want to be able to use short
      aliases for beans. The SqlSessionFactoryBean has the capability to search for beans and
      register their short names as aliases if we setup the typeAliasPackage property like
      the following:

<source><![CDATA[
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="typeAliasesPackage" value="org.mybatis.jpetstore.domain" />
</bean>
]]></source>

Our application is now fully configured and ready to run. But before running it lets have a tour
		through the code to see how it looks like.

      </subsection>

      <subsection name="Code tour">

JPetStore 6 is a typical MVC application with three layers: presentation, logic and data access.

Presentation

The presentation layer is composed by JSP files and Stripes ActionBeans. JSPs just use plain HTML,
      JSTL tags and Stripes tags. Stripes ActionBeans are like Struts actions or Spring MVC controllers.

Given that we have integrated Stripes with Spring, we can inject our services into our ActionsBeans so
      you can just use them without caring about its creation or lookup.
      Have a look at CatalogActionBean:

<source><![CDATA[
@SessionScope
public class CatalogActionBean extends AbstractActionBean {
  ...
  @SpringBean
  private transient CatalogService catalogService;
  ...
  public ForwardResolution viewCategory() {
    if (categoryId != null) {
      productList = catalogService.getProductListByCategory(categoryId);
      category = catalogService.getCategory(categoryId);
    }
    return new ForwardResolution(VIEW_CATEGORY);
  }
  ...
]]></source>

The @SpringBean annotation is an Stripes annotation that tells Stripes to
	  look for that bean in Spring and inject it into this ActionBean.

Logic

Application logic is composed by plain Java beans that act as services and plain Java beans that
      act as domain objects. This layer is in charge of filling domain objects with database data and
      updating database data with the content of the domain objects. For this purpose this layer must be
      transactional.

Let's have a look at OrderService code to see how all this is achieved:

<source><![CDATA[
@Service
public class OrderService {

  @Autowired
  private ItemMapper itemMapper;
  @Autowired
  private OrderMapper orderMapper;
  @Autowired
  private LineItemMapper lineItemMapper;

  @Transactional
  public void insertOrder(Order order) {
    order.setOrderId(getNextId("ordernum"));
    for (int i = 0; i < order.getLineItems().size(); i++) {
      LineItem lineItem = (LineItem) order.getLineItems().get(i);
      String itemId = lineItem.getItemId();
      Integer increment = new Integer(lineItem.getQuantity());
      Map<String, Object> param = new HashMap<String, Object>(2);
      param.put("itemId", itemId);
      param.put("increment", increment);
      itemMapper.updateInventoryQuantity(param);
    }

    orderMapper.insertOrder(order);
    orderMapper.insertOrderStatus(order);
    for (int i = 0; i < order.getLineItems().size(); i++) {
      LineItem lineItem = (LineItem) order.getLineItems().get(i);
      lineItem.setOrderId(order.getOrderId());
      lineItemMapper.insertLineItem(lineItem);
    }
  }
]]></source>

The first thing you will notice is that there is no JDBC code in the service,
      nor it is any MyBatis code in it. You may think that we used the
      DAO pattern and database access code is in the database layer, but as we will see later,
      the database layer is built with MyBatis mappers, that are plain java
      interfaces, and that is why you will not find any call to MyBatis API
      in the whole application. It is just not needed.

The second thing you may have noticed is that there are no commits or rollbacks.
      That is because it uses the declarative transaction demarcation feature of Spring that is
      fully supported by MyBatis-Spring.
      The Spring's @Transactional annotation indicates that this method is transactional,
      that means that all updateInventoryQuantity, insertOrder and
      insertLineItem mapper calls must end OK. If one of them fails any previous
      update will be rolled back.

Persistence

The persistence layer is composed of MyBatis mappers. Mappers are just plain Java
      interfaces and mapper XML files containing the SQL statements.
      There is no custom Java code in this layer. When the
      getOrder method is called on the OrderMapper interface,
      MyBatis will execute the getOrder SQL statement in OrderMapper.xml file and
      will populate the Order domain bean with retrieved data.

<source><![CDATA[
public interface OrderMapper {
  List<Order> getOrdersByUsername(String username);
  Order getOrder(int orderId);
  void insertOrder(Order order);
  void insertOrderStatus(Order order);
}]]></source>

<source><![CDATA[
<mapper namespace="org.mybatis.jpetstore.persistence.OrderMapper">

  <cache />

  <select id="getOrder" resultType="Order">
    SELECT
      BILLADDR1 AS billAddress1,
      BILLADDR2 AS billAddress2,
      BILLCITY,
      BILLCOUNTRY,
      BILLSTATE,
      BILLTOFIRSTNAME,
      BILLTOLASTNAME,
      BILLZIP,
      SHIPADDR1 AS shipAddress1,
      SHIPADDR2 AS shipAddress2,
      SHIPCITY,
      SHIPCOUNTRY,
      SHIPSTATE,
      SHIPTOFIRSTNAME,
      SHIPTOLASTNAME,
      SHIPZIP,
      CARDTYPE,
      COURIER,
      CREDITCARD,
      EXPRDATE AS expiryDate,
      LOCALE,
      ORDERDATE,
      ORDERS.ORDERID,
      TOTALPRICE,
      USERID AS username,
      STATUS
    FROM ORDERS, ORDERSTATUS
    WHERE ORDERS.ORDERID = #{value}
      AND ORDERS.ORDERID = ORDERSTATUS.ORDERID
  </select>
  ...
</mapper>
]]></source>

      NOTE
      You can easily add caching to your queries by adding a <cache /> element to your mapper xml file.

      </subsection>

      <subsection name="Running JPetStore">

You may ask. Does all this work? Yes it does! Let's run it.

Let's assume you have a clean computer. These are the steps you should follow to
           have the sample running on Tomcat with Eclipse:

Download and install a JDK 6 or later

Download and upzip Eclipse

Download and unzip Tomcat

Run Eclipse

Go to Git tab

Clone the repo https://github.com/mybatis/jpetstore-6.git

Select working directory, right click and select Import Projects (general)

Go to Java EE tab

Right click on jpetstore project and select "Configure/Convert to Maven Project"

Right click on jpetstore project and select "run on server"

Select Tomcat Server and set your installation directory

JPetStore home page should be shown!!

          Now you are ready to play with it, experiment with your own changes or whatever you want.

          And remember that if you find a bug or something that is missing or can be improved (for example the missing tests!),
          fork the repo, change it, and open a pull request. Thanks in advance!!!

        NOTE
		JPetStore 6 should run in any Servlet 2.5 y JSP 2.1 compliant Java server. Eclipse is not needed
		either, you can run the sample from your favorite IDE or the command line.

      </subsection>

</document>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="cache-control" content="max-age=0">
  <meta http-equiv="cache-control" content="no-cache">
  <meta http-equiv="expires" content="0">
  <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT">
  <meta http-equiv="pragma" content="no-cache">
  <link rel="stylesheet" type="text/css" href="/static/css/ico.css">

        <button data-toggle="collapse" data-target="#ico-navbar" class="navbar-toggle collapsed">Toggle navigation</button>

Home

ICO

About

Blog

Contact

TUTORING SCHEDULELEARNING TOOLS GALLERY

Craft Day

Craft Day at 5629 Gallery

5629 Michigan Ave.

Detroit, MI 48210

Tutoring Day

Tutoring Day at Central Alliance Church

616 West Hancock

Detroit, MI 48201

Photo Class

Photo Class at Focus Hope

Coming soon!

Coming soon!


text:
package xorm

import (
	"errors"
	"fmt"
	"reflect"

	"github.com/go-xorm/builder"
)

// Exist returns true if the record exist otherwise return false
func (session *Session) Exist(bean ...interface{}) (bool, error) {
	if session.isAutoClose {
		defer session.Close()
	}

	var sqlStr string
	var args []interface{}
	var err error

	if session.statement.RawSQL == "" {
		if len(bean) == 0 {
			tableName := session.statement.TableName()
			if len(tableName) <= 0 {
				return false, ErrTableNotFound
			}

			if session.statement.cond.IsValid() {
				condSQL, condArgs, err := builder.ToSQL(session.statement.cond)
				if err != nil {
					return false, err
				}

				sqlStr = fmt.Sprintf("SELECT * FROM %s WHERE %s LIMIT 1", tableName, condSQL)
				args = condArgs
			} else {
				sqlStr = fmt.Sprintf("SELECT * FROM %s LIMIT 1", tableName)
				args = []interface{}{}
			}
		} else {
			beanValue := reflect.ValueOf(bean[0])
			if beanValue.Kind() != reflect.Ptr {
				return false, errors.New("needs a pointer")
			}

			if beanValue.Elem().Kind() == reflect.Struct {
				if err := session.statement.setRefValue(beanValue.Elem()); err != nil {
					return false, err
				}
			}

			if len(session.statement.TableName()) <= 0 {
				return false, ErrTableNotFound
			}
			session.statement.Limit(1)
			sqlStr, args, err = session.statement.genGetSQL(bean[0])
			if err != nil {
				return false, err
			}
		}
	} else {
		sqlStr = session.statement.RawSQL
		args = session.statement.RawParams
	}

	rows, err := session.queryRows(sqlStr, args...)
	if err != nil {
		return false, err
	}
	defer rows.Close()

	return rows.Next(), nil
}


text:
<?php

namespace App\Domain\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Log extends Entities
{
    use SoftDeletes;

    protected $table='log';
    protected $fillable = [
        'id', 'nama', 'email', 'telephone', 'keperluan', 'description'
    ];

    protected $primaryKey = 'id';

}


text:
from __future__ import annotations

from . import dtypes, nputils

def dask_rolling_wrapper(moving_func, a, window, min_count=None, axis=-1):
    """Wrapper to apply bottleneck moving window funcs on dask arrays"""
    import dask.array as da

    dtype, fill_value = dtypes.maybe_promote(a.dtype)
    a = a.astype(dtype)
    # inputs for overlap
    if axis < 0:
        axis = a.ndim + axis
    depth = {d: 0 for d in range(a.ndim)}
    depth[axis] = (window + 1) // 2
    boundary = {d: fill_value for d in range(a.ndim)}
    # Create overlap array.
    ag = da.overlap.overlap(a, depth=depth, boundary=boundary)
    # apply rolling func
    out = da.map_blocks(
        moving_func, ag, window, min_count=min_count, axis=axis, dtype=a.dtype
    )
    # trim array
    result = da.overlap.trim_internal(out, depth)
    return result

def least_squares(lhs, rhs, rcond=None, skipna=False):
    import dask.array as da

    lhs_da = da.from_array(lhs, chunks=(rhs.chunks[0], lhs.shape[1]))
    if skipna:
        added_dim = rhs.ndim == 1
        if added_dim:
            rhs = rhs.reshape(rhs.shape[0], 1)
        results = da.apply_along_axis(
            nputils._nanpolyfit_1d,
            0,
            rhs,
            lhs_da,
            dtype=float,
            shape=(lhs.shape[1] + 1,),
            rcond=rcond,
        )
        coeffs = results[:-1, ...]
        residuals = results[-1, ...]
        if added_dim:
            coeffs = coeffs.reshape(coeffs.shape[0])
            residuals = residuals.reshape(residuals.shape[0])
    else:
        # Residuals here are (1, 1) but should be (K,) as rhs is (N, K)
        # See issue dask/dask#6516
        coeffs, residuals, _, _ = da.linalg.lstsq(lhs_da, rhs)
    return coeffs, residuals

def push(array, n, axis):
    """
    Dask-aware bottleneck.push
    """
    import bottleneck
    import dask.array as da
    import numpy as np

    def _fill_with_last_one(a, b):
        # cumreduction apply the push func over all the blocks first so, the only missing part is filling
        # the missing values using the last data of the previous chunk
        return np.where(~np.isnan(b), b, a)

    if n is not None and 0 < n < array.shape[axis] - 1:
        arange = da.broadcast_to(
            da.arange(
                array.shape[axis], chunks=array.chunks[axis], dtype=array.dtype
            ).reshape(
                tuple(size if i == axis else 1 for i, size in enumerate(array.shape))
            ),
            array.shape,
            array.chunks,
        )
        valid_arange = da.where(da.notnull(array), arange, np.nan)
        valid_limits = (arange - push(valid_arange, None, axis)) <= n
        # omit the forward fill that violate the limit
        return da.where(valid_limits, push(array, None, axis), np.nan)

    # The method parameter makes that the tests for python 3.7 fails.
    return da.reductions.cumreduction(
        func=bottleneck.push,
        binop=_fill_with_last_one,
        ident=np.nan,
        x=array,
        axis=axis,
        dtype=array.dtype,
    )


text: どちらに興味がありますか?


text:
package com.hazelcast.jet.pipeline;

import com.hazelcast.jet.Job;
import com.hazelcast.jet.core.Processor.Context;
import org.junit.Test;

import static com.hazelcast.jet.aggregate.AggregateOperations.counting;
import static com.hazelcast.jet.core.EventTimePolicy.DEFAULT_IDLE_TIMEOUT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class StreamSourceTest extends PipelineTestSupport {

    @Test
    public void test_defaultIdle() {
        test(DEFAULT_IDLE_TIMEOUT);
    }

    @Test
    public void test_shortIdle() {
        test(500);
    }

    private void test(long idleTimeout) {
        StreamSource<Object> source = SourceBuilder
                .stream("src", Context::globalProcessorIndex)
                .distributed(1)
                .fillBufferFn((index, buf) -> {
                    // Only 1 instance will generate output. Until other instances are marked
                    // idle, there should be no output.
                    if (index == 0) {
                        buf.add("item");
                        Thread.sleep(10);
                    }
                })
                .build();
        if (idleTimeout != DEFAULT_IDLE_TIMEOUT) {
            source = source.setPartitionIdleTimeout(idleTimeout);
        }

        Pipeline p = Pipeline.create();
        p.readFrom(source)
         .withTimestamps(o -> System.currentTimeMillis(), 0)
         .window(WindowDefinition.tumbling(100))
         .aggregate(counting())
         .writeTo(sink);

        Job job = allJetInstances()[0].newJob(p);

        if (idleTimeout > 10_000) {
            assertTrueAllTheTime(() -> assertEquals("unexpected sink size", 0, sinkList.size()), 5);
        } else if (idleTimeout < 1000) {
            assertTrueEventually(() -> assertTrue("sink empty", sinkList.size() > 0));
        } else {
            fail("test not designed for idleTimeout=" + idleTimeout);
        }

        cancelAndJoin(job);
    }
}


text:
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/in.h>
#include <net/sock.h>
#include <net/ipv6.h>
#include <net/if_inet6.h>
#include <net/sctp/sctp.h>
#include <net/sctp/sm.h>

/* Forward declarations for internal helpers. */
static int sctp_copy_one_addr(struct sctp_bind_addr *, union sctp_addr *,
			      sctp_scope_t scope, gfp_t gfp,
			      int flags);
static void sctp_bind_addr_clean(struct sctp_bind_addr *);

/* First Level Abstractions. */

/* Copy 'src' to 'dest' taking 'scope' into account.  Omit addresses
 * in 'src' which have a broader scope than 'scope'.
 */
int sctp_bind_addr_copy(struct sctp_bind_addr *dest,
			const struct sctp_bind_addr *src,
			sctp_scope_t scope, gfp_t gfp,
			int flags)
{
	struct sctp_sockaddr_entry *addr;
	int error = 0;

	/* All addresses share the same port.  */
	dest->port = src->port;

	/* Extract the addresses which are relevant for this scope.  */
	list_for_each_entry(addr, &src->address_list, list) {
		error = sctp_copy_one_addr(dest, &addr->a, scope,
					   gfp, flags);
		if (error < 0)
			goto out;
	}

	/* If there are no addresses matching the scope and
	 * this is global scope, try to get a link scope address, with
	 * the assumption that we must be sitting behind a NAT.
	 */
	if (list_empty(&dest->address_list) && (SCTP_SCOPE_GLOBAL == scope)) {
		list_for_each_entry(addr, &src->address_list, list) {
			error = sctp_copy_one_addr(dest, &addr->a,
						   SCTP_SCOPE_LINK, gfp,
						   flags);
			if (error < 0)
				goto out;
		}
	}

out:
	if (error)
		sctp_bind_addr_clean(dest);

	return error;
}

/* Exactly duplicate the address lists.  This is necessary when doing
 * peer-offs and accepts.  We don't want to put all the current system
 * addresses into the endpoint.  That's useless.  But we do want duplicat
 * the list of bound addresses that the older endpoint used.
 */
int sctp_bind_addr_dup(struct sctp_bind_addr *dest,
			const struct sctp_bind_addr *src,
			gfp_t gfp)
{
	struct sctp_sockaddr_entry *addr;
	int error = 0;

	/* All addresses share the same port.  */
	dest->port = src->port;

	list_for_each_entry(addr, &src->address_list, list) {
		error = sctp_add_bind_addr(dest, &addr->a, 1, gfp);
		if (error < 0)
			break;
	}

	return error;
}

/* Initialize the SCTP_bind_addr structure for either an endpoint or
 * an association.
 */
void sctp_bind_addr_init(struct sctp_bind_addr *bp, __u16 port)
{
	bp->malloced = 0;

	INIT_LIST_HEAD(&bp->address_list);
	bp->port = port;
}

/* Dispose of the address list. */
static void sctp_bind_addr_clean(struct sctp_bind_addr *bp)
{
	struct sctp_sockaddr_entry *addr, *temp;

	/* Empty the bind address list. */
	list_for_each_entry_safe(addr, temp, &bp->address_list, list) {
		list_del_rcu(&addr->list);
		kfree_rcu(addr, rcu);
		SCTP_DBG_OBJCNT_DEC(addr);
	}
}

/* Dispose of an SCTP_bind_addr structure  */
void sctp_bind_addr_free(struct sctp_bind_addr *bp)
{
	/* Empty the bind address list. */
	sctp_bind_addr_clean(bp);

	if (bp->malloced) {
		kfree(bp);
		SCTP_DBG_OBJCNT_DEC(bind_addr);
	}
}

/* Add an address to the bind address list in the SCTP_bind_addr structure. */
int sctp_add_bind_addr(struct sctp_bind_addr *bp, union sctp_addr *new,
		       __u8 addr_state, gfp_t gfp)
{
	struct sctp_sockaddr_entry *addr;

	/* Add the address to the bind address list.  */
	addr = t_new(struct sctp_sockaddr_entry, gfp);
	if (!addr)
		return -ENOMEM;

	memcpy(&addr->a, new, sizeof(*new));

	/* Fix up the port if it has not yet been set.
	 * Both v4 and v6 have the port at the same offset.
	 */
	if (!addr->a.v4.sin_port)
		addr->a.v4.sin_port = htons(bp->port);

	addr->state = addr_state;
	addr->valid = 1;

	INIT_LIST_HEAD(&addr->list);

	/* We always hold a socket lock when calling this function,
	 * and that acts as a writer synchronizing lock.
	 */
	list_add_tail_rcu(&addr->list, &bp->address_list);
	SCTP_DBG_OBJCNT_INC(addr);

	return 0;
}

/* Delete an address from the bind address list in the SCTP_bind_addr
 * structure.
 */
int sctp_del_bind_addr(struct sctp_bind_addr *bp, union sctp_addr *del_addr)
{
	struct sctp_sockaddr_entry *addr, *temp;
	int found = 0;

	/* We hold the socket lock when calling this function,
	 * and that acts as a writer synchronizing lock.
	 */
	list_for_each_entry_safe(addr, temp, &bp->address_list, list) {
		if (sctp_cmp_addr_exact(&addr->a, del_addr)) {
			/* Found the exact match. */
			found = 1;
			addr->valid = 0;
			list_del_rcu(&addr->list);
			break;
		}
	}

	if (found) {
		kfree_rcu(addr, rcu);
		SCTP_DBG_OBJCNT_DEC(addr);
		return 0;
	}

	return -EINVAL;
}

/* Create a network byte-order representation of all the addresses
 * formated as SCTP parameters.
 *
 * The second argument is the return value for the length.
 */
union sctp_params sctp_bind_addrs_to_raw(const struct sctp_bind_addr *bp,
					 int *addrs_len,
					 gfp_t gfp)
{
	union sctp_params addrparms;
	union sctp_params retval;
	int addrparms_len;
	union sctp_addr_param rawaddr;
	int len;
	struct sctp_sockaddr_entry *addr;
	struct list_head *pos;
	struct sctp_af *af;

	addrparms_len = 0;
	len = 0;

	/* Allocate enough memory at once. */
	list_for_each(pos, &bp->address_list) {
		len += sizeof(union sctp_addr_param);
	}

	/* Don't even bother embedding an address if there
	 * is only one.
	 */
	if (len == sizeof(union sctp_addr_param)) {
		retval.v = NULL;
		goto end_raw;
	}

	retval.v = kmalloc(len, gfp);
	if (!retval.v)
		goto end_raw;

	addrparms = retval;

	list_for_each_entry(addr, &bp->address_list, list) {
		af = sctp_get_af_specific(addr->a.v4.sin_family);
		len = af->to_addr_param(&addr->a, &rawaddr);
		memcpy(addrparms.v, &rawaddr, len);
		addrparms.v += len;
		addrparms_len += len;
	}

end_raw:
	*addrs_len = addrparms_len;
	return retval;
}

/*
 * Create an address list out of the raw address list format (IPv4 and IPv6
 * address parameters).
 */
int sctp_raw_to_bind_addrs(struct sctp_bind_addr *bp, __u8 *raw_addr_list,
			   int addrs_len, __u16 port, gfp_t gfp)
{
	union sctp_addr_param *rawaddr;
	struct sctp_paramhdr *param;
	union sctp_addr addr;
	int retval = 0;
	int len;
	struct sctp_af *af;

	/* Convert the raw address to standard address format */
	while (addrs_len) {
		param = (struct sctp_paramhdr *)raw_addr_list;
		rawaddr = (union sctp_addr_param *)raw_addr_list;

		af = sctp_get_af_specific(param_type2af(param->type));
		if (unlikely(!af)) {
			retval = -EINVAL;
			sctp_bind_addr_clean(bp);
			break;
		}

		af->from_addr_param(&addr, rawaddr, htons(port), 0);
		retval = sctp_add_bind_addr(bp, &addr, SCTP_ADDR_SRC, gfp);
		if (retval) {
			/* Can't finish building the list, clean up. */
			sctp_bind_addr_clean(bp);
			break;
		}

		len = ntohs(param->length);
		addrs_len -= len;
		raw_addr_list += len;
	}

	return retval;
}

/********************************************************************
 * 2nd Level Abstractions
 ********************************************************************/

/* Does this contain a specified address?  Allow wildcarding. */
int sctp_bind_addr_match(struct sctp_bind_addr *bp,
			 const union sctp_addr *addr,
			 struct sctp_sock *opt)
{
	struct sctp_sockaddr_entry *laddr;
	int match = 0;

	rcu_read_lock();
	list_for_each_entry_rcu(laddr, &bp->address_list, list) {
		if (!laddr->valid)
			continue;
		if (opt->pf->cmp_addr(&laddr->a, addr, opt)) {
			match = 1;
			break;
		}
	}
	rcu_read_unlock();

	return match;
}

/* Does the address 'addr' conflict with any addresses in
 * the bp.
 */
int sctp_bind_addr_conflict(struct sctp_bind_addr *bp,
			    const union sctp_addr *addr,
			    struct sctp_sock *bp_sp,
			    struct sctp_sock *addr_sp)
{
	struct sctp_sockaddr_entry *laddr;
	int conflict = 0;
	struct sctp_sock *sp;

	/* Pick the IPv6 socket as the basis of comparison
	 * since it's usually a superset of the IPv4.
	 * If there is no IPv6 socket, then default to bind_addr.
	 */
	if (sctp_opt2sk(bp_sp)->sk_family == AF_INET6)
		sp = bp_sp;
	else if (sctp_opt2sk(addr_sp)->sk_family == AF_INET6)
		sp = addr_sp;
	else
		sp = bp_sp;

	rcu_read_lock();
	list_for_each_entry_rcu(laddr, &bp->address_list, list) {
		if (!laddr->valid)
			continue;

		conflict = sp->pf->cmp_addr(&laddr->a, addr, sp);
		if (conflict)
			break;
	}
	rcu_read_unlock();

	return conflict;
}

/* Get the state of the entry in the bind_addr_list */
int sctp_bind_addr_state(const struct sctp_bind_addr *bp,
			 const union sctp_addr *addr)
{
	struct sctp_sockaddr_entry *laddr;
	struct sctp_af *af;
	int state = -1;

	af = sctp_get_af_specific(addr->sa.sa_family);
	if (unlikely(!af))
		return state;

	rcu_read_lock();
	list_for_each_entry_rcu(laddr, &bp->address_list, list) {
		if (!laddr->valid)
			continue;
		if (af->cmp_addr(&laddr->a, addr)) {
			state = laddr->state;
			break;
		}
	}
	rcu_read_unlock();

	return state;
}

/* Find the first address in the bind address list that is not present in
 * the addrs packed array.
 */
union sctp_addr *sctp_find_unmatch_addr(struct sctp_bind_addr	*bp,
					const union sctp_addr	*addrs,
					int			addrcnt,
					struct sctp_sock	*opt)
{
	struct sctp_sockaddr_entry	*laddr;
	union sctp_addr			*addr;
	void 				*addr_buf;
	struct sctp_af			*af;
	int				i;

	/* This is only called sctp_send_asconf_del_ip() and we hold
	 * the socket lock in that code patch, so that address list
	 * can't change.
	 */
	list_for_each_entry(laddr, &bp->address_list, list) {
		addr_buf = (union sctp_addr *)addrs;
		for (i = 0; i < addrcnt; i++) {
			addr = addr_buf;
			af = sctp_get_af_specific(addr->v4.sin_family);
			if (!af)
				break;

			if (opt->pf->cmp_addr(&laddr->a, addr, opt))
				break;

			addr_buf += af->sockaddr_len;
		}
		if (i == addrcnt)
			return &laddr->a;
	}

	return NULL;
}

/* Copy out addresses from the global local address list. */
static int sctp_copy_one_addr(struct sctp_bind_addr *dest,
			      union sctp_addr *addr,
			      sctp_scope_t scope, gfp_t gfp,
			      int flags)
{
	int error = 0;

	if (sctp_is_any(NULL, addr)) {
		error = sctp_copy_local_addr_list(dest, scope, gfp, flags);
	} else if (sctp_in_scope(addr, scope)) {
		/* Now that the address is in scope, check to see if
		 * the address type is supported by local sock as
		 * well as the remote peer.
		 */
		if ((((AF_INET == addr->sa.sa_family) &&
		      (flags & SCTP_ADDR4_PEERSUPP))) ||
		    (((AF_INET6 == addr->sa.sa_family) &&
		      (flags & SCTP_ADDR6_ALLOWED) &&
		      (flags & SCTP_ADDR6_PEERSUPP))))
			error = sctp_add_bind_addr(dest, addr, SCTP_ADDR_SRC,
						    gfp);
	}

	return error;
}

/* Is this a wildcard address?  */
int sctp_is_any(struct sock *sk, const union sctp_addr *addr)
{
	unsigned short fam = 0;
	struct sctp_af *af;

	/* Try to get the right address family */
	if (addr->sa.sa_family != AF_UNSPEC)
		fam = addr->sa.sa_family;
	else if (sk)
		fam = sk->sk_family;

	af = sctp_get_af_specific(fam);
	if (!af)
		return 0;

	return af->is_any(addr);
}

/* Is 'addr' valid for 'scope'?  */
int sctp_in_scope(const union sctp_addr *addr, sctp_scope_t scope)
{
	sctp_scope_t addr_scope = sctp_scope(addr);

	/* The unusable SCTP addresses will not be considered with
	 * any defined scopes.
	 */
	if (SCTP_SCOPE_UNUSABLE == addr_scope)
		return 0;
	/*
	 * For INIT and INIT-ACK address list, let L be the level of
	 * of requested destination address, sender and receiver
	 * SHOULD include all of its addresses with level greater
	 * than or equal to L.
	 *
	 * Address scoping can be selectively controlled via sysctl
	 * option
	 */
	switch (sctp_scope_policy) {
	case SCTP_SCOPE_POLICY_DISABLE:
		return 1;
	case SCTP_SCOPE_POLICY_ENABLE:
		if (addr_scope <= scope)
			return 1;
		break;
	case SCTP_SCOPE_POLICY_PRIVATE:
		if (addr_scope <= scope || SCTP_SCOPE_PRIVATE == addr_scope)
			return 1;
		break;
	case SCTP_SCOPE_POLICY_LINK:
		if (addr_scope <= scope || SCTP_SCOPE_LINK == addr_scope)
			return 1;
		break;
	default:
		break;
	}

	return 0;
}

int sctp_is_ep_boundall(struct sock *sk)
{
	struct sctp_bind_addr *bp;
	struct sctp_sockaddr_entry *addr;

	bp = &sctp_sk(sk)->ep->base.bind_addr;
	if (sctp_list_single_entry(&bp->address_list)) {
		addr = list_entry(bp->address_list.next,
				  struct sctp_sockaddr_entry, list);
		if (sctp_is_any(sk, &addr->a))
			return 1;
	}
	return 0;
}

/********************************************************************
 * 3rd Level Abstractions
 ********************************************************************/

/* What is the scope of 'addr'?  */
sctp_scope_t sctp_scope(const union sctp_addr *addr)
{
	struct sctp_af *af;

	af = sctp_get_af_specific(addr->sa.sa_family);
	if (!af)
		return SCTP_SCOPE_UNUSABLE;

	return af->scope((union sctp_addr *)addr);
}


text:
<TITLE>Review for Silent Trigger (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Silent Trigger (1996)

reviewed by
Roger Lim

                             SILENT TRIGGER
                       A film review by Roger Lim
                        Copyright 1996 Roger Lim

Directed by: Russell Mulcahy
Produced by: Algonquin Productions
Distributed by: Filmline International Inc
Cast: Dolph Lundgren (assassin), Gina Bellman (spotter), Conrad Dunn
(security guard), Chris Heyerdahl (security guard).
Run Time: 113 minutes
Theatres:Shaw

No movie critic (except those that grew up watching Masters of the
Universe) worth his salt would give this "action-thriller" by Russell
Mulcahy a three star rating. In a year filled with scores of
action-thrillers that reads like: MISSION: IMPOSSIBLE, BROKEN ARROW,
CABLE GUY, ..... SILENT TRIGGER can at best claim to be
not-so-action-oriented action-thriller.

Starring M.I.T's Fulbright scholar cum muscleman Dolph Lundgren
(MASTERS OF THE UNIVERSE) and England based actress Gina Bellman (LEON
THE PIG FARMER), Silent Trigger revolves around a pair of hired
killers (Lundgren & Gina) staking out in a deserted skyscaper waiting
for their kill target. Receiving instructions from a mysterious figure
known only as the "Supervisor", they have to overcome a series of
stumbling blocks including two security agents who are intent on
keeping the premises safe. (Well, actually one was more intent on
getting into Bellman's pants).

The film centers on Lundgren having serious reservations about the
morality of his profession with flashbacks of a past failed
assasination attempt with Bellman haunting him. Although the
flashbacks provided much details on their past, it offered little
about what the whole movie was about. The audience spent most of their
time wondering about who these hired killers were, what organisation
they were from, and who were their targets.

As far as "action" is concerned, expect a fair amount of the usual gun
fights; blazing machine guns and the likes. My advice is, save your $7
for high tea unless you are a member of
Gina-Bellman-Admirers-Anonymous.

REVIEW's rating system:
* Wait for the video.
** A little creaky, but still better than staying at home with Gotcha!
*** Pretty good, bring a friend.
**** Amazing, potent stuff.
***** Perfection. See it twice.

Copyright REVIEW. This review was written for REVIEW
<,">http://www.silkweb.com.sg/dmedia/review/>, an online, fortnightly
Singaporean rag curiously known to insiders as Giddiness Clinic. Visit us
for a free consultation on that ringing noise in your penguin's ear.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
require 'spec_helper'
require File.expand_path("#{File.dirname __FILE__}/../../../../../lib/htty/cli/commands/address")
require File.expand_path("#{File.dirname __FILE__}/../../../../../lib/htty/cli/commands/userinfo_clear")
require File.expand_path("#{File.dirname __FILE__}/../../../../../lib/htty/cli/commands/userinfo_set")
require File.expand_path("#{File.dirname __FILE__}/../../../../../lib/htty/cli/commands/userinfo_unset")

describe HTTY::CLI::Commands::UserinfoUnset do
  describe 'class' do
    let :klass do
      subject.class
    end

    it 'should be an alias_for the expected command' do
      klass.alias_for.should == nil
    end

    it 'should have the expected aliases' do
      klass.aliases.should == [HTTY::CLI::Commands::UserinfoClear]
    end

    it 'should belong to the expected category' do
      klass.category.should == 'Navigation'
    end

    it 'should have the expected command_line' do
      klass.command_line.should == 'userinfo-u[nset]'
    end

    it 'should have the expected command_line_arguments' do
      klass.command_line_arguments.should == nil
    end

    it 'should have the expected help' do
      klass.help.should == "Removes the userinfo from the request's address"
    end

    it 'should have the expected help_extended' do
      expected = <<-end_help_extended
Removes the userinfo used for the request. Does not communicate with the host.

The console prompt shows the address for the current request.
      end_help_extended
      klass.help_extended.should == expected.chomp
    end

    it 'should have the expected see_also_commands' do
      klass.see_also_commands.should == [HTTY::CLI::Commands::UserinfoSet,
                                         HTTY::CLI::Commands::Address]
    end

    describe 'build_for' do
      it 'should correctly handle a valid, unabbreviated command line' do
        built = klass.build_for('userinfo-unset', :session => :the_session)
        built.should be_instance_of(klass)
        built.arguments.should == []
        built.session.should   == :the_session
      end

      it 'should correctly handle a valid, abbreviated command line' do
        built = klass.build_for('userinfo-u', :session => :a_session)
        built.should be_instance_of(klass)
        built.arguments.should == []
        built.session.should   == :a_session
      end

      it 'should correctly handle a command line with a bad command' do
        built = klass.build_for('x', :session => :another_session)
        built.should == nil
      end
    end
  end
end


text:
from c7n_azure.provider import resources
from c7n_azure.resources.arm import ArmResourceManager

@resources.register('batch')
class Batch(ArmResourceManager):

    class resource_type(ArmResourceManager.resource_type):
        service = 'azure.mgmt.batch'
        client = 'BatchManagementClient'
        enum_spec = ('batch_account', 'list', None)
        default_report_fields = (
            'name',
            'location',
            'resourceGroup'
        )


text:
layout: playlists
title: "Bird by Bird"
author: Anne Lammott
image: https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1394996112l/12543.jpg
amazon: https://amzn.to/3cyqsu7
---


text:
import socket

ip = "localhost"
port = 12229
buffer_size = 18

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))

while True:
    data = float(s.recv(buffer_size))
    print(data)


text:
.. _Aggregates:

================
Model Aggregates
================

.. php:namespace:: Atk4\Data\Model

.. php:class:: AggregateModel

In order to create model aggregates the AggregateModel model needs to be used:

Grouping
--------

AggregateModel model can be used for grouping::

    $aggregate = new AggregateModel($orders)->setGroupBy(['country_id']);

`$aggregate` above is a new object that is most appropriate for the model's persistence and which can be manipulated
in various ways to fine-tune aggregation. Below is one sample use::

    $aggregate = new AggregateModel($orders);
    $aggregate->addField('country');
    $aggregate->setGroupBy(['country_id'], [
            'count' => ['expr' => 'count(*)', 'type' => 'integer'],
            'total_amount' => ['expr' => 'sum([amount])', 'type' => 'atk4_money'],
        ],
    );

    // $aggregate will have following rows:
    // ['country' => 'UK', 'count' => 20, 'total_amount' => 123.2];
    // ..

Below is how opening balance can be built::

    $ledger = new GeneralLedger($db);
    $ledger->addCondition('date', '<', $from);

    // we actually need grouping by nominal
    $ledger->setGroupBy(['nominal_id'], [
        'opening_balance' => ['expr' => 'sum([amount])', 'type' => 'atk4_money'],
    ]);


text:
package main

import (
	"log"
	"os"
	"strconv"

	"github.com/hongrich/glog"
	"github.com/hongrich/revel"
	"github.com/hongrich/revel/harness"
)

var cmdRun = &Command{
	UsageLine: "run [import path] [run mode] [port]",
	Short:     "run a Revel application",
	Long: `
Run the Revel web application named by the given import path.

For example, to run the chat room sample application:

    revel run github.com/hongrich/revel/samples/chat dev

The run mode is used to select which set of app.conf configuration should
apply and may be used to determine logic in the application itself.

Run mode defaults to "dev".

You can set a port as an optional third parameter.  For example:

    revel run github.com/hongrich/revel/samples/chat prod 8080`,
}

func init() {
	cmdRun.Run = runApp
}

func runApp(args []string) {
	if len(args) == 0 {
		errorf("No import path given.\nRun 'revel help run' for usage.\n")
	}

	// Determine the run mode.
	mode := "dev"
	if len(args) >= 2 {
		mode = args[1]
	}

	// Find and parse app.conf
	revel.Init(mode, args[0], "")
	revel.LoadModules()
	revel.LoadMimeConfig()

	// Set working directory to BasePath, to make relative paths convenient and
	// dependable.
	if err := os.Chdir(revel.BasePath); err != nil {
		log.Fatalln("Failed to change directory into app path: ", err)
	}

	// Determine the override port, if any.
	port := revel.HttpPort
	if len(args) == 3 {
		var err error
		if port, err = strconv.Atoi(args[2]); err != nil {
			errorf("Failed to parse port as integer: %s", args[2])
		}
	}

	glog.Infof("Running %s (%s) in %s mode", revel.AppName, revel.ImportPath, mode)
	glog.V(1).Info("Base path: ", revel.BasePath)

	// If the app is run in "watched" mode, use the harness to run it.
	if revel.Config.BoolDefault("watch", true) && revel.Config.BoolDefault("watch.code", true) {
		revel.HttpPort = port
		harness.NewHarness().Run() // Never returns.
	}

	// Else, just build and run the app.
	app, err := harness.Build()
	if err != nil {
		errorf("Failed to build app: %s", err)
	}
	app.Port = port
	app.Cmd().Run()
}


text:
/*
Title: Code Deploy FAQs
*/

## Code Deploy FAQs

Q: What is AWS CodeDeploy?
AWS CodeDeploy is a service that automates code deployments to any instance, including Amazon EC2 instances and instances running on-premises. AWS CodeDeploy makes it easier for you to rapidly release new features, helps you avoid downtime during deployment, and handles the complexity of updating your applications. You can use AWS CodeDeploy to automate deployments, eliminating the need for error-prone manual operations, and the service scales with your infrastructure so you can easily deploy to one instance or thousands.

Q: Who should use AWS CodeDeploy?
AWS CodeDeploy is designed for developers and administrators who need to deploy applications to any instance, including Amazon EC2 instances and instances running on-premises. It is flexible and can also be used by anyone wanting to update software or run scripts on their instances.

Q: What types of applications can be deployed with AWS CodeDeploy?
AWS CodeDeploy can be used for deploying any type of application. To use AWS CodeDeploy, you specify the files to copy and the scripts to run on each instance during the deployment. AWS CodeDeploy is programming language and architecture agnostic, so you can use scripts for any custom deployment logic.

Q: What operating systems does AWS CodeDeploy support?
AWS CodeDeploy supports a wide variety of operating systems. AWS CodeDeploy provides agents that have been tested on Amazon Linux, Ubuntu Server, and Microsoft Windows Server. If you want to use other operating systems, the AWS CodeDeploy agent is available as open source software here. For more information on operating system support, see AWS CodeDeploy Documentation.

Q:Will AWS CodeDeploy work with my existing tool chain?
Yes. AWS CodeDeploy works with a variety of configuration management systems, continuous integration and deployment systems, and source control systems. For more information, see product integrations page.

Q: How is AWS CodeDeploy different from other AWS deployment and management services such as AWS Elastic Beanstalk and AWS OpsWorks?
AWS CodeDeploy is a building block service focused on helping developers deploy and update software on any instance, including Amazon EC2 instances and instances running on-premises. AWS Elastic Beanstalk and AWS OpsWorks are end-to-end application management solutions.

Q: Does AWS CodeDeploy support on-premises instances?
Yes. AWS CodeDeploy supports any instance that can install the CodeDeploy agent and connect to AWS public endpoints.

Updates.


text:
Current version: 2014.10.3.2

[![Build Status](https://drone.io/github.com/iggyvolz/korra-dl/status.png)](https://drone.io/github.com/iggyvolz/korra-dl/latest)

Download episodes of The Legend of Korra on the terminal, directly from the Nickelodeon API!

Prerequisites
=============
*ffmpeg
*python (2 or 3)
*git (optional)

If not pre-installed, all three of these can be installed quickly using [brew][1], [apt-get][2], or [chocolatey][3].  Run `(brew install/sudo apt-get install/cinst) ffmpeg python git`

Note: Mac already includes python and git, so there is no need to install these using brew.

Additional note: Ubuntu felt the need to rename ffmpeg and make changes to it.  To install the actual ffmpeg, run `sudo apt-add-repository ppa:jon-severinsson/ffmpeg;sudo apt-get update` before attempting to install ffmpeg.

Another additional note: Has not been tested on Windows.  Windows support is experimental as I don't have a Windows computer.  Feel free to report issues or make pull requests.

How to run
==========
Run the following script to install to /usr/local/bin/korra-dl:
```bash
curl https://raw.githubusercontent.com/iggyvolz/korra-dl/go/install|python
```
You can also clone the repo and run ./build to build from the episodes folder.

The syntax is korra-dl [episode number] [output type] [output file].

Output types
============
Nick offers 7 output types for download, and these are all available using the output type parameter (the second parameter).  The higher the format number, the better quality the video is, and the longer it takes to download:
| Format | Width | Height | Bitrate |
|--------|-------|--------|---------|
| 1      | 384   | 216    | 300     |
| 2      | 384   | 216    | 400     |
| 3      | 512   | 288    | 750     |
| 4      | 640   | 360    | 1200    |
| 5      | 768   | 432    | 1700    |
| 6      | 960   | 540    | 2200    |
| 7      | 1280  | 720    | 3500    |

[1]: http://brew.sh
[2]: http://www.ubuntu.com/
[3]: http://chocolatey.org/
[4]: https://raw.githubusercontent.com/iggyvolz/fetch-dl/master/fetch-dl


text:
define([
    "../lib/Matrix",
    "../lib/NdArray",
    "../lib/linearmodel/Linearmodel"
], function (Matrix, NdArray, LinearModel) {

    function fitlm(variables, response) {

        var variablesNdArray, responseNdArray;

        if (variables.type === "TABLE") {
            variablesNdArray = Matrix.mergeHorizontal(variables.data.map(function(m) { return new Matrix(m); }));
        } else {
            variablesNdArray = new NdArray(variables);
        }

        if (response.type === "TABLE") {
            responseNdArray = Matrix.mergeHorizontal(response.data.map(function(m) { return new Matrix(m); }));
        } else {
            responseNdArray = new Matrix(response);
        }

        var linearModel = new LinearModel(variablesNdArray, responseNdArray);
        linearModel.fit();

        return linearModel;

    }

    fitlm.async = false;
    fitlm.shortHelp = "Perform regression analysis by fitting a linear model to the input data.";
    fitlm.help = "# fitlm\n\n" +
        "Perform regression analysis by fitting a linear model to the input data.\n\n" +
        "## Syntax \n\n" +
        "```\nlinearModel = fitlm(X,y) \n" +
        "```\n\n" +
        "## Description\n\n" +
        "Creates a linear model.\n\n" +
        "### Inputs       \n\n" +
        "- `X` -- the input data. A matrix or table with the independent values. Each row represents a sample, and the columns are the measurements of the independent variables. \n" +
        "- `Y` -- the response values. A column or row vector of the dependent variable.\n\n" +
        "### Output       \n\n" +
        "`linearModel` -- an object which represents the result of the regression analysis. It can be used with the `display` or `predict` functions.\n         \n" +
        "## Examples\n\n" +
        "```\n" +
        "X = [1,2;2,2;3,1]\n" +
        "y = [8;10;9]\n" +
        "linearModel = fitlm(X,y)\n" +
        "display(linearModel)\n" +
        "```";

    return fitlm;

});


text:
from django.utils.translation import get_language

def get_language_upper(lang=None):
    lang = lang if lang else get_language()
    if lang.find('-') >= 0:
        lang = lang[:2].lower() + '-' + lang[3:].upper()
    return lang


text:
"use strict";

var util = require("./util");
var wrap = util.wrap;
var TrieAscoltatore = require("./trie_ascoltatore");
var AbstractAscoltatore = require('./abstract_ascoltatore');
var SubsCounter = require("./subs_counter");
var debug = require("debug")("ascoltatori:mongodb");
var mongo = require('mongodb');
var MongoClient = require('mongodb').MongoClient;
var BSON = mongo.BSONPure;
var async = require("async");

/**
 * MongoAscoltatore is a class that inherits from AbstractAscoltatore.
 * It is implemented through the `mongoskin` package.
 *
 * The options are:
 * `url`: the mongodb url (default: 'mongodb://localhost:27017/ascoltatori?auto_reconnect')
 * `pubsubCollection`: where to store the messages on mongodb (default: pubsub)
 * `mongo`: settings for the mongodb connection
 *
 * @api public
 * @param {Object} opts The options object
 */
var MongoAscoltatore = function(opts) {
  AbstractAscoltatore.call(this);

  if (typeof opts.db === 'string' || opts.uri) {
    // old options
    opts.uri = opts.uri || 'mongodb://127.0.0.1/';
    opts.db = opts.db || 'ascoltatori';
    opts.url = opts.uri + opts.db + '?auto_reconnect';
    delete opts.db;
  }

  this._opts = opts || {};
  this.url = this._opts.url || 'mongodb://127.0.0.1/ascoltatori?auto_reconnect';
  this._pubsubCollection = opts.pubsubCollection || 'pubsub';
  this.mongoOpts = this._opts.mongo || {};

  this._ascoltatore = new TrieAscoltatore(opts);

  this.channels = {};
  this._closed = false;

  this.wait = this._opts.wait || 100;

  this.connectionParams = {
    capped: true,
    size: this._opts.size || 10 * 1024 * 1024, // 10 MB
    max: this._opts.max || 1000 // documents
  };

  var that = this;

  var setupDB = function(err, db) {
    if (err) {
      that.emit('error', err);
      return;
    }

    that.db = db;

    // creating the capped collection where we can exchange messages
    that.db.createCollection(that._pubsubCollection, that.connectionParams, function(err, collection) {
      if (err) {
        that.emit('error', err);
      } else  {
        that.collection = collection;

        // be sure to have a capped collection on the run
        that.db.executeDbCommand({
          "convertToCapped": that._pubsubCollection,
          size: that.connectionParams.size,
          max: that.connectionParams.max
        }, function ready() {
          debug('ready');

          // create a new object id. We will get all the events from now on
          that._poll(new BSON.ObjectID());

          that.emit('ready');
        });
      }
    });
  };

  if (opts.db) {
    setupDB(null, opts.db);
  } else {
    MongoClient.connect(this.url, this.mongoOpts, setupDB);
  }
};

/**
 * Inheriting
 *
 * @api private
 */
MongoAscoltatore.prototype = Object.create(AbstractAscoltatore.prototype);

MongoAscoltatore.prototype.publish = function(topic, message, options, done) {
  this._raiseIfClosed();
  message = message || "";
  done = done || function() {};

  var messageObj = {
    value: message,
    topic: topic,
    options: options
  };

  debug('publishing message: ' + message + ' on ' + topic + '...');

  this.collection.insert(messageObj, { w: 1 }, done);
};

/**
 *
 * @return {Boolean} true when the user is not connected with mongodb
 * @private
 */
MongoAscoltatore.prototype._disconnected = function() {
  return this.db.db.state === 'disconnected';
};

/**
 * Used to avoid to continue to go on if an error occurs
 *
 * @param die if true, avoid to keep going and just report the error
 * @param callback real callback to call
 * @return {Function} simply exit
 * @private
 */
MongoAscoltatore.prototype._handle = function(die, callback) {

  debug('handle');

  var that = this;

  return function() {
    if (that._disconnected()) {
      debug('disconnected');
      return;
    }

    var args = [].slice.call(arguments),
      err = args.shift();

    if (err && !that._closed) {
      that.emit('error', err);
    }

    if (err && die) {
      debug('ERROR: ' + err);
      return;
    }

    debug('handle -> calling the callback');
    callback.apply(that, args);
  };
};

MongoAscoltatore.prototype.subscribe = function(topic, callback, done) {
  this._raiseIfClosed();

  debug('subscribe');
  this._ascoltatore.subscribe(topic, callback, done);
};

/**
 * function to poll from mongodb for the infos
 * @param latest starting id to look at
 * @private
 */
MongoAscoltatore.prototype._poll = function(latest) {
  debug('poll');

  var options = {
    tailable: true,
    awaitdata: true,
    numberOfRetries: -1
  };

  this._cursor = this.collection.find({ _id: { $gte: latest } }, options);

  // we have created only the cursor, now take a look at the messages arrived until now
  this._more(latest);
};

/**
 *
 * @param {ObjectID} latest as above, first id to use as reference
 * @private
 */
MongoAscoltatore.prototype._more = function(latest) {
  var that = this;

  debug('more');

  that._cursor.each(that._handle(true, function(doc) {

    var value;

    if (!doc) {
      debug('setting the subscriber polling');
      that._pollTimeout = setTimeout(function() {
        that._poll(latest);
      }, that.wait);
      return;
    }

    debug('calling the subscriber callback');

    latest = doc._id;

    if (!that._closed) {
      if (doc.value && doc.value.buffer) {
        value = doc.value.buffer;
      } else {
        value = doc.value;
      }

      that._ascoltatore.publish(doc.topic, value, doc.options);
    }
  }));
};

MongoAscoltatore.prototype.unsubscribe = function() {
  this._raiseIfClosed();
  this._ascoltatore.unsubscribe.apply(this._ascoltatore, arguments);
};

MongoAscoltatore.prototype.unsub = MongoAscoltatore.prototype.unsubscribe;

MongoAscoltatore.prototype.close = function close(done) {
  var that = this;
  var closeEmbedded = function() {
    that._ascoltatore.close(function() {
      that.emit("closed");
      if (done) {
        done();
      }
    });
  };

  if (this._pollTimeout) {
    clearTimeout(this._pollTimeout);
  }

  that._closed = true;

  async.series([
    function(cb) {
      if (that._cursor) {
        that._cursor.close(cb);
        delete that._cursor;
      } else {
        cb();
      }
    },
    function(cb) {
      that.db.close(cb);
    }
  ], closeEmbedded);
};

util.aliasAscoltatore(MongoAscoltatore.prototype);

/**
 * Exports the MongoAscoltatore
 *
 * @api public
 */
module.exports = MongoAscoltatore;


text:
namespace MassTransit.Transports
{
    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using Context;
    using GreenPipes;
    using Pipeline;

    public class PublishPipeContextAdapter<T> :
        IPipe<SendContext<T>>
        where T : class
    {
        readonly T _message;
        readonly IPublishObserver _observer;
        readonly IPipe<PublishContext<T>> _pipe;
        readonly IPublishPipe _publishPipe;
        readonly Uri _sourceAddress;
        readonly ConsumeContext _consumeContext;
        PublishContext<T> _context;

        public PublishPipeContextAdapter(IPipe<PublishContext<T>> pipe, IPublishPipe publishPipe, IPublishObserver observer, Uri sourceAddress,
            ConsumeContext consumeContext, T message)
        {
            _pipe = pipe;
            _publishPipe = publishPipe;
            _observer = observer;
            _sourceAddress = sourceAddress;
            _consumeContext = consumeContext;
            _message = message;
        }

        public PublishPipeContextAdapter(IPipe<PublishContext> pipe, IPublishPipe publishPipe, IPublishObserver observer, Uri sourceAddress,
            ConsumeContext consumeContext, T message)
        {
            _pipe = pipe;
            _publishPipe = publishPipe;
            _observer = observer;
            _sourceAddress = sourceAddress;
            _consumeContext = consumeContext;
            _message = message;
        }

        public PublishPipeContextAdapter(IPublishPipe publishPipe, IPublishObserver observer, Uri sourceAddress, ConsumeContext consumeContext, T message)
        {
            _pipe = Pipe.Empty<PublishContext<T>>();
            _publishPipe = publishPipe;
            _observer = observer;
            _sourceAddress = sourceAddress;
            _consumeContext = consumeContext;
            _message = message;
        }

        void IProbeSite.Probe(ProbeContext context)
        {
            _pipe.Probe(context);
        }

        public async Task Send(SendContext<T> context)
        {
            if (_consumeContext != null)
                context.TransferConsumeContextHeaders(_consumeContext);

            context.SourceAddress = _sourceAddress;

            var publishContext = new PublishContextProxy<T>(context, context.Message);
            var firstTime = Interlocked.CompareExchange(ref _context, publishContext, null) == null;

            await _publishPipe.Send(publishContext).ConfigureAwait(false);

            await _pipe.Send(publishContext).ConfigureAwait(false);

            if (firstTime)
                await _observer.PrePublish(publishContext).ConfigureAwait(false);
        }

        public Task PostPublish()
        {
            return _observer.PostPublish(_context ?? GetDefaultPublishContext());
        }

        public Task PublishFaulted(Exception exception)
        {
            return _observer.PublishFault(_context ?? GetDefaultPublishContext(), exception);
        }

        PublishContext<T> GetDefaultPublishContext()
        {
            return new FaultedPublishContext<T>(_message, CancellationToken.None)
            {
                SourceAddress = _sourceAddress,
                ConversationId = _consumeContext?.ConversationId,
                InitiatorId = _consumeContext?.CorrelationId,
                Mandatory = _context?.Mandatory ?? false
            };
        }
    }
}


text:
#ifndef _KINBAND_H
#define _KINBAND_H

#ifdef __cplusplus  /* wrapper to enable C++ usage */
extern "C" {
#endif

#include <kinsol/kinsol_direct.h>
#include <sundials/sundials_band.h>

/*
 * -----------------------------------------------------------------
 * Function : KINBand
 * -----------------------------------------------------------------
 * A call to the KINBand function links the main solver with the
 * KINBAND linear solver. Its arguments are as follows:
 *
 * kinmem - pointer to the integrator memory returned by KINCreate.
 *
 * N      - problem size
 *
 * mupper - upper bandwidth of the band Jacobian
 *
 * mlower - lower bandwidth of the band Jacobian
 *
 * The return value of KINBand is one of:
 *    KINDLS_SUCCESS   if successful
 *    KINDLS_MEM_NULL  if the kinsol memory was NULL
 *    KINDLS_MEM_FAIL  if there was a memory allocation failure
 *    KINDLS_ILL_INPUT if a required vector operation is missing
 *                        or if a bandwidth has an illegal value.
 * -----------------------------------------------------------------
 */

SUNDIALS_EXPORT int KINBand(void *kinmem, long int N, long int mupper, long int mlower);

#ifdef __cplusplus
}
#endif

#endif


text:
int main()
{
  printf("#define SIZEOF_INT %d\n",(int)sizeof(int));
  printf("#define SIZEOF_LONG %d\n",(int)sizeof(long));
#ifdef HAVE_LONGLONG
  printf("#define SIZEOF_LONG_LONG %d\n",(int)sizeof(long long));
#else
  printf("#define SIZEOF_LONG_LONG %d\n",0);
#endif
  return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:clickable="true"
    android:focusable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp"
    card_view:cardCornerRadius="3dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        >

        <ImageView
            android:id="@+id/local_cor_lateral"
            android:layout_width="5dp"
            android:layout_height="match_parent"
            />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/color_cinza"
            android:orientation="vertical">

            <TextView
                android:id="@+id/local_subtitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/color_shadow"
                android:gravity="center"
                android:padding="8dp"
                android:textColor="@color/color_black"
                android:text="Modelo"
                style="@style/Base.TextAppearance.AppCompat.Small"/>

            <TextView
                android:id="@+id/local_title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="16dp"
                android:textColor="@color/color_black"
                android:text="AAA-4444"
                android:textSize="35sp"
                style="@style/Base.TextAppearance.AppCompat.Body2"/>

        </LinearLayout>

    </LinearLayout>

</android.support.v7.widget.CardView>


text:
package fr.agilespirit.lovelylegacy.infra.context;

/**
 * User:    Jérémy Buget
 * Email:   jbuget@agile-spirit.fr
 * Twitter: @jbuget
 * GitHub:  https://github.com/AgileSpirit/
 * Date:    09/09/2014
 */
public abstract class SpringBean {

}


text:
from cobwebs.mq.core import RPCLink, TopicsLink
from cobwebs.mq.backends.rabbitmq import driver
import pytest
import spider
import json
from unittest import mock

HOST = "127.0.0.1"

def test_driver_instance():
    assert isinstance(driver.rpc, RPCLink)
    assert isinstance(driver.topics, TopicsLink)

@mock.patch("cobwebs.mq.backends.rabbitmq")
def test_rpc(rabbitmq):
    request = {"action": "list", "data": None}
    result = rabbitmq.rpc.send("db_driver", json.dumps(request), HOST)
    rabbitmq.rpc.send.assert_called_with("db_driver", json.dumps(request), HOST)

@mock.patch("cobwebs.mq.backends.rabbitmq")
def test_topic(rabbitmq):
    result = rabbitmq.topic.emit(key="test", message="this is just a message")
    rabbitmq.topic.emit.assert_called_with(key="test",
                                           message="this is just a message")


text:
package edu.utah.ece.async.ibiosim.gui.analysisView.incrementalsim;

/**
 *
 * @author Chris Myers
 * @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
 * @version %I%
 */
public class EventQueueElement {
	private double time;
	private double delayVal;
	private String eventID;
	private double priorityVal;

	public EventQueueElement(double time, String eventID, double delayVal, double priorityVal ) {
		this.time = time;
		this.delayVal = delayVal;
		this.eventID = eventID;
		this.priorityVal = priorityVal;
	}

	public double getScheduledTime(){
		return time+delayVal;
	}

	public String getEventId(){
		return eventID;
	}

	public double getPriorityVal() {
		return priorityVal;
	}

}


text:
<title>
Arizona vigilantes' call to arms
</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>

<?php include "../../legacy-includes/TopLogo.htmlf" ?>

<?php include "../../legacy-includes/TopAd.htmlf" ?>

<?php include "../../legacy-includes/LeftButtons.htmlf" ?>

<?php include "../../legacy-includes/BodyInsert.htmlf" ?>

Arizona vigilantes' call to arms

January 17, 2003 | Page 2

IMMIGRANT BASHERS have a friend in the Tombstone Tumbleweed, a newspaper based in Cochise County, Ariz. Late last year, under the headline "Enough is Enough: A Public Call to Arms," the paper urged the formation of a militia to stop illegal immigration.

The paper's call comes on the heels of a rash of vigilante murders in Arizona. Since June, the bodies of at least 10 immigrants have been discovered in the desert near Phoenix, Ariz.--most with their hands bound and shot in the back of the head, reportedly by two men wearing camouflage fatigues.

"To have the official newspaper of the county call on people to take up arms is very dangerous, very frightening," said Tucson human rights activist Isabel Garcia. "Law enforcement and public officials should be concerned."

They should be--but don't hold your breath. Cochise County Sheriff Larry Dever is publicly friendly with groups like the American Border Patrol--which sends out night patrols of as many as 50 people armed with semi-automatic weapons to hunt undocumented immigrants. Dever even acknowledged attending and speaking at the group's meetings--but says that his presence should be seen as a "voice of reason" rather than support for their "methodology."

<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>

<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>


text:
/*Generated By KISSY Module Compiler*/
config({
'editor/plugin/strike-through': {requires: ['editor/plugin/font/ui','editor/plugin/strike-through/cmd','editor/plugin/button']}
});


text:
from django.shortcuts import render
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required

from .models import Queue
from ..entries.models import Entry

@login_required
def active_queues(request):
    context = {}

    return render(request, 'queues/active_queues.html', context)

@login_required
def all_queues(request):
    context = {}
    queues = Queue.objects.filter(owner=request.user.id)
    context['queues'] = queues

    return render(request, 'queues/all_queues.html', context)

@login_required
def queue_detail(request, id):
    context = {}

    return render(request, 'queues/queue_detail.html', context)

@login_required
def manage_queue(request, id):
    context = {}

    queue = Queue.objects.get(id=id)
    entries = Entry.objects.filter(queue=queue, active=True)

    context['queue'] = queue
    context['entries'] = entries

    return render(request, 'queues/manage_queue.html', context)


text:
using CDesignInfoSys.Toolshed.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Threading;
using System.IO;

namespace ProjectEstimationTool.Classes
{
    /// <summary>
    /// Stores an item in the recently used files list.
    /// </summary>
    internal struct RecentlyUsedFileItem
    {
        #region Fields
        /// <summary>
        /// Path to the file
        /// </summary>
        private readonly String mFilePath;
        #endregion // Fields

        #region Construction
        /// <summary>
        /// Construct an instance of the type
        /// </summary>
        /// <param name="filePath">
        /// Path to the file.
        /// </param>
        public RecentlyUsedFileItem(String filePath)
        {
            mFilePath = filePath;
        }

        /// <summary>
        /// Gets the stored file path.
        /// </summary>
        public String FilePath => mFilePath;

        /// <summary>
        /// Gets the file name without the directory path.
        /// </summary>
        public String FileName
        {
            get
            {
                if (String.IsNullOrEmpty(mFilePath)) return null;
                return Path.GetFileName(mFilePath);
            }
        }

        /// <summary>
        /// Gets a flag to indicate if the item is in use.
        /// </summary>
        public Boolean IsUsed => !String.IsNullOrWhiteSpace(mFilePath);
        #endregion // Construction
    } // struct RecentlyUsedFileItem
} // namespace ProjectEstimationTool.Classes


text:
/**
 *  \file   edma_event.h
 *
 *  \brief  EDMA event enumeration
 *
*/

/*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/
*/
/*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*    Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*
*    Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in the
*    documentation and/or other materials provided with the
*    distribution.
*
*    Neither the name of Texas Instruments Incorporated nor the names of
*    its contributors may be used to endorse or promote products derived
*    from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
*  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
*  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
*  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
*  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/

#ifndef _EDMAEVENT_H
#define _EDMAEVENT_H

#include "hw_types.h"

#ifdef __cplusplus
extern "C" {
#endif
/****************************************************************************
**                       MACRO DEFINITIONS
****************************************************************************/

/********************* Direct Mapped Events ********************************/

/* MMCSD1 transmit event. */
#define EDMA3_CHA_MMCSD1_TX               (2u)
/* MMCSD1 receive event. */
#define EDMA3_CHA_MMCSD1_RX               (3u)

/* Events for McASP 1*/
#define EDMA3_CHA_MCASP1_TX               (10u)
#define EDMA3_CHA_MCASP1_RX               (11u)

/* MCSPI0 Channel 0 transmit event */
#define EDMA3_CHA_MCSPI0_CH0_TX           (16u)
/* MCSPI0 Channel 0 receive event */
#define EDMA3_CHA_MCSPI0_CH0_RX           (17u)
/* MCSPI0 Channel 1 transmit event */
#define EDMA3_CHA_MCSPI0_CH1_TX           (18u)
/* MCSPI0 Channel 1 receive event */
#define EDMA3_CHA_MCSPI0_CH1_RX           (19u)

/* MMCSD0 transmit event. */
#define EDMA3_CHA_MMCSD0_TX               (24u)
/* MMCSD0 receive event. */
#define EDMA3_CHA_MMCSD0_RX               (25u)

/* UART0 Transmit Event. */
#define EDMA3_CHA_UART0_TX                (26u)
/* UART0 Receive Event. */
#define EDMA3_CHA_UART0_RX                (27u)

/* UART1 Transmit Event. */
#define EDMA3_CHA_UART1_TX                (28u)
/* UART1 Receive Event. */
#define EDMA3_CHA_UART1_RX                (29u)

/* UART2 Transmit Event. */
#define EDMA3_CHA_UART2_TX                (30u)
/* UART2 Receive Event. */
#define EDMA3_CHA_UART2_RX                (31u)

/* MCSPI1 Channel 0 transmit event */
#define EDMA3_CHA_MCSPI1_CH0_TX           (42u)
/* MCSPI1 Channel 0 receive event */
#define EDMA3_CHA_MCSPI1_CH0_RX           (43u)
/* MCSPI1 Channel 1 transmit event */
#define EDMA3_CHA_MCSPI1_CH1_TX           (44u)
/* MCSPI1 Channel 1 receive event */
#define EDMA3_CHA_MCSPI1_CH1_RX           (45u)
/* I2C0 Transmit Event */
#define EDMA3_CHA_I2C0_TX                 (58u)
/* I2C0 Receive Event */
#define EDMA3_CHA_I2C0_RX                 (59u)
/* I2C1 Receive Event */
#define EDMA3_CHA_I2C1_TX                 (60u)
/* I2C1 Transmit Event */
#define EDMA3_CHA_I2C1_RX                 (61u)

/********************** Crossbar Mapped Events ********************************/
/* I2C2 Receive Event */
#define EDMA3_CHA_HSI2C2_RX               (4u)
/* I2C2 Transmit Event */
#define EDMA3_CHA_HSI2C2_TX               (3u)

/* UART3 Transmit Event. */
#define EDMA3_CHA_UART3_TX                (7u)
/* UART3 Receive Event. */
#define EDMA3_CHA_UART3_RX                (8u)

/* UART4 Transmit Event. */
#define EDMA3_CHA_UART4_TX                (9u)
/* UART4 Receive Event. */
#define EDMA3_CHA_UART4_RX                (10u)

/* UART5 Transmit Event. */
#define EDMA3_CHA_UART5_TX                (11u)
/* UART5 Receive Event. */
#define EDMA3_CHA_UART5_RX                (12u)

/*
**EDMA Event number list
*/
#ifdef __cplusplus
}
#endif

#endif


text:
"""Add order fields for DV

Revision ID: 80d36c1e37e2
Revises: 77422a4d8e14
Create Date: 2019-03-05 14:16:11.937122

"""
import model.utils
import sqlalchemy as sa
from alembic import op

from rdr_service.participant_enums import OrderStatus

# revision identifiers, used by Alembic.
revision = "80d36c1e37e2"
down_revision = "77422a4d8e14"
branch_labels = None
depends_on = None

def upgrade(engine_name):
    globals()["upgrade_%s" % engine_name]()

def downgrade(engine_name):
    globals()["downgrade_%s" % engine_name]()

def upgrade_rdr():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column(
        "participant_summary", sa.Column("sample_order_status_dv_1sal2", model.utils.Enum(OrderStatus), nullable=True)
    )
    op.add_column(
        "participant_summary", sa.Column("sample_order_status_dv_1sal2_time", model.utils.UTCDateTime(), nullable=True)
    )
    # ### end Alembic commands ###

def downgrade_rdr():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("participant_summary", "sample_order_status_dv_1sal2_time")
    op.drop_column("participant_summary", "sample_order_status_dv_1sal2")
    # ### end Alembic commands ###

def upgrade_metrics():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

def downgrade_metrics():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###


text:
<?php

/**
 * This interface should be implemented by classes that want to comunicate with
 * the visitors module
 *
 * @author Wouter Sioen <wouter.sioen@wijs.be>
 */
interface FrontendVisitorsInterface
{
	/**
	 * Gets the url for an item with a certain id
	 * This will work with internal and external url's
	 *
	 * @param int $id
	 * @return string
	 */
	public static function getUrlForVisitors($id);
}