text:
export function pexpire(key: string, milliseconds: number) {
  if (!this.data.has(key)) {
    return 0;
  }

  this.expires.set(key, milliseconds + Date.now());

  return 1;
}

redpajama_set_name: RedPajamaGithub


text:
from pyramid.i18n import get_localizer
from pyramid.events import (
    NewRequest,
    BeforeRender,
    subscriber,
)

DEFAULT_TRANSLATION_DOMAIN = 'osmtm'

@subscriber(BeforeRender)
def add_renderer_globals(event):
    request = event['request']
    event['_'] = request.translate
    # ngettext is used to define a translatable plural string as one of the
    # supported keywords by Babel """https://github.com/mitsuhiko/babel/blob/
    # master/babel/messages/extract.py#L34"""
    event['ngettext'] = request.plural_translate
    event['localizer'] = request.localizer

@subscriber(NewRequest)
def add_localizer(event):
    request = event.request
    localizer = get_localizer(request)

    def auto_translate(*args, **kwargs):
        # set the default domain if not provided by the context
        kwargs.setdefault('domain', DEFAULT_TRANSLATION_DOMAIN)

        return localizer.translate(*args, **kwargs)

    def auto_plural_translate(*args, **kwargs):
        # set the default domain if not provided by the context
        kwargs.setdefault('domain', DEFAULT_TRANSLATION_DOMAIN)

        return localizer.pluralize(*args, **kwargs)

    request.localizer = localizer
    request.translate = auto_translate
    request.plural_translate = auto_plural_translate

@subscriber(NewRequest)
def setAcceptedLanguagesLocale(event):
    if not event.request.accept_language:
        return
    accepted = event.request.accept_language
    event.request._LOCALE_ = accepted.best_match(
        event.request.registry.settings.available_languages.split(),
        event.request.registry.settings.default_locale_name)

def custom_locale_negotiator(request):
    """ The :term:`custom locale negotiator`. Returns a locale name.

    - First, the negotiator looks for the ``_LOCALE_`` attribute of
      the request object (possibly set by a view or a listener for an
      :term:`event`).

    - Then it looks for the ``request.params['_LOCALE_']`` value.

    - Then it looks for the ``request.cookies['_LOCALE_']`` value.

    - Then it looks for the ``Accept-Language`` header value,
      which is set by the user in his/her browser configuration.

    - Finally, if the locale could not be determined via any of
      the previous checks, the negotiator returns the
      :term:`default locale name`.
    """

    name = '_LOCALE_'
    if request.params.get(name) is not None:
        return request.params.get(name)
    if request.cookies.get(name) is not None:
        return request.cookies.get(name)
    return request.accept_language.best_match(
        request.registry.settings.available_languages.split(),
        request.registry.settings.default_locale_name)


text:
#include "StackTrace.h"
#include "Log.h"
#include "LinkedList.h"

#include "Clients.h"
#include "Thread.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#if defined(WIN32)
#define snprintf _snprintf
#endif

/*BE
def STACKENTRY
{
	n32 ptr STRING open "name"
	n32 dec "line"
}

defList(STACKENTRY)
BE*/

#define MAX_STACK_DEPTH 50
#define MAX_FUNCTION_NAME_LENGTH 30
#define MAX_THREADS 255

typedef struct
{
	unsigned long threadid;
	char name[MAX_FUNCTION_NAME_LENGTH];
	int line;
} stackEntry;

typedef struct
{
	unsigned long id;
	int maxdepth;
	int current_depth;
	stackEntry callstack[MAX_STACK_DEPTH];
} threadEntry;

#include "StackTrace.h"

static int thread_count = 0;
static threadEntry threads[MAX_THREADS];
static threadEntry *cur_thread = NULL;

#if defined(WIN32)
mutex_type stack_mutex;
#else
static pthread_mutex_t stack_mutex_store = PTHREAD_MUTEX_INITIALIZER;
static mutex_type stack_mutex = &stack_mutex_store;
#endif

int setStack(int create)
{
	int i = -1;
	thread_id_type curid = Thread_getid();

	cur_thread = NULL;
	for (i = 0; i < MAX_THREADS && i < thread_count; ++i)
	{
		if (threads[i].id == curid)
		{
			cur_thread = &threads[i];
			break;
		}
	}

	if (cur_thread == NULL && create && thread_count < MAX_THREADS)
	{
		cur_thread = &threads[thread_count];
		cur_thread->id = curid;
		cur_thread->maxdepth = 0;
		cur_thread->current_depth = 0;
		++thread_count;
	}
	return cur_thread != NULL; /* good == 1 */
}

void StackTrace_entry(const char* name, int line, int trace_level)
{
	Thread_lock_mutex(stack_mutex);
	if (!setStack(1))
		goto exit;
	if (trace_level != -1)
		Log_stackTrace(trace_level, 9, cur_thread->id, cur_thread->current_depth, name, line, NULL);
	strncpy(cur_thread->callstack[cur_thread->current_depth].name, name, sizeof(cur_thread->callstack[0].name)-1);
	cur_thread->callstack[(cur_thread->current_depth)++].line = line;
	if (cur_thread->current_depth > cur_thread->maxdepth)
		cur_thread->maxdepth = cur_thread->current_depth;
	if (cur_thread->current_depth >= MAX_STACK_DEPTH)
		Log(LOG_FATAL, -1, "Max stack depth exceeded");
exit:
	Thread_unlock_mutex(stack_mutex);
}

void StackTrace_exit(const char* name, int line, void* rc, int trace_level)
{
	Thread_lock_mutex(stack_mutex);
	if (!setStack(0))
		goto exit;
	if (--(cur_thread->current_depth) < 0)
		Log(LOG_FATAL, -1, "Minimum stack depth exceeded for thread %lu", cur_thread->id);
	if (strncmp(cur_thread->callstack[cur_thread->current_depth].name, name, sizeof(cur_thread->callstack[0].name)-1) != 0)
		Log(LOG_FATAL, -1, "Stack mismatch. Entry:%s Exit:%s\n", cur_thread->callstack[cur_thread->current_depth].name, name);
	if (trace_level != -1)
	{
		if (rc == NULL)
			Log_stackTrace(trace_level, 10, cur_thread->id, cur_thread->current_depth, name, line, NULL);
		else
			Log_stackTrace(trace_level, 11, cur_thread->id, cur_thread->current_depth, name, line, (int*)rc);
	}
exit:
	Thread_unlock_mutex(stack_mutex);
}

void StackTrace_printStack(char* dest)
{
	FILE* file = stdout;
	int t = 0;

	for (t = 0; t < thread_count; ++t)
	{
		threadEntry *cur_thread = &threads[t];

		if (cur_thread->id > 0)
		{
			int i = cur_thread->current_depth - 1;

			fprintf(file, "=========== Start of stack trace for thread %lu ==========\n", cur_thread->id);
			if (i >= 0)
			{
				fprintf(file, "%s (%d)\n", cur_thread->callstack[i].name, cur_thread->callstack[i].line);
				while (--i >= 0)
					fprintf(file, "   at %s (%d)\n", cur_thread->callstack[i].name, cur_thread->callstack[i].line);
			}
			fprintf(file, "=========== End of stack trace for thread %lu ==========\n\n", cur_thread->id);
		}
	}
	if (file != stdout && file != stderr && file != NULL)
		fclose(file);
}

char* StackTrace_get(unsigned long threadid)
{
	int bufsize = 256;
	char* buf = NULL;
	int t = 0;

	if ((buf = malloc(bufsize)) == NULL)
		goto exit;
	buf[0] = '\0';
	for (t = 0; t < thread_count; ++t)
	{
		threadEntry *cur_thread = &threads[t];

		if (cur_thread->id == threadid)
		{
			int i = cur_thread->current_depth - 1;
			int curpos = 0;

			if (i >= 0)
			{
				curpos += snprintf(&buf[curpos], bufsize - curpos -1,
						"%s (%d)\n", cur_thread->callstack[i].name, cur_thread->callstack[i].line);
				while (--i >= 0)
					curpos += snprintf(&buf[curpos], bufsize - curpos -1,
							"   at %s (%d)\n", cur_thread->callstack[i].name, cur_thread->callstack[i].line);
				if (buf[--curpos] == '\n')
					buf[curpos] = '\0';
			}
			break;
		}
	}
exit:
	return buf;
}


text:
package hu.deik.boozepal.service.impl.test;

import java.util.Arrays;
import java.util.List;

import javax.ejb.EJB;

import org.hamcrest.Matchers;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.container.ClassContainer;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;

import hu.deik.boozepal.arquillian.container.ArquillianContainer;
import hu.deik.boozepal.common.entity.DrinkType;
import hu.deik.boozepal.common.entity.DrinkTypeEnum;
import hu.deik.boozepal.common.vo.DrinkStatisticsVO;
import hu.deik.boozepal.core.repo.DrinkRepository;
import hu.deik.boozepal.core.repo.DrinkTypeRepository;
import hu.deik.boozepal.service.DrinkTypeService;
import hu.deik.boozepal.service.UserService;
import hu.deik.boozepal.service.impl.DrinkTypeServiceImpl;
import hu.deik.boozepal.service.impl.UserServiceImpl;
import hu.deik.boozepal.service.statistics.DrinkStatisticsService;
import hu.deik.boozepal.service.statistics.impl.AbstractStatisticsService;
import hu.deik.boozepal.service.statistics.impl.DrinkStatisticsServiceImpl;

@RunWith(Arquillian.class)
public class DrinkStatisticsServiceIT extends ArquillianContainer {

    private static Class<?>[] testClasses = { UserService.class, UserServiceImpl.class, DrinkTypeService.class,
            DrinkTypeServiceImpl.class, DrinkTypeRepository.class, DrinkRepository.class, DrinkStatisticsVO.class,
            DrinkStatisticsService.class, DrinkStatisticsServiceImpl.class, AbstractStatisticsService.class };

    @Deployment
    public static Archive<WebArchive> createDeployment() {
        Archive<WebArchive> deployment = ArquillianContainer.createDeployment();
        ((ClassContainer<WebArchive>) deployment).addClasses(testClasses);
        return deployment;
    }

    private static final String VODKA = "vodka";
    private static final String RUM = "rum";
    private static final String BEER = "beer";

    @EJB
    private UserService userService;

    @EJB
    private DrinkTypeService drinkTypeService;

    @EJB
    private DrinkStatisticsService drinkStatisticsService;

    @Test
    public void testGetTheFavouriteDrinkType() {
        DrinkTypeEnum theFavouriteDrinkType = drinkStatisticsService.getTheFavouriteDrinkType();
        Assert.assertEquals(DrinkTypeEnum.RUM, theFavouriteDrinkType);
    }

    @Test
    public void testGetDrinkStatistics() {
        // given

        // drinks in db
        // users in db
        // drink types in db
        DrinkStatisticsVO beerTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.BEER, 2);
        DrinkStatisticsVO rumTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.RUM, 3);
        DrinkStatisticsVO vodkaTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.VODKA, 0);
        DrinkStatisticsVO champagneTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.CHAMPAGNE, 0);
        DrinkStatisticsVO brandyTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.BRANDY, 0);
        DrinkStatisticsVO ginTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.GIN, 0);
        DrinkStatisticsVO wine = new DrinkStatisticsVO(DrinkTypeEnum.WINE, 0);
        DrinkStatisticsVO whiskey = new DrinkStatisticsVO(DrinkTypeEnum.WHISKEY, 0);
        DrinkStatisticsVO unknown = new DrinkStatisticsVO(DrinkTypeEnum.UNKNOWN, 0);

        // when
        List<DrinkStatisticsVO> drinkStatistics = drinkStatisticsService.getDrinkStatistics();

        // then
        Assert.assertThat(Arrays.asList(beerTypeStat, rumTypeStat, vodkaTypeStat, champagneTypeStat, wine, whiskey,
                unknown, ginTypeStat, brandyTypeStat), Matchers.containsInAnyOrder(drinkStatistics.toArray()));

    }

    @Test
    public void testGetDrinksTopList() {
        List<DrinkStatisticsVO> topList = drinkStatisticsService.getDrinksTopList();
        // Beer type
        DrinkStatisticsVO beerTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.BEER, 2);
        // Rum type
        DrinkStatisticsVO rumTypeStat = new DrinkStatisticsVO(DrinkTypeEnum.RUM, 3);
        // Assert in ORDER
        Assert.assertEquals(Arrays.asList(rumTypeStat, beerTypeStat), topList);
    }
}


text:
Version 2.0.13 by Volodymyr Volynets

	<time class="change_log_date_commit" datetime="2018-09-29">2018-09-29</time>

Framework

	Enhancement #1060 (Added ability to override Registry.)

Change Log

	Enhancement #1060 (Updated Change Log.)

Repository / Git:
	Name: Numbers\Framework
	Title: Numbers Framework
	Version: 2.0.12
	Last Tag: 2.0.12
	User Name: Volodymyr Volynets
	User Email: volodymyr.volynets@gmail.com
Statistics:
	Addition: 89
	Deletion: 23
Modules:
	Change Log (Numbers\ChangeLog, 1.0.7)                                                     |    43   14
		   13    0	 | .numbers/Framework/Helper/Cmd.php
		   29   13	 | .numbers/Framework/Helper/File.php
		    1    1	 | .numbers/module.ini
	Numbers Framework (Numbers\Framework, 2.0.12)                                             |    46    9
		    8    0	 | Db.php
		   11    1	 | Functions.php
		   27    8	 | Registry.php


text:
'''
Created on 29.07.2015

@author: mEDI

import or update data from http://eddb.io/archive/v3/systems.json
'''
import os

from datetime import datetime, timedelta
import json

import gzip
import io
import sys

try:
    from _version import __buildid__, __version__, __builddate__, __toolname__, __useragent__
except ImportError:
    __buildid__ = "UNKNOWN"
    __version__ = "UNKNOWN"
    __builddate__ = "NONE"
    __toolname__ = "mEDI s Elite Tools"
    __useragent__ = '%s/%s (%s) %s(%s)' % (__toolname__.replace(" ", ""), __version__, sys.platform, __buildid__, __builddate__.replace(" ", "").replace("-", "").replace(":", ""))

try:
    import urllib2
except ImportError:
    import urllib.request as urllib2

class loader(object):
    '''
    classdocs
    '''
    mydb = None

    def __init__(self, mydb):
        '''
        Constructor
        '''
        self.mydb = mydb

    def importData(self, filename=None):
        print("import %s" % filename)

        fp = open(filename)
        josnData = json.load(fp)
        fp.close()

        if not josnData:
            return

        cur = self.mydb.cursor()

        # build systemCache
        cur.execute("select id, System, modified from systems")
        result = cur.fetchall()
        systemCache = {}
        for system in result:
            systemCache[ system["System"].lower() ] = [system["id"], system["modified"]]
        result = None

        insertCount = 0
        updateCount = 0
        totalCount = 0
        updateSystem = []
        for system in josnData:
            totalCount += 1
            modified = datetime.fromtimestamp(system["updated_at"])

            powerID = None
            if system["power_control_faction"]:
                powerID = self.mydb.getPowerID(system["power_control_faction"])
                if not powerID:
                    cur.execute("insert or IGNORE into powers (Name) values (?) ", (system["power_control_faction"], ))
                    powerID = self.mydb.getPowerID(system["power_control_faction"])

            allegianceID = self.mydb.getAllegianceID(system["allegiance"], True)

            governmentID = self.mydb.getGovernmentID(system["government"], True)

            if system["name"].lower() not in systemCache:
                insertCount += 1
                cur.execute("insert or IGNORE into systems (System, posX, posY, posZ, permit, power_control, government, allegiance, modified) values (?,?,?,?,?,?,?,?,?) ",
                                        (system["name"], float(system["x"]), float(system["y"]), float(system["z"]), system["needs_permit"], powerID, governmentID, allegianceID, modified))

            elif system["name"].lower() in systemCache and (not systemCache[ system["name"].lower() ][1] or systemCache[ system["name"].lower() ][1] < modified):
                updateCount += 1
                updateSystem.append([system["name"], float(system["x"]), float(system["y"]), float(system["z"]), system["needs_permit"], powerID, governmentID, allegianceID, modified, systemCache[ system["name"].lower() ][0] ])

        if updateSystem:
            cur.executemany("update systems SET System=?, posX=?, posY=?, posZ=?, permit=?, power_control=?, government=?, allegiance=?, modified=? where id is ?", updateSystem)

        if updateCount or insertCount:
            print("update", updateCount, "insert", insertCount, "from", totalCount, "systems")

        self.mydb.con.commit()
        cur.close()

    def filenameFromUrl(self, url):

        filename = url.split("/").pop()

        return filename

    def update(self):
        eddbUrl_systems = "http://eddb.io/archive/v3/systems.json"
        storageDir = "db"

        filename = self.filenameFromUrl(eddbUrl_systems)
        filename = os.path.join(storageDir, filename)

        if os.path.isfile(filename):

            cDate = datetime.fromtimestamp(os.path.getmtime(filename))

            if cDate < datetime.now() - timedelta(hours=1):
                self.updateFromUrl(filename, eddbUrl_systems)

        else:  # download file not exists
            self.updateFromUrl(filename, eddbUrl_systems)

        # self.importData(filename)
#        self.updateFromUrl(filename, eddbUrl_systems)

    def updateFromUrl(self, filename, url):
        if not url:
            return

        print("download %s" % url)

        request = urllib2.Request(url)
        request.add_header('User-Agent', __useragent__)
        request.add_header('Accept-encoding', 'gzip')
        response = urllib2.urlopen(request)
        if response.info().get('Content-Encoding') == 'gzip':
            # print("gzip ok")
            buf = io.BytesIO(response.read())
            f = gzip.GzipFile(fileobj=buf)
        else:
            # print("none")
            f = response

        wfp = open(filename, "wb")
        wfp.write(f.read())
        wfp.close()

        if response.info().get('content-type').split("; ")[0] == "application/json":
            self.importData(filename)
        else:
            print("download error?")
            print(response.info().items())


text:
import java.util.Scanner;

public class Solution{
    public static void main(String args[]){
        Scanner s = new Scanner(System.in);
        String raw;
        raw = s.nextLine();
        //int i=0;
        while(repeat(raw)){
            //System.out.println(i+" : "+raw);i++;
            raw = process(raw);
        }
        boolean lock = true;
        try{
            char ch = raw.charAt(0);
        }catch(Exception e){
            System.out.println("Empty String");lock=false;
        }
        if(lock){
            System.out.println(raw);
        }
    }
    public static boolean repeat(String src){
        for(int i=0;i<=src.length()-2;i++){
            if(src.charAt(i)==src.charAt(i+1)){
                return true;
            }
        }
        return false;
    }
    public static String process(String src){
        String dummy=null;
        for(int i=0;i<=src.length()-2;i++){
            if(src.charAt(i)==src.charAt(i+1)){
                dummy = src.substring(0,i)+src.substring(i+2,src.length());
                break;
            }
        }
        return dummy;
    }
}


text:
@interface FYNKeyboardCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UILabel *lab;
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgWidth;
@property (nonatomic, assign) FYNKeyboardCellType type;
@end


text:
"""
Defines the entities in a Control Flow Graph
"""

class Numeric:
    """Base class for Variables & Constants"""
    pass

class Variable (Numeric):

    def __init__(self, name):
        """
        :param str name: The name of a variable is as same as in the source code
        """
        assert(isinstance(name, str))
        self.name = name

class Constant (Numeric):

    def __init__(self, value):
        """
        :param int value: the numeric value of a constant
        """
        assert(isinstance(value, int))
        self.value = value
        self.name = str(value)

class Operation:
    """
    Represents a binary operation
    """
    def __init__(self, name):
        assert(name == '<' or \
                name == '>' or \
                name == '<=' or \
                name == '>=' or \
                name == '==' or \
                name == '!=' or\
                name == '+' or \
                name == '*' or \
                name == '/' or \
                name == '-' or \
                name == '%')
        self.name = name

    def __eq__(self, other):
        return (self.name == other.name)

class Instruction:
    """Base class for all Instructions"""
    pass

class CmpInstruction (Instruction):
    """
    Represents instructions of the format: 'a = b op c' where\
            op can be <, >, <=, >=, ==, !=
    'a' has to be a Variable, where as 'b' & 'c' can be a variable or a constant
    """

    def __init__(self, lhs, rhs_1, rhs_2, op):
        """
        :type lhs: Variable
        :type rhs_1: Numeric
        :type rhs_2: Numeric
        :type op: Operation
        """
        assert(op == Operation('<') or \
                op == Operation('>') or \
                op == Operation('<=') or \
                op == Operation('>=') or \
                op == Operation('==') or \
                op == Operation('!='))
        assert(isinstance(lhs, Variable) and \
                isinstance(rhs_1, Numeric) and \
                isinstance(rhs_2, Numeric))
        self.lhs = lhs
        self.rhs_1 = rhs_1
        self.rhs_2 = rhs_2
        self.op = op

class ArithInstruction(Instruction):
    """
    Represents instructions of the format: 'a = b op c' where\
            op can be +, *, /, -, %
    'a' has to be a Variable, where as 'b' & 'c' can be a variable or a constant
    """

    def __init__(self, lhs, rhs_1, rhs_2, op):
        """
        :type lhs: Variable
        :type rhs_1: Numeric
        :type rhs_2: Numeric
        :type op: Operation
        """
        assert(op == Operation('+') or \
                op == Operation('*') or \
                op == Operation('/') or \
                op == Operation('-') or \
                op == Operation('%'))
        assert(isinstance(lhs, Variable) and \
                isinstance(rhs_1, Numeric) and \
                isinstance(rhs_2, Numeric))
        self.lhs = lhs
        self.rhs_1 = rhs_1
        self.rhs_2 = rhs_2
        self.op = op

class EqInstruction(Instruction):
    """
    Represents instuctions of the format: 'a = b'
    """

    def __init__(self, lhs, rhs):
        """
        :type lhs: Variable
        :type rhs: Numeric
        """
        assert(isinstance(lhs, Variable) and isinstance(rhs, Numeric))
        self.lhs = lhs
        self.rhs = rhs
        return

class BasicBlock:

    """
    Represents a basic block in the Control Flow Graph

    :param used_variables: A list of all variables which come in the RHS of any\
            instruction in the basic block. Example, if a instruction 'a = 3 + b'\
            is a part of the basic block, then 'b'  would be added in this list
    :type used_variables: list(Variable)

    :param defined_variables: A list of all variables which come in the LHS of any\
            instruction in the basic block. Example, if a instruction 'a = 3 _ b'\
            is a part of the basic blocl, then 'a' would be added to this list
    :type defined_variables: list(Variable)

    :param child_true: The exit basic block in case the condition evaluates to True
    :type child_true: BasicBlock

    :param child_false: The exit basic block in case the condition evaluates to False
    :type child_false: BasicBlock

    :param instruction_list: The list of instructions which form this basic block
    :type instruction_list: list(Instruction)

    :param int identity: Unique identity which identifies this basic block
    """

    def __init__(self):
        self.identity = 0
        self.condition = None
        self.condition_instr = None
        self.child_true = None
        self.child_false = None
        self.used_variables = []
        self.defined_variables = []
        self.instruction_list = []

    def add_instruction (self, instr):
        """
        Adds the argument instruction in the list of instructions of this basic block.

        Also updates the variable lists (used_variables, defined_variables)
        """
        assert(isinstance(instr, Instruction))
        self.instruction_list.append(instr)
        if instr.lhs not in self.defined_variables:
            if isinstance(instr.lhs, Variable):
                self.defined_variables.append(instr.lhs)
        if isinstance(instr, EqInstruction):
            if isinstance(instr.rhs, Variable):
                if instr.rhs not in self.used_variables:
                    self.used_variables.append(instr.rhs)
        else:
            if isinstance(instr.rhs_1, Variable):
                if instr.rhs_1 not in self.used_variables:
                    self.used_variables.append(instr.rhs_1)
            if isinstance(instr.rhs_2, Variable):
                if instr.rhs_2 not in self.used_variables:
                    self.used_variables.append(instr.rhs_2)

    def set_condition(self, condition, condition_instr=None):
        """
        Defines the condition which decides how the basic block exits

        :param condition:
        :type condition:

        :param condition_instr: If the 'condition' argument is a Variable, then\
                condition_instr is None, else, condition_instr should be\
                of type CmpInstruction
        :type condition_instr: CmpInstruction
        """
        assert(isinstance(condition, Numeric))
        if condition_instr is not None:
            assert(isinstance(condition_instr, CmpInstruction))
        self.condition = condition
        self.condition_instr = condition_instr
        if condition_instr is not None:
            if condition_instr.lhs not in self.defined_variables:
                if isinstance(condition_instr.lhs, Variable):
                    self.defined_variables.append(condition_instr.lhs)
            if isinstance(condition_instr.rhs_1, Variable):
                if condition_instr.rhs_1 not in self.used_variables:
                    self.used_variables.append(condition_instr.rhs_1)
            if isinstance(condition_instr.rhs_2, Variable):
                if condition_instr.rhs_2 not in self.used_variables:
                    self.used_variables.append(condition_instr.rhs_2)

    def clean_up(self):
        if self.child_true == self.child_false:
            self.child = self.child_true
            if(self.child == None):
                self.number_of_children = 0
            else:
                self.number_of_children = 1
        else:
            self.number_of_children = 2

class Function:

    """A function in the CFG is a collection of interconnected\
            basic blocks
    :param basic_block_list: A list of basic blocks contained in the function
    :type basic_block_list: list(BasicBlock)

    :param variable_list: A list of variables which are defined or used in the function
    :type variable_list: list(Variable)

    :param input_variable_list: A list of variables whose initial which are passed as argument\
            to the function in the source code. The initial values of these variables is known
    :type input_variable_list: list(Variable)

    :param output_variable_list: A list of variables which are returned by the function
    :type output_variable_list: list(Variable)
    """
    def __init__(self):
        self.basic_block_list = []
        self.variable_list = []
        self.input_variable_list = []
        self.output_variable_list = []
        self.summary = ""

    def add_basic_block(self, basic_block):
        """Adds the given basic block in the function"""
        assert(isinstance(basic_block, BasicBlock))
        self.basic_block_list.append(basic_block)

    def clean_up(self):
        identity = 0
        for basic_block in self.basic_block_list:
            basic_block.clean_up()
            basic_block.identity = identity
            identity += 1

    def get_variable(self, var_name):
        """
        If a variable with the name var_name exists in this function's variable list, \
                then that variable object is returned; else a new variable is created\
                with the given name and added to the variable list of this function\
                and returned back

        :returns: A variable which has the its name as var_name
        :rype: Variable
        """
        assert(isinstance(var_name, str))
        if isinstance(var_name, str):
            for var in self.variable_list:
                if var.name == var_name:
                    return var
            new_var = Variable(var_name)
            self.variable_list.append(new_var)
            return new_var

    def add_input_variable(self, var):
        """Adds the argument variable as one of the input variable"""
        assert(isinstance(var, Variable))
        self.input_variable_list.append(var)

    def add_output_variable(self, var):
        """Adds the argument variable as one of the output variable"""
        assert(isinstance(var, Variable))
        self.output_variable_list.append(var)

    def add_summary(self, summary_string):
        """Adds a summary description to this function"""
        assert(isinstance(summary_string, str))
        self.summary = summary_string
        return


text:
String Trio (2020)
==================

Trio for violin, viola and cello.

Written for the Abjad summer course hosted at Stanford University's CCRMA.


text:
<?php

namespace App\Controller\Api\OptOut;

use App\Domain\Entity\OptOut\OptOutDomain\OptOutDomain;
use App\Domain\Entity\OptOut\OptOutDomain\OptOutDomainRepository;
use App\Messenger\Validation;
use IteratorAggregate;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use OutOfBoundsException;

#[Route('/api/opt-out/domains')]
class OptOutDomainController
{

    #[Route('', methods: ['GET'])]
    #[IsGranted('OPTOUT_DOMAIN_LIST')]
    public function list(
        Request                $request,
        OptOutDomainRepository $optOutDomainRepository
    ): Response
    {
        $query = $request->query->get('query');
        $start = $request->query->get('start');
        $max = $request->query->get('max') ?? 20;
        $sortBy = $request->query->get('sortBy');
        $desc = $request->query->get('desc');
        $domains = $optOutDomainRepository->findAll($query, $start, $max, $sortBy, boolval($desc));

        $count = is_array($domains) ? count($domains) : $domains->count();

        if ($domains instanceof IteratorAggregate) {
            $domains = (array)$domains->getIterator();
        }

        return new JsonResponse([
            'results' => $count === 0 ? [] : $domains,
            'count' => $count,
        ]);
    }

    #[Route('', methods: ['POST'])]
    #[IsGranted('OPTOUT_DOMAIN_CREATE')]
    public function create(
        Request                $request,
        ValidatorInterface     $validator,
        OptOutDomainRepository $optOutDomainRepository
    ): Response
    {
        $body = $request->getContent();
        $data = json_decode($body, true);

        $data['domain'] = is_array($data['domain']) ? array_unique($data['domain']) : array($data['domain']);

        $domains = [];
        foreach ($data['domain'] as $domain) {
            $domainToCreate = new OptOutDomain($domain);
            $errors = $validator->validate($domainToCreate);

            if (count($errors) > 0) {
                return Validation::getViolations($errors);
            }
            $domains[] = $domainToCreate;
        }

        foreach ($domains as $domain) {
            $optOutDomainRepository->save($domain);
        }

        return new JsonResponse('Data has been added successfully!');
    }

    #[Route('/edit', methods: ['PUT'])]
    #[IsGranted('OPTOUT_DOMAIN_EDIT')]
    public function edit(
        Request                $request,
        ValidatorInterface     $validator,
        OptOutDomainRepository $optOutDomainRepository
    ): Response
    {
        $body = $request->getContent();
        $data = json_decode($body, true);

        $domainToFind = $data['dynamicID']['domain'] ?? '';
        if ($domainToFind === $data['domain']) { // if old data and new data is same

            $params = ['domain' => $data['domain']];

        } else {
            $optOutDomain = $optOutDomainRepository->findById($domainToFind);
            if (!$optOutDomain) {
                throw new OutOfBoundsException('No Opt-out domain found for ' . $domainToFind);
            }

            $optOutDomain->domain = $data['domain'] ?? '';
            $errors = $validator->validate($optOutDomain);

            if (count($errors) > 0) {
                return Validation::getViolations($errors);
            }
            $domain = $optOutDomainRepository->save($optOutDomain);

            $params = ['domain' => $domain->getDomain()];
        }
        return new JsonResponse($params);
    }

    #[Route('/delete', methods: ['DELETE'])]
    #[IsGranted('OPTOUT_DOMAIN_DELETE')]
    public function delete(
        Request                $request,
        OptOutDomainRepository $optOutDomainRepository
    ): Response
    {
        $body = $request->getContent();
        $data = json_decode($body, true);

        $domain = $data['domain'] ?? '';

        $optOutDomain = $optOutDomainRepository->findById($domain);
        if (!$optOutDomain) {
            throw new OutOfBoundsException('No Opt-out domain found for ' . $domain);
        }
        $optOutDomainRepository->delete($optOutDomain);
        return new JsonResponse('Domain deleted successfully!');
    }
}


text:
package com.datastax.driver.core.exceptions;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * Indicates an error during the authentication phase while connecting to a node.
 */
public class AuthenticationException extends DriverException {

    private static final long serialVersionUID = 0;

    private final InetSocketAddress address;

    public AuthenticationException(InetSocketAddress address, String message) {
        super(String.format("Authentication error on host %s: %s", address, message));
        this.address = address;
    }

    private AuthenticationException(String message, Throwable cause, InetSocketAddress address)
    {
        super(message, cause);
        this.address = address;
    }

    /**
     * The host for which the authentication failed.
     * <p>
     * This is a shortcut for {@code getAddress().getAddress()}.
     *
     * @return the host for which the authentication failed.
     */
    public InetAddress getHost() {
        return address.getAddress();
    }

    /**
     * The full address of the host for which the authentication failed.
     *
     * @return the host for which the authentication failed.
     */
    public InetSocketAddress getAddress() {
        return address;
    }

    @Override
    public DriverException copy() {
        return new AuthenticationException(getMessage(), this, address);
    }
}


text:
.timeslider .timeslider_wrapper {
    position:absolute;
    top:-4px;
    left:350px;
    right:20px;
}
.timeslider .jslider .jslider-value {
    top: 12px;
    z-index: 1;
}
.timeslider .jslider .jslider-value {
    visibility: hidden !important;
}
.timeslider .jslider:hover .jslider-value-from {
    visibility: visible !important;
}
.timeslider .jslider .jslider-pointer {
    cursor: auto;
}
.timeslider_more {
    position: absolute;
    top:4px;
    left: 200px;
}

.timeslider .jslider .jslider-transition {
    -webkit-transition: all 0.6s ease;
    -moz-transition: all 0.6s ease;
    -o-transition: all 0.6s ease;
    transition: all 0.6s ease;
}
.timeslider .timeslider_more .active {
    -webkit-animation-duration: 1.2s;
    animation-duration: 1.2s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
    animation-iteration-count:1;
    -webkit-animation-iteration-count:1;
}

@-webkit-keyframes tada {
    0% {-webkit-transform: scale(1);}
    10%, 20% {-webkit-transform: scale(0.9) rotate(-3deg);}
    30%, 50%, 70%, 90% {-webkit-transform: scale(1.1) rotate(3deg);}
    40%, 60%, 80% {-webkit-transform: scale(1.1) rotate(-3deg);}
    100% {-webkit-transform: scale(1) rotate(0);}
}
@keyframes tada {
    0% {transform: scale(1);}
    10%, 20% {transform: scale(0.9) rotate(-3deg);}
    30%, 50%, 70%, 90% {transform: scale(1.1) rotate(3deg);}
    40%, 60%, 80% {transform: scale(1.1) rotate(-3deg);}
    100% {transform: scale(1) rotate(0);}
}
.tada {
    -webkit-animation-name: tada;
    animation-name: tada;
}


text:
Default

		Panel is a style that is is implemented by inheriting the vertical group, just like the vertical menu.

				 Panel Heading

				The jQuery Cycle Plugin is a slideshow plugin that supports many different types of transition effect.
				It supports pause-on-hover, auto-stop, auto-fit, before/after callbacks, click triggers and much more. It also supports, but does not require, the Easing Plugin.

				Panel Footer

		The following is an example that can be implemented more simply by excluding the head and/or the foot.

						Panel Heading

						Panel Body

						Panel Body

						Panel Footer

Combine

		Panel provides a function that enables combination with other components. and that can be used instead of body.

				Panel Heading

						A	B	C	D	E

						A	B	C	D	E

						A	B	C	D	E

						A	B	C	D	E

Close

		Panel provides a closed option. The user needs to add a panel-close class as shown below.

				 Panel Heading

				Panel Body

				Panel Footer

Fit

		When you want to set the padding value in the body area to 0, add a fit class to the body.

				 Panel Heading

				The jQuery Cycle Plugin is a slideshow plugin that supports many different types of transition effects.
				It supports pause-on-hover, auto-stop, auto-fit, before/after callbacks, click triggers and much more.
				It also supports, but does not require, the Easing Plugin.

Include

		Panel can add a component such as a small button or a label to the header or the footer.

				 Panel Heading

						Select...

				Panel Body

Tab Header

		Panel can add a tab component to the header.

						Home

CSS

Script

						Menu

				Panel Body

Panel Group

		Panel Group can combine several panels as a group.

					Panel Heading

					Panel Body

					Panel Heading

					Panel Body

					Panel Heading

					Panel Body


text:
import React, { PropTypes, Component } from 'react';
import TodoTextInput from './TodoTextInput';

class Header extends Component {
  handleSave(text) {
    if (text.length > 0) {
      this.props.addTodo(text);
    }
  }

  render() {
    return (

할 일 목록

        <TodoTextInput onSave={this.handleSave.bind(this)} placeholder="할 일을 입력해주세요" />

    );
  }
}

export default Header;


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>api Examples — Matplotlib 1.3.1 documentation</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Matplotlib 1.3.1 documentation"
          href="../../_static/opensearch.xml"/>
    <link rel="top" title="Matplotlib 1.3.1 documentation" href="../../index.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

Matplotlib 1.3.1 documentation »

api Examples¶

<col class="field-name" />
<col class="field-body" />

Release:	1.3.1

Date:	May 03, 2016

agg_oo

barchart_demo

bbox_intersect

collections_demo

colorbar_only

compound_path

custom_projection_example

custom_scale_example

date_demo

date_index_formatter

demo_affine_image

donut_demo

engineering_formatter

fahrenheit_celsius_scales

font_family_rc

font_file

histogram_path_demo

image_zcoord

joinstyle

legend_demo

line_with_text

logo2

mathtext_asarray

patch_collection

quad_bezier

radar_chart

sankey_demo_basics

sankey_demo_links

sankey_demo_old

sankey_demo_rankine

scatter_piecharts

span_regions

two_scales

unicode_minus

watermark_image

watermark_text

    © Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the matplotlib development team; 2012 - 2013 The matplotlib development team.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
package pugbot.core.entities.settings.serversettings;

import pugbot.core.exceptions.BadArgumentsException;

public class SettingDCTimeout extends ServerSetting<Integer> {

	public SettingDCTimeout(long serverId, Integer value) {
		super(serverId, value);
	}

	@Override
	public String getName() {
		return "DCTimeout";
	}

	@Override
	public String getDescription() {
		return "The amount of time when a player disconnects until removal";
	}

	@Override
	public String getValueString() {
		return getValue() + " Minutes";
	}

	@Override
	public void set(String[] args) {
		if(args.length != 1){
			throw new BadArgumentsException("Only one argument is allowed");
		}

		int newValue;

		try{
			newValue = Integer.valueOf(args[0]);
		}catch(NumberFormatException ex){
			throw new BadArgumentsException("Value must be a valid integer");
		}

		if(newValue < 0){
			throw new BadArgumentsException("Value must be positive");
		}

		setValue(newValue);
	}

	@Override
	public String getSaveString() {
		return getValue().toString();
	}

}


text:
package com.budget.test.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.budget.service.ISalaireService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:META-INF/test-context.xml")
public class SalaireListServiceTest {

	@Autowired
	ISalaireService salaireService;

	@Test
	public void test(){
		System.out.println(salaireService.findAll());
	}

}


text:
module Jekyll

  class TextileConverter < Converter
    safe true

    pygments_prefix '<notextile>'
    pygments_suffix '</notextile>'

    def setup
      return if @setup
      require 'redcloth'
      @setup = true
    rescue LoadError
      STDERR.puts 'You are missing a library required for Textile. Please run:'
      STDERR.puts '  $ [sudo] gem install RedCloth'
      raise FatalException.new("Missing dependency: RedCloth")
    end

    def matches(ext)
      rgx = '(' + @config['textile_ext'].gsub(',','|') +')'
      ext =~ Regexp.new(rgx, Regexp::IGNORECASE)
    end

    def output_ext(ext)
      ".html"
    end

    def convert(content)
      setup
      RedCloth.new(content).to_html
    end
  end

end


text:
		<div id="doc-content" style="height: <?php echo $content_height; ?>px">

				public class

Simplex

							linearprogramming

Class Overview

Java implementation of the linear programming algorithm provided in
					Cormen, Leiserson, Rivest
					and Stein, Introduction to Algorithms, 3rd ed., ch. 29. In this implementation, the objective
					function and inequality constraints must be specified when a Simplex object
					is created (i.e., as arguments to its constructor). The getResult() method will then generate and return an array
					of type double that provides an optimal solution, or it will return null if the
					solution is unbounded. If there are multiple solutions to the linear program specified when a Simplex
					object is created, getResult()
					will return one such solution.

Summary

					<?php $i = 0; ?>

								Public Constructors

							<?php
								if ($i == 0) {
									echo '
';
									$i = $i + 1;
								}
								else {
									echo '
';
									$i = $i - 1;
								}
							?>

									<nobr> </nobr>

									<nobr>

										Simplex
										(double[][] A, double[] b, double[] c)
									</nobr>

					<?php $i = 0; ?>

								Public Methods

							<?php
								if ($i == 0) {
									echo '
';
									$i = $i + 1;
								}
								else {
									echo '
';
									$i = $i - 1;
								}
							?>

									<nobr>double[]</nobr>

										getResult()

Returns an optimal solution to the calling linear program.

Public Constructors

						public
						Simplex
						(double[][] A, double[] b, double[] c)

Create a Simplex object from the standard form of a linear program.

Parameters

										A
										2-dimensional array of type double representing the coefficients in
										the inequality constraints of the standard form of a linear program.

										b
										An array of type double representing the maxima given in the
										inequality constraints.

										c
										An array of type double representing the objective function of the given linear program.

Public Methods

						public void
						getResult
						()

Solve the linear program specified when the calling object was created.

Returns

an array of type double that maximizes the objective function. Or else null if
								the inequality constraints impose no bound on the objective function.


text:
(function (ng) {

    var mod = ng.module("itemModule");

    mod.controller("itemDeleteCtrl", ["$state", "item", function ($state, item) {
            this.confirmDelete = function () {
                item.remove().then(function () {
                    $state.go('itemList', null, {reload: true});
                });
            };
        }]);
})(window.angular);


text:
package org.jetbrains.plugins.scala.conversion.ast

import com.intellij.openapi.project.Project
import com.intellij.psi.PsiType
import org.jetbrains.plugins.scala.extensions.PsiTypeExt
import org.jetbrains.plugins.scala.lang.psi.types.api.{JavaArrayType, ParameterizedType}
import org.jetbrains.plugins.scala.lang.psi.types.{ScType, ScTypeExt, TypePresentationContext}
import org.jetbrains.plugins.scala.project.ProjectContext
import org.jetbrains.plugins.scala.project.ProjectContext.fromProject

import scala.collection.mutable

case class TypeConstruction(inType: String) extends TypeNode {
  def getDefaultTypeValue: String = {
    inType match {
      case "Int" | "Byte" | "Short" | "Char" => "0"
      case "Double" | "Float" => ".0"
      case "Boolean" => "false"
      case "Long" => "0L"
      case "Unit" => "{}"
      case _ => "null"
    }
  }

  override def getType: TypeConstruction = this.asInstanceOf[TypeConstruction]
}

object TypeConstruction {
  def createIntermediateTypePresentation(
    inType: PsiType,
    inProject: Project,
    textMode: Boolean,
  ): TypeNode = {
    implicit val ctx: ProjectContext = inProject

    val buffer = mutable.ArrayBuffer.empty[(IntermediateNode, Option[String])]
    //java Object should be treated as AnyRef, not Any
    val scType = inType.toScType(paramTopLevel = true, treatJavaObjectAsAny = false)
    val result = getParts(scType, buffer, textMode)

    result match {
      case parametrized: ParametrizedConstruction =>
        parametrized.associationMap = buffer.toSeq
      case array: ArrayConstruction =>
        array.associationMap = buffer.toSeq
      case _ =>
    }

    result
  }

  // get simple parts of type if type is array or parametrized
  private def getParts(
    scType: ScType,
    buffer: mutable.ArrayBuffer[(IntermediateNode, Option[String])],
    textMode: Boolean
  )(
    implicit ctx: ProjectContext
  ): TypeNode = {
    implicit val tpc: TypePresentationContext = TypePresentationContext.emptyContext
    scType match {
      case p@ParameterizedType(des, args) =>
        val typeConstruction: IntermediateNode = TypeConstruction(ctx.typeSystem.presentableText(des, withPrefix = textMode))
        buffer += ((typeConstruction, p.extractClass.flatMap(el => Option(el.getQualifiedName))))
        val argsOnLevel = args.map(getParts(_, buffer, textMode))
        ParametrizedConstruction(typeConstruction, argsOnLevel)
      case JavaArrayType(argument) =>
        ArrayConstruction(getParts(argument, buffer, textMode))
      case otherType =>
        val typeConstruction: TypeNode = TypeConstruction(ctx.typeSystem.presentableText(otherType, withPrefix = textMode))
        buffer += ((typeConstruction, otherType.extractClass.flatMap(el => Option(el.getQualifiedName))))
        typeConstruction
    }
  }
}

case class ParametrizedConstruction(iNode: IntermediateNode, parts: Seq[IntermediateNode]) extends TypeNode {
  var associationMap = Seq.empty[(IntermediateNode, Option[String])]

  override def getType: TypeConstruction = iNode.asInstanceOf[TypedElement].getType
}

case class ArrayConstruction(iNode: IntermediateNode) extends TypeNode {
  var associationMap = Seq.empty[(IntermediateNode, Option[String])]

  override def getType: TypeConstruction = iNode.asInstanceOf[TypedElement].getType
}

case class DisjunctionTypeConstructions(parts: Seq[IntermediateNode]) extends TypeNode {
  override def getType: TypeConstruction = this.asInstanceOf[TypeConstruction]
}

case class TypeParameterConstruction(name: NameIdentifier, typez: Seq[IntermediateNode]) extends IntermediateNode

case class TypeParameters(data: Seq[IntermediateNode]) extends IntermediateNode


text:
> A PHP build tool based on Apache Ant.

- Perform the default task in the "build.xml" file:

`phing`

- Initialise a new build file:

`phing -i {{path/to/build.xml}}`

- Perform a specific task:

`phing {{task_name}}`

- Specify a custom build file path:

`phing -f {{path/to/build.xml}} {{task_name}}`

- Specify a log file to output to:

`phing -b {{path/to/log_file}} {{task_name}}`

- Specify custom properties to use in the build:

`phing -D{{property}}={{value}} {{task_name}}`

- Specify a custom listener class:

`phing -listener {{class_name}} {{task_name}}`

- Build using verbose output:

`phing -verbose {{task_name}}`


text:
import FlexberryEnum from 'ember-flexberry-data/transforms/flexberry-enum';
import tTypeOperationTypeEnum from '../enums/new-platform-flexberry-audit-big-data-audit-operation-type';

export default FlexberryEnum.extend({
  enum: tTypeOperationTypeEnum
});


text:
#include <stdio.h>
//#include <string.h>
/*
La funcion fgets toma una entrada de caracteres de la
entrada.
En este ejemplo, cadena es el nombre del arreglo de caracteres,
sizeof cadena es la cantidad de texto en la entrada más uno;
y stdin es el nombre del dispositivo estandar de entrada.
*/

void main()
{
  char cadena[5];

  puts("Escriba un texto:");
  fgets(cadena, sizeof cadena, stdin);
  puts("El texto escrito es:");
  puts(cadena);
}


text:
set -e

unset AZURE_CLI_DIAGNOSTICS_TELEMETRY
pip install azure-storage==0.36.0

wd=`cd $(dirname $0); pwd`

if [ -z $PUBLISH_STORAGE_SAS ] || [ -z $PUBLISH_STORAGE_ACCT ] || [ -z $PUBLISH_CONTAINER ]; then
    echo 'Missing publish storage account credential. Skip publishing to store.'
    exit 0
fi

echo 'Generate artifacts'
. $wd/artifacts.sh

echo 'Upload artifacts to store'
python $wd/publish.py store -b $share_folder -c $PUBLISH_CONTAINER -a $PUBLISH_STORAGE_ACCT -s $PUBLISH_STORAGE_SAS

if [ -z $EDGE_STORAGE_SAS ] || [ -z $EDGE_STORAGE_ACCT ] || [ -z $EDGE_CONTAINER ]; then
    echo 'Missing edge storage account credential. Skip publishing the edge build.'
    exit 0
fi

echo 'Upload artifacts to edge feed'
python $wd/publish.py nightly -b $share_folder -c $EDGE_CONTAINER -a $EDGE_STORAGE_ACCT -s $EDGE_STORAGE_SAS


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;

namespace Orleans.Streams
{
    internal interface IStreamSubscriptionHandle
    {
        Task<StreamHandshakeToken> DeliverItem(object item, StreamSequenceToken currentToken, StreamHandshakeToken handshakeToken);
        Task<StreamHandshakeToken> DeliverBatch(IBatchContainer item, StreamHandshakeToken handshakeToken);
        Task CompleteStream();
        Task ErrorInStream(Exception exc);
        StreamHandshakeToken GetSequenceToken();
    }

    /// <summary>
    /// The extesion multiplexes all stream related messages to this grain between different streams and their stream observers.
    ///
    /// On the silo, we have one extension object per activation and this extesion multiplexes all streams on this activation
    ///     (streams of all types and ids: different stream ids and different stream providers).
    /// On the client, we have one extension per stream (we bind an extesion for every StreamConsumer, therefore every stream has its own extension).
    /// </summary>
    [Serializable]
    internal class StreamConsumerExtension : IStreamConsumerExtension
    {
        private readonly IStreamProviderRuntime providerRuntime;
        private readonly ConcurrentDictionary<GuidId, IStreamSubscriptionHandle> allStreamObservers; // map to different ObserversCollection<T> of different Ts.
        private readonly Logger logger;

        internal StreamConsumerExtension(IStreamProviderRuntime providerRt)
        {
            providerRuntime = providerRt;
            allStreamObservers = new ConcurrentDictionary<GuidId, IStreamSubscriptionHandle>();
            logger = providerRuntime.GetLogger(GetType().Name);
        }

        internal StreamSubscriptionHandleImpl<T> SetObserver<T>(GuidId subscriptionId, StreamImpl<T> stream, IAsyncObserver<T> observer, StreamSequenceToken token, IStreamFilterPredicateWrapper filter)
        {
            if (null == stream) throw new ArgumentNullException("stream");
            if (null == observer) throw new ArgumentNullException("observer");

            try
            {
                if (logger.IsVerbose) logger.Verbose("{0} AddObserver for stream {1}", providerRuntime.ExecutingEntityIdentity(), stream.StreamId);

                // Note: The caller [StreamConsumer] already handles locking for Add/Remove operations, so we don't need to repeat here.
                var handle = new StreamSubscriptionHandleImpl<T>(subscriptionId, observer, stream, filter, token);
                return allStreamObservers.AddOrUpdate(subscriptionId, handle, (key, old) => handle) as StreamSubscriptionHandleImpl<T>;
            }
            catch (Exception exc)
            {
                logger.Error((int)ErrorCode.StreamProvider_AddObserverException, String.Format("{0} StreamConsumerExtension.AddObserver({1}) caugth exception.",
                    providerRuntime.ExecutingEntityIdentity(), stream.StreamId), exc);
                throw;
            }
        }

        internal bool RemoveObserver(GuidId subscriptionId)
        {
            IStreamSubscriptionHandle ignore;
            return allStreamObservers.TryRemove(subscriptionId, out ignore);
        }

        public Task<StreamHandshakeToken> DeliverItem(GuidId subscriptionId, Immutable<object> item, StreamSequenceToken currentToken, StreamHandshakeToken handshakeToken)
        {
            if (logger.IsVerbose3) logger.Verbose3("DeliverItem {0} for subscription {1}", item.Value, subscriptionId);

            IStreamSubscriptionHandle observer;
            if (allStreamObservers.TryGetValue(subscriptionId, out observer))
                return observer.DeliverItem(item.Value, currentToken, handshakeToken);

            logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForItem), "{0} got an item for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.",
                providerRuntime.ExecutingEntityIdentity(), subscriptionId);
            // We got an item when we don't think we're the subscriber. This is a normal race condition.
            // We can drop the item on the floor, or pass it to the rendezvous, or ...
            return Task.FromResult(default(StreamHandshakeToken));
        }

        public Task<StreamHandshakeToken> DeliverBatch(GuidId subscriptionId, Immutable<IBatchContainer> batch, StreamHandshakeToken handshakeToken)
        {
            if (logger.IsVerbose3) logger.Verbose3("DeliverBatch {0} for subscription {1}", batch.Value, subscriptionId);

            IStreamSubscriptionHandle observer;
            if (allStreamObservers.TryGetValue(subscriptionId, out observer))
                return observer.DeliverBatch(batch.Value, handshakeToken);

            logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForBatch), "{0} got an item for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.",
                providerRuntime.ExecutingEntityIdentity(), subscriptionId);
            // We got an item when we don't think we're the subscriber. This is a normal race condition.
            // We can drop the item on the floor, or pass it to the rendezvous, or ...
            return Task.FromResult(default(StreamHandshakeToken));
        }

        public Task CompleteStream(GuidId subscriptionId)
        {
            if (logger.IsVerbose3) logger.Verbose3("CompleteStream for subscription {0}", subscriptionId);

            IStreamSubscriptionHandle observer;
            if (allStreamObservers.TryGetValue(subscriptionId, out observer))
                return observer.CompleteStream();

            logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForItem), "{0} got a Complete for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.",
                providerRuntime.ExecutingEntityIdentity(), subscriptionId);
            // We got an item when we don't think we're the subscriber. This is a normal race condition.
            // We can drop the item on the floor, or pass it to the rendezvous, or ...
            return TaskDone.Done;
        }

        public Task ErrorInStream(GuidId subscriptionId, Exception exc)
        {
            if (logger.IsVerbose3) logger.Verbose3("ErrorInStream {0} for subscription {1}", exc, subscriptionId);

            IStreamSubscriptionHandle observer;
            if (allStreamObservers.TryGetValue(subscriptionId, out observer))
                return observer.ErrorInStream(exc);

            logger.Warn((int)(ErrorCode.StreamProvider_NoStreamForItem), "{0} got an Error for subscription {1}, but I don't have any subscriber for that stream. Dropping on the floor.",
                providerRuntime.ExecutingEntityIdentity(), subscriptionId);
            // We got an item when we don't think we're the subscriber. This is a normal race condition.
            // We can drop the item on the floor, or pass it to the rendezvous, or ...
            return TaskDone.Done;
        }

        public Task<StreamHandshakeToken> GetSequenceToken(GuidId subscriptionId)
        {
            IStreamSubscriptionHandle observer;
            return Task.FromResult(allStreamObservers.TryGetValue(subscriptionId, out observer) ? observer.GetSequenceToken() : null);
        }

        internal int DiagCountStreamObservers<T>(StreamId streamId)
        {
            return allStreamObservers.Values
                                     .OfType<StreamSubscriptionHandleImpl<T>>()
                                     .Aggregate(0, (count, o) => count + (o.SameStreamId(streamId) ? 1 : 0));
        }

        internal IList<StreamSubscriptionHandleImpl<T>> GetAllStreamHandles<T>()
        {
            return allStreamObservers.Values
                .OfType<StreamSubscriptionHandleImpl<T>>()
                .Where(o => o != null)
                .ToList();
        }
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Register extends CI_Controller {

  /**
   * Index Page for this controller.
   *
   * Maps to the following URL
   *    http://example.com/index.php/welcome
   *  - or -
   *    http://example.com/index.php/welcome/index
   *  - or -
   * Since this controller is set as the default controller in
   * config/routes.php, it's displayed at http://example.com/
   *
   * So any other public methods not prefixed with an underscore will
   * map to /index.php/welcome/<method_name>
   * @see http://codeigniter.com/user_guide/general/urls.html
   */
  public function index()
  {
    if(null != $this->session->userdata('logged_in')){
      $this->load->helper('url');
      redirect('/index.php/dashboard', 'refresh');
    }
    $this->load->view('header');
    $this->load->view('register');
    $this->load->view('footer');
  }
  public function signup(){
   $this->load->database();
   $result= $this->db->query("INSERT INTO User (`username`, `description`, `zip`, `gender`, `age`, `password`)  VALUES(?, ?, ?, ?, ?, ?)", array($this->input->post("username"), $this->input->post("description"), $this->input->post("zip"), $this->input->post("gender"), $this->input->post("age"), md5($this->input->post("password"))));

    if ($result == false){
       $data = array("error_message"=> "An error occurred.");
       $this->load->view('header');
       $this->load->view('register', $data);
       $this->load->view('footer');
    }
    else{
       $data = array("success_message"=> "Account created.");
       $this->load->view("header");
       $this->load->view("login", $data);
       $this->load->view("footer");
    }
  }
  public function usernameExists(){
    $username = $this->input->post("username");

    $this->load->database();

    $this->load->model('User');
    if ($this->User->exists($username))
        echo json_encode(array("exists"=>"true"));
    else
        echo json_encode(array("exists"=>"false"));
  }
}


text:
<?php
require_once('config.php');
?>

	<meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width'>
    <title>Mobage JS SDK Login</title>

Mobage JS SDK Login

Login (Hybrid Flow)

Login (Authorization Code Grant Flow)

Login (Client-Side Flow)

Check Login Status