text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

DOCUMENTATION = r'''
---
module: bigip_smtp
short_description: Manages SMTP settings on the BIG-IP
description:
  - Allows configuring of the BIG-IP to send mail via an SMTP server by
    configuring the parameters of an SMTP server.
version_added: "1.0.0"
options:
  name:
    description:
      - Specifies the name of the SMTP server configuration.
    type: str
    required: True
  partition:
    description:
      - Device partition to manage resources on.
    type: str
    default: Common
  smtp_server:
    description:
      - SMTP server host name in the format of a fully qualified domain name.
      - This value is required when creating a new SMTP configuration.
    type: str
  smtp_server_port:
    description:
      - Specifies the SMTP port number.
      - When creating a new SMTP configuration, the default is C(25) when
        C(encryption) is C(none) or C(tls). The default is C(465) when C(ssl) is selected.
    type: int
  local_host_name:
    description:
      - Hostname used in SMTP headers in the format of a fully qualified
        domain name. This setting does not refer to the hostname of the BIG-IP system.
    type: str
  from_address:
    description:
      - Email address the email is being sent from. This is the "Reply-to"
        address the recipient sees.
    type: str
  encryption:
    description:
      - Specifies whether the SMTP server requires an encrypted connection in
        order to send mail.
    type: str
    choices:
      - none
      - ssl
      - tls
  authentication:
    description:
      - Credentials can be set on an SMTP server's configuration even if that
        authentication is not used (for example, staging configs or emergency changes).
        This parameter acts as a switch to make the specified C(smtp_server_username)
        and C(smtp_server_password) parameters active or not.
      - When C(yes), the authentication parameters are active.
      - When C(no), the authentication parameters are inactive.
    type: bool
  smtp_server_username:
    description:
      - User name the SMTP server requires when validating a user.
    type: str
  smtp_server_password:
    description:
      - Password the SMTP server requires when validating a user.
    type: str
  state:
    description:
      - When C(present), ensures the SMTP configuration exists.
      - When C(absent), ensures the SMTP configuration does not exist.
    type: str
    choices:
      - present
      - absent
    default: present
  update_password:
    description:
      - Passwords are stored encrypted, so the module cannot know if the supplied
        C(smtp_server_password) is the same or different than the existing password.
        This parameter controls the updating of the C(smtp_server_password)
        credential.
      - When C(always), the system always updates the password.
      - When C(on_create), the system only sets the password for newly created SMTP server
        configurations.
    type: str
    choices:
      - always
      - on_create
    default: always
extends_documentation_fragment: f5networks.f5_modules.f5
author:
  - Tim Rupp (@caphrim007)
'''

EXAMPLES = r'''
- name: Create a base SMTP server configuration
  bigip_smtp:
    name: my-smtp
    smtp_server: 1.1.1.1
    smtp_server_username: mail-admin
    smtp_server_password: mail-secret
    local_host_name: smtp.mydomain.com
    from_address: no-reply@mydomain.com
    state: present
    provider:
      user: admin
      password: secret
      server: lb.mydomain.com
  delegate_to: localhost
'''

RETURN = r'''
smtp_server:
  description: The new C(smtp_server) value of the SMTP configuration.
  returned: changed
  type: str
  sample: mail.mydomain.com
smtp_server_port:
  description: The new C(smtp_server_port) value of the SMTP configuration.
  returned: changed
  type: int
  sample: 25
local_host_name:
  description: The new C(local_host_name) value of the SMTP configuration.
  returned: changed
  type: str
  sample: smtp.mydomain.com
from_address:
  description: The new C(from_address) value of the SMTP configuration.
  returned: changed
  type: str
  sample: no-reply@mydomain.com
encryption:
  description: The new C(encryption) value of the SMTP configuration.
  returned: changed
  type: str
  sample: tls
authentication:
  description: Whether the authentication parameters are active or not.
  returned: changed
  type: bool
  sample: yes
'''
from datetime import datetime
from ansible.module_utils.basic import (
    AnsibleModule, env_fallback
)

from ..module_utils.bigip import F5RestClient
from ..module_utils.common import (
    F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, is_valid_hostname
)
from ..module_utils.ipaddress import is_valid_ip
from ..module_utils.icontrol import tmos_version
from ..module_utils.teem import send_teem

class Parameters(AnsibleF5Parameters):
    api_map = {
        'username': 'smtp_server_username',
        'passwordEncrypted': 'smtp_server_password',
        'localHostName': 'local_host_name',
        'smtpServerHostName': 'smtp_server',
        'smtpServerPort': 'smtp_server_port',
        'encryptedConnection': 'encryption',
        'authenticationEnabled': 'authentication_enabled',
        'authenticationDisabled': 'authentication_disabled',
        'fromAddress': 'from_address',
    }

    api_attributes = [
        'username',
        'passwordEncrypted',
        'localHostName',
        'smtpServerHostName',
        'smtpServerPort',
        'encryptedConnection',
        'authenticationEnabled',
        'authenticationDisabled',
        'fromAddress',
    ]

    returnables = [
        'smtp_server_username',
        'smtp_server_password',
        'local_host_name',
        'smtp_server',
        'smtp_server_port',
        'encryption',
        'authentication',
        'from_address',
    ]

    updatables = [
        'smtp_server_username',
        'smtp_server_password',
        'local_host_name',
        'smtp_server',
        'smtp_server_port',
        'encryption',
        'authentication',
        'from_address',
    ]

class ApiParameters(Parameters):
    pass

class ModuleParameters(Parameters):
    @property
    def local_host_name(self):
        if self._values['local_host_name'] is None:
            return None
        if is_valid_ip(self._values['local_host_name']):
            return self._values['local_host_name']
        elif is_valid_hostname(self._values['local_host_name']):
            # else fallback to checking reasonably well formatted hostnames
            return str(self._values['local_host_name'])
        raise F5ModuleError(
            "The provided 'local_host_name' value {0} is not a valid IP or hostname".format(
                str(self._values['local_host_name'])
            )
        )

    @property
    def authentication_enabled(self):
        if self._values['authentication'] is None:
            return None
        if self._values['authentication']:
            return True

    @property
    def authentication_disabled(self):
        if self._values['authentication'] is None:
            return None
        if not self._values['authentication']:
            return True

    @property
    def smtp_server_port(self):
        if self._values['smtp_server_port'] is None:
            return None
        return int(self._values['smtp_server_port'])

class Changes(Parameters):
    def to_return(self):
        result = {}
        try:
            for returnable in self.returnables:
                result[returnable] = getattr(self, returnable)
            result = self._filter_params(result)
        except Exception:
            pass
        return result

class UsableChanges(Changes):
    pass

class ReportableChanges(Changes):
    @property
    def smtp_server_password(self):
        return None

    @property
    def smtp_server_username(self):
        return None

class Difference(object):
    def __init__(self, want, have=None):
        self.want = want
        self.have = have

    def compare(self, param):
        try:
            result = getattr(self, param)
            return result
        except AttributeError:
            return self.__default(param)

    def __default(self, param):
        attr1 = getattr(self.want, param)
        try:
            attr2 = getattr(self.have, param)
            if attr1 != attr2:
                return attr1
        except AttributeError:
            return attr1

    @property
    def smtp_server_password(self):
        if self.want.update_password == 'on_create':
            return None
        return self.want.smtp_server_password

    @property
    def authentication(self):
        if self.want.authentication_enabled:
            if self.want.authentication_enabled != self.have.authentication_enabled:
                return dict(
                    authentication_enabled=self.want.authentication_enabled
                )
        if self.want.authentication_disabled:
            if self.want.authentication_disabled != self.have.authentication_disabled:
                return dict(
                    authentication_disable=self.want.authentication_disabled
                )

class ModuleManager(object):
    def __init__(self, *args, **kwargs):
        self.module = kwargs.get('module', None)
        self.client = F5RestClient(**self.module.params)
        self.want = ModuleParameters(params=self.module.params)
        self.have = ApiParameters()
        self.changes = UsableChanges()

    def _set_changed_options(self):
        changed = {}
        for key in Parameters.returnables:
            if getattr(self.want, key) is not None:
                changed[key] = getattr(self.want, key)
        if changed:
            self.changes = UsableChanges(params=changed)

    def _update_changed_options(self):
        diff = Difference(self.want, self.have)
        updatables = Parameters.updatables
        changed = dict()
        for k in updatables:
            change = diff.compare(k)
            if change is None:
                continue
            else:
                if isinstance(change, dict):
                    changed.update(change)
                else:
                    changed[k] = change
        if changed:
            self.changes = UsableChanges(params=changed)
            return True
        return False

    def should_update(self):
        result = self._update_changed_options()
        if result:
            return True
        return False

    def exec_module(self):
        start = datetime.now().isoformat()
        version = tmos_version(self.client)
        changed = False
        result = dict()
        state = self.want.state

        if state == "present":
            changed = self.present()
        elif state == "absent":
            changed = self.absent()

        reportable = ReportableChanges(params=self.changes.to_return())
        changes = reportable.to_return()
        result.update(**changes)
        result.update(dict(changed=changed))
        self._announce_deprecations(result)
        send_teem(start, self.module, version)
        return result

    def _announce_deprecations(self, result):
        warnings = result.pop('__warnings', [])
        for warning in warnings:
            self.client.module.deprecate(
                msg=warning['msg'],
                version=warning['version']
            )

    def present(self):
        if self.exists():
            return self.update()
        else:
            return self.create()

    def absent(self):
        if self.exists():
            return self.remove()
        return False

    def update(self):
        self.have = self.read_current_from_device()
        if not self.should_update():
            return False
        if self.module.check_mode:
            return True
        self.update_on_device()
        return True

    def remove(self):
        if self.module.check_mode:
            return True
        self.remove_from_device()
        if self.exists():
            raise F5ModuleError("Failed to delete the resource.")
        return True

    def create(self):
        self._set_changed_options()
        if self.module.check_mode:
            return True
        self.create_on_device()
        return True

    def exists(self):
        uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
            transform_name(self.want.partition, self.want.name)
        )
        resp = self.client.api.get(uri)
        try:
            response = resp.json()
        except ValueError as ex:
            raise F5ModuleError(str(ex))

        if resp.status == 404 or 'code' in response and response['code'] == 404:
            return False
        if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
            return True

        errors = [401, 403, 409, 500, 501, 502, 503, 504]

        if resp.status in errors or 'code' in response and response['code'] in errors:
            if 'message' in response:
                raise F5ModuleError(response['message'])
            else:
                raise F5ModuleError(resp.content)

    def create_on_device(self):
        params = self.want.api_params()
        params['name'] = self.want.name
        params['partition'] = self.want.partition
        uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
        )
        resp = self.client.api.post(uri, json=params)
        try:
            response = resp.json()
        except ValueError as ex:
            raise F5ModuleError(str(ex))

        if 'code' in response and response['code'] in [400, 403]:
            if 'message' in response:
                raise F5ModuleError(response['message'])
            else:
                raise F5ModuleError(resp.content)

    def update_on_device(self):
        params = self.want.api_params()
        uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
            transform_name(self.want.partition, self.want.name)
        )
        resp = self.client.api.patch(uri, json=params)
        try:
            response = resp.json()
        except ValueError as ex:
            raise F5ModuleError(str(ex))

        if 'code' in response and response['code'] == 400:
            if 'message' in response:
                raise F5ModuleError(response['message'])
            else:
                raise F5ModuleError(resp.content)

    def remove_from_device(self):
        uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
            transform_name(self.want.partition, self.want.name)
        )
        resp = self.client.api.delete(uri)
        if resp.status == 200:
            return True

    def read_current_from_device(self):
        uri = "https://{0}:{1}/mgmt/tm/sys/smtp-server/{2}".format(
            self.client.provider['server'],
            self.client.provider['server_port'],
            transform_name(self.want.partition, self.want.name)
        )
        resp = self.client.api.get(uri)
        try:
            response = resp.json()
        except ValueError as ex:
            raise F5ModuleError(str(ex))

        if 'code' in response and response['code'] == 400:
            if 'message' in response:
                raise F5ModuleError(response['message'])
            else:
                raise F5ModuleError(resp.content)
        return ApiParameters(params=response)

class ArgumentSpec(object):
    def __init__(self):
        self.supports_check_mode = True
        argument_spec = dict(
            name=dict(required=True),
            smtp_server=dict(),
            smtp_server_port=dict(type='int'),
            smtp_server_username=dict(no_log=True),
            smtp_server_password=dict(no_log=True),
            local_host_name=dict(),
            encryption=dict(choices=['none', 'ssl', 'tls']),
            update_password=dict(
                default='always',
                choices=['always', 'on_create']
            ),
            from_address=dict(),
            authentication=dict(type='bool'),
            partition=dict(
                default='Common',
                fallback=(env_fallback, ['F5_PARTITION'])
            ),
            state=dict(
                default='present',
                choices=['present', 'absent']
            )
        )
        self.argument_spec = {}
        self.argument_spec.update(f5_argument_spec)
        self.argument_spec.update(argument_spec)

def main():
    spec = ArgumentSpec()

    module = AnsibleModule(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode
    )

    try:
        mm = ModuleManager(module=module)
        results = mm.exec_module()
        module.exit_json(**results)
    except F5ModuleError as ex:
        module.fail_json(msg=str(ex))

if __name__ == '__main__':
    main()


text:
//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.

#ifndef Patternist_TruthPredicate_H
#define Patternist_TruthPredicate_H

#include <private/qgenericpredicate_p.h>

QT_BEGIN_NAMESPACE

namespace QPatternist
{
    /**
     * @short A predicate which is optimized for filter expressions that
     * are of type @c xs:boolean.
     *
     * @author Frans Englich <frans.englich@nokia.com>
     * @ingroup Patternist_expressions
     */
    class TruthPredicate : public GenericPredicate
    {
    public:
        /**
         * Creates a TruthPredicate which filters the items from the @p sourceExpression
         * through @p predicate.
         *
         * This constructor is protected. The proper way to create predicates is via the static
         * create() function.
         */
        TruthPredicate(const Expression::Ptr &sourceExpression,
                       const Expression::Ptr &predicate);

        inline Item mapToItem(const Item &item, const DynamicContext::Ptr &context) const
        {
            Q_ASSERT_X(false, Q_FUNC_INFO, "This is practically dead code because it never gets called in GenericPredicate, "
                                           "which binds to its own mapToItem for completely legitime reasons.");
            if(m_operand2->evaluateEBV(context))
                return item;
            else
                return Item();
        }

        inline Item::Iterator::Ptr map(const Item &item,
                                       const DynamicContext::Ptr &context) const
        {
            Q_ASSERT_X(false, Q_FUNC_INFO, "I don't expect this function to be called, for the same reasons as above.");
            if(m_operand2->evaluateEBV(context))
                return makeSingletonIterator(item);
            else
                return CommonValues::emptyIterator;
        }

        virtual SequenceType::List expectedOperandTypes() const;
        virtual ExpressionVisitorResult::Ptr accept(const ExpressionVisitor::Ptr &visitor) const;
    };
}

QT_END_NAMESPACE

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

use \Bootstart\Bootstart;

/**
 * This class handles Slack Integrations
 * @author Gustav Trenwith <gtrenwith@gmail.com>
 */
class Slack extends Bootstart
{
    /**
     * Sends a notification to Slack
     * @param string $message The message
     * @param string $channel The Slack channel
     * @param string $webhook The Slack web hook
     */
    function notification($message, $channel = null, $webhook = "")
    {
        Bootstart::registry('curl')->request(
            $webhook,
            "POST",
            "payload=".json_encode([
                "channel" => $channel,
                "text" => $message
            ])
        );
    }
}


text:
package main

import "testing"

func TestOne(t *testing.T) {
	if !PalindromeCheck("racecar") {
		t.Error("Was expecting true, got false")
	}
}

func TestTwo(t *testing.T) {
	if !PalindromeCheck("tacocat") {
		t.Error("Was expecting true, got false")
	}
}

func TestThree(t *testing.T) {
	if !PalindromeCheck("~ - | * | - ~") {
		t.Error("Was expecting true, got false")
	}
}

func TestFour(t *testing.T) {
	if PalindromeCheck("not a palindrome") {
		t.Error("Was expecting false, got true")
	}
}

func TestFive(t *testing.T) {
	if PalindromeCheck("what what") {
		t.Error("Was expecting false, got true")
	}
}

func TestEight(t *testing.T) {
	if !PalindromeCheck("evenneve") {
		t.Error("Was expecting true, got false")
	}
}

func TestNine(t *testing.T) {
	if !PalindromeCheck("") {
		t.Error("Was expecting true, got false")
	}
}


text:
package com.microsoft.applicationinsights.web.struts;

import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.microsoft.applicationinsights.web.internal.ThreadContext;
import com.microsoft.applicationinsights.internal.util.DateTimeUtils;
import com.microsoft.applicationinsights.telemetry.RequestTelemetry;
import com.microsoft.applicationinsights.web.internal.RequestTelemetryContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Created by yonisha on 3/10/2015.
 */
public class RequestNameInterceptorTests {

    private static final String HTTP_METHOD = "GET";
    private static final String ACTION_NAME = "TestAction";
    private static final String REQUEST_NAME = String.format("%s /%s", HTTP_METHOD, ACTION_NAME);

    private static ActionContext actionContext;
    private static ActionInvocation actionInvocation;
    private static RequestNameInterceptor interceptor = new RequestNameInterceptor();

    @BeforeClass
    public static void classInitialize() {
        actionInvocation = mock(ActionInvocation.class);
    }

    @Before
    public void testInitialize() {
        RequestTelemetryContext requestTelemetryContext = new RequestTelemetryContext(DateTimeUtils.getDateTimeNow().getTime());
        ThreadContext.setRequestTelemetryContext(requestTelemetryContext);
        RequestTelemetry requestTelemetry = ThreadContext.getRequestTelemetryContext().getHttpRequestTelemetry();
        requestTelemetry.setHttpMethod(HTTP_METHOD);

        // Setting mock for action context
        actionContext = mock(ActionContext.class);
        when(actionContext.getName()).thenReturn(ACTION_NAME);
        ActionContext.setContext(actionContext);
    }

    @Test
    public void testInterceptorSetRequestNameCorrectly() throws Exception {
        interceptor.intercept(actionInvocation);

        RequestTelemetry requestTelemetry = ThreadContext.getRequestTelemetryContext().getHttpRequestTelemetry();
        Assert.assertEquals(REQUEST_NAME, requestTelemetry.getName());
    }

    @Test
    public void testActionInvocationWhenExceptionThrownDuringRequestCalculation() throws Exception {

        // Mocking the ActionContext to throw exception.
        Mockito.doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                throw new Exception("FATAL!");
            }
        }).when(actionContext).getName();
        ActionContext.setContext(actionContext);

        interceptor.intercept(actionInvocation);
    }
}


text:
IDIR=./include
SDIR=./src
TDIR=./test
OUTPUT=simpleObserver
TESTS=tests
CC=gcc
CFLAGS=-I$(IDIR)
SRC=$(SDIR)/*.c

.PHONY: build clean help test

help:
	@echo "make build   - build the program"
	@echo "make clean   - clean the generated files"
	@echo "make help    - show this help message"

build:
	@$(CC) -o $(OUTPUT) $(SRC) $(CFLAGS)

test:
	#@echo "Building tests"
	#@$(CC) -o $(TESTS) $(TDIR)/*.c $(SDIR)/observer.c -I$(TDIR) $(CFLAGS)
	#@echo "Runing tests"
	#@./$(TESTS)

clean:
	@rm $(OUTPUT)
	@rm $(TESTS)


text:
// @flow

/**
 * Created by dirk-janrutten on 13/08/16.
 */

import {
    GraphQLString,
    GraphQLObjectType,
    GraphQLInt,
    GraphQLNonNull
} from 'graphql'
import {globalIdField} from 'graphql-relay'

import {nodeInterface} from './relayNode'
import {Joke} from '../../models'
import type {ID} from '../type'

export default new GraphQLObjectType({
  name: 'Joke',
  description: 'Represents a joke.',
  fields: () => ({
    id: globalIdField(
          'Joke',
          (joke: Joke): ID => joke.id
        ),
    text: {
      type: new GraphQLNonNull(GraphQLString),
      resolve: (joke: Joke): string => joke.text
    },
    funnyLevel: {
      type: new GraphQLNonNull(GraphQLInt),
      resolve: (joke: Joke): number => joke.funnyLevel
    }
  }),
    // Relay will use this function to determine if an object in your system is
    // of a particular GraphQL type
  isTypeOf: function (obj) { return obj instanceof Joke },
  interfaces: [ nodeInterface ]
})


text:
NS_ASSUME_NONNULL_BEGIN

@interface LOTBezierPath : NSObject

+ (instancetype)pathWithCGPath:(CGPathRef)path;

+ (instancetype)newPath;

- (void)LOT_moveToPoint:(CGPoint)point;

- (void)LOT_addLineToPoint:(CGPoint)point;

- (void)LOT_addCurveToPoint:(CGPoint)point
              controlPoint1:(CGPoint)cp1
              controlPoint2:(CGPoint)cp2;

- (void)LOT_closePath;

- (void)LOT_removeAllPoints;

- (void)LOT_appendPath:(LOTBezierPath *)bezierPath;

- (void)trimPathFromT:(CGFloat)fromT toT:(CGFloat)toT offset:(CGFloat)offset;

- (void)LOT_applyTransform:(CGAffineTransform)transform;

@property (nonatomic, assign) BOOL cacheLengths;

@property (nonatomic, readonly) CGFloat length;

@property (nonatomic, readonly) CGPathRef CGPath;
@property (nonatomic, readonly) CGPoint currentPoint;
@property (nonatomic) CGFloat lineWidth;
@property (nonatomic) CGLineCap lineCapStyle;
@property (nonatomic) CGLineJoin lineJoinStyle;
@property (nonatomic) CGFloat miterLimit;
@property (nonatomic) CGFloat flatness;
@property (nonatomic) BOOL usesEvenOddFillRule;
@property (readonly, getter=isEmpty) BOOL empty;
@property (nonatomic, readonly) CGRect bounds;

@end

NS_ASSUME_NONNULL_END


text:
{% include "schemaMacros.html" %}
{{ formText(name, label) }}


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <vector>

#include "vast/table_slice.hpp"

namespace vast {

/// Performs a selection (and optional projection) on a table slice.
/// @param slice The table slice to subset.
/// @param first_row The row of the first value.
/// @param num_rows The number of values to select starting from *first_fow*.
/// @param first_col The first column to begin selecion
/// @param num_cols The number of columns from *first_col*.
/// @returns A subset of *slice*, with rows in the range
///          *[first_row, first_row + num_rows)* and columns in the range
///          *[first_col, first_col + num_cols)*.
/// @see subset_events
std::vector<value> subset(
  const table_slice& slice,
  table_slice::size_type first_row = 0u,
  table_slice::size_type num_rows = table_slice::npos,
  table_slice::size_type first_col = 0u,
  table_slice::size_type num_cols = table_slice::npos);

} // namespace vast


text:
package com.dogmalabs.wonderadapter.demo.util;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import com.dogmalabs.wonderadapter.demo.db.Contract;

/**
 * Created by cesar on 28/01/14.
 */
public class CursorUtil {

  private Context context;
  private String[] projection;
  private String selection;
  private String[] selectionArgs;
  private String orderBy;

  public CursorUtil(Context context) {
    this.context = context;
  }

  public Loader<Cursor> getWondersLoader() {
    Uri uri = Contract.getContentUri(context, Contract.Cursor.Wonders.PATH_DIR);
    return new CursorLoader(context, uri, projection, selection, selectionArgs, orderBy);
  }

}


text:
#ifndef MODELMAKER_HH
#define MODELMAKER_HH

#include <list>
#include <string>

#include "sdf/sdf.h"
#include "gui/EntityMaker.hh"

namespace gazebo
{
  namespace msgs
  {
    class Visual;
  }

  namespace gui
  {
    class ModelMaker : public EntityMaker
    {
      public: ModelMaker();
      public: virtual ~ModelMaker();

      public: void InitFromModel(const std::string &_modelName);
      public: void InitFromFile(const std::string &_filename);
      public: virtual void Start(const rendering::UserCameraPtr _camera);

      public: virtual void Stop();
      public: virtual bool IsActive() const;

      public: virtual void OnMousePush(const common::MouseEvent &_event);
      public: virtual void OnMouseRelease(const common::MouseEvent &_event);
      public: virtual void OnMouseDrag(const common::MouseEvent &_event);
      public: virtual void OnMouseMove(const common::MouseEvent &_event);

      private: virtual void CreateTheEntity();
      private: int state;
      private: bool leftMousePressed;
      private: math::Vector2i mousePushPos, mouseReleasePos;

      private: rendering::VisualPtr modelVisual;
      private: std::list<rendering::VisualPtr> visuals;
      private: sdf::SDFPtr modelSDF;

      private: bool clone;
    };
  }
}
#endif


text:
SPEC_BEGIN(StorageRoomSpec)

describe(@"Helpers", ^{
    describe(@"SRAccountPath()", ^{
        it(@"should return path", ^{
            [[SRAccountPath(@"123") should] equal:@"/accounts/123"];
        });
    });

    describe(@"SRCollectionsPath()", ^{
        it(@"should return path", ^{
            [[SRCollectionsPath() should] equal:@"/collections"];
        });
    });

    describe(@"SRCollectionPath()", ^{
        it(@"should return path", ^{
            [[SRCollectionPath(@"123") should] equal:@"/collections/123"];
        });
    });

    describe(@"SRCollectionEntriesPath()", ^{
        it(@"should return path", ^{
            [[SRCollectionEntriesPath(@"123") should] equal:@"/collections/123/entries"];
        });
    });

    describe(@"SRCollectionEntryPath()", ^{
        it(@"should return path", ^{
            [[SRCollectionEntryPath(@"123", @"456") should] equal:@"/collections/123/entries/456"];
        });
    });

    describe(@"SRDeletedEntriesPath()", ^{
        it(@"should return path", ^{
            [[SRDeletedEntriesPath() should] equal:@"/deleted_entries"];
        });
    });

    describe(@"SRDeletedEntriesForCollection()", ^{
        it(@"should return path", ^{
            [[SRDeletedEntriesForCollection(@"COLLECTION_URL") should] equal:@"/deleted_entries?collection_url=COLLECTION_URL"];
        });
    });

    describe(@"SRAbsoluteUrlToRelativePath()", ^{
        it(@"should return path", ^{
            [[SRAbsoluteUrlToRelativePath(@"http://api.storageroomapp.com/accounts/123/collections/456") should] equal:@"/collections/456"];
        });
    });

    describe(@"SRMeta()", ^{
        it(@"should return path", ^{
            [[SRMeta(@"something") should] equal:@"m_something"];
        });
    });

    describe(@"SRAppendOperator()", ^{
        it(@"should return path", ^{
            [[SRAppendOperator(@"key", @"operator") should] equal:@"key!operator"];
        });
    });

    describe(@"SRTypeAttribute()", ^{
        it(@"should return path", ^{
            [[SRTypeAttribute() should] equal:@"m_type"];
        });
    });

    describe(@"SRSubclasses()", ^{
        it(@"should return array", ^{
            NSArray *classes = SRSubclasses([SRObject class]);
            [[classes should] haveCountOf:34];
            [[classes should] contain:[SRAccount class]];
            [[classes should] contain:[SRField class]];

        });
    });

    describe(@"SRObjectiveCToIdentifier()", ^{
        it(@"should return name", ^{
            [[SRObjectiveCToIdentifier(@"nameInCamelCase") should] equal:@"name_in_camel_case"];
        });
    });

    describe(@"SRIdentifierToObjectiveC()", ^{
        it(@"should return name", ^{
            [[SRIdentifierToObjectiveC(@"name_with_underscores") should] equal:@"nameWithUnderscores"];
        });
    });

    describe(@"SRIdFromUrl()", ^{
        it(@"should return id", ^{
            [[SRIdFromUrl(@"http://api.storageroomapp.com/accounts/123/collections/456") should] equal:@"456"];
        });
    });

    describe(@"SRPathAppendQueryParams()", ^{
        it(@"should return with existing query", ^{
            [[SRPathAppendQueryParams(@"/existing?one=1&two=2", [NSDictionary dictionaryWithObject:@"3" forKey:@"three"]) should] equal:@"/existing?one=1&two=2&three=3"];
        });

        it(@"should return without existing query", ^{
            [[SRPathAppendQueryParams(@"/existing", [NSDictionary dictionaryWithObject:@"3" forKey:@"three"]) should] equal:@"/existing?three=3"];
        });
    });

});

SPEC_END


text:
namespace Microsoft.Protocols.TestSuites.Common
{
    using System;
    using System.Runtime.InteropServices;

    /// <summary>
    /// RopAbortSubmit request buffer structure.
    /// </summary>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct RopAbortSubmitRequest : ISerializable
    {
        /// <summary>
        /// Unsigned 8-bit integer. This value specifies the type of remote operation.
        /// For this operation, this field is set to 0x34.
        /// </summary>
        public byte RopId;

        /// <summary>
        /// Unsigned 8-bit integer. This value specifies the logon associated with this operation.
        /// </summary>
        public byte LogonId;

        /// <summary>
        /// Unsigned 8-bit integer. This index specifies the location in the Server Object Handle Table
        /// where the handle for the input Server object is stored.
        /// </summary>
        public byte InputHandleIndex;

        /// <summary>
        /// 64-bit identifier. This value identifies the folder in which the submitted message is located.
        /// </summary>
        public ulong FolderId;

        /// <summary>
        /// 64-bit identifier. This value identifies the submitted message.
        /// </summary>
        public ulong MessageId;

        /// <summary>
        /// Serialize the ROP request buffer.
        /// </summary>
        /// <returns>The ROP request buffer serialized.</returns>
        public byte[] Serialize()
        {
            byte[] serializeBuffer = new byte[Marshal.SizeOf(this)];
            IntPtr requestBuffer = new IntPtr();
            requestBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(this));
            try
            {
                Marshal.StructureToPtr(this, requestBuffer, true);
                Marshal.Copy(requestBuffer, serializeBuffer, 0, Marshal.SizeOf(this));
                return serializeBuffer;
            }
            finally
            {
                Marshal.FreeHGlobal(requestBuffer);
            }
        }

        /// <summary>
        /// Return the size of this structure.
        /// </summary>
        /// <returns>The size of this structure.</returns>
        public int Size()
        {
            return Marshal.SizeOf(this);
        }
    }

    /// <summary>
    /// RopAbortSubmit response buffer structure.
    /// </summary>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct RopAbortSubmitResponse : IDeserializable
    {
        /// <summary>
        /// Unsigned 8-bit integer. This value specifies the type of remote operation.
        /// For this operation, this field is set to 0x34.
        /// </summary>
        public byte RopId;

        /// <summary>
        /// Unsigned 8-bit integer. This index MUST be set to the InputHandleIndex specified in the request.
        /// </summary>
        public byte InputHandleIndex;

        /// <summary>
        /// Unsigned 32-bit integer. This value specifies the status of the remote operation.
        /// </summary>
        public uint ReturnValue;

        /// <summary>
        /// Deserialize the ROP response buffer.
        /// </summary>
        /// <param name="ropBytes">ROPs bytes in response.</param>
        /// <param name="startIndex">The start index of this ROP.</param>
        /// <returns>The size of response buffer structure.</returns>
        public int Deserialize(byte[] ropBytes, int startIndex)
        {
            IntPtr responseBuffer = new IntPtr();
            responseBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(this));
            try
            {
                Marshal.Copy(ropBytes, startIndex, responseBuffer, Marshal.SizeOf(this));
                this = (RopAbortSubmitResponse)Marshal.PtrToStructure(responseBuffer, typeof(RopAbortSubmitResponse));
                return Marshal.SizeOf(this);
            }
            finally
            {
                Marshal.FreeHGlobal(responseBuffer);
            }
        }
    }
}


text:
/**
 * @requires javelin-install
 * @provides phabricator-textareautils
 * @javelin
 */

JX.install('TextAreaUtils', {
  statics : {
    getSelectionRange : function(area) {
      var v = area.value;

      // NOTE: This works well in Safari, Firefox and Chrome. We'll probably get
      // less-good behavior on IE.

      var s = v.length;
      var e = v.length;

      if ('selectionStart' in area) {
        s = area.selectionStart;
        e = area.selectionEnd;
      }

      return {start: s, end: e};
    },

    getSelectionText : function(area) {
      var v = area.value;
      var r = JX.TextAreaUtils.getSelectionRange(area);
      return v.substring(r.start, r.end);
    },

    setSelectionRange : function(area, start, end) {
      if ('setSelectionRange' in area) {
        area.focus();
        area.setSelectionRange(start, end);
      }
    },

    setSelectionText : function(area, text) {
      var v = area.value;
      var r = JX.TextAreaUtils.getSelectionRange(area);

      v = v.substring(0, r.start) + text + v.substring(r.end, v.length);
      area.value = v;

      JX.TextAreaUtils.setSelectionRange(area, r.start, r.start + text.length);
    }
  }
});


text:
def welcome(street, city, state)
  case state

   when "California"
    return "Welcome to California!"
    when "CA"
    return "Welcome to California!"
    else
    return "You should move to California"
    end
  end

  welcome("1833 Sawyer", "Chicago", "California")

=begin
refactored solution using split method

def welcome(address)
  state= address.split

for word in state
  if word == "CA" || word== "California"
    return "Welcome to California"
  end
end
 return "You should move to California"
end

=end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

namespace Microsoft.Azure.Management.StorageCache.Tests
{
    using System;
    using System.Collections.Generic;
    using Microsoft.Azure.Management.Storage;
    using Microsoft.Azure.Management.StorageCache.Models;
    using Microsoft.Azure.Management.StorageCache.Tests.Fixtures;
    using Microsoft.Azure.Management.StorageCache.Tests.Utilities;
    using Microsoft.Azure.Test.HttpRecorder;
    using Xunit;
    using Xunit.Abstractions;

    /// <summary>
    /// Defines the <see cref="StorageCacheTest" />.
    /// </summary>
    [Collection("StorageCacheCollection")]
    public class StorageCacheTest
    {
        /// <summary>
        /// Defines the testOutputHelper.
        /// </summary>
        private readonly ITestOutputHelper testOutputHelper;

        /// <summary>
        /// Defines the Fixture.
        /// </summary>
        private readonly StorageCacheTestFixture fixture;

        /// <summary>
        /// Initializes a new instance of the <see cref="StorageCacheTest"/> class.
        /// </summary>
        /// <param name="testOutputHelper">The testOutputHelper<see cref="ITestOutputHelper"/>.</param>
        /// <param name="fixture">The Fixture<see cref="StorageCacheTestFixture"/>.</param>
        public StorageCacheTest(ITestOutputHelper testOutputHelper, StorageCacheTestFixture fixture)
        {
            this.fixture = fixture;
            this.testOutputHelper = testOutputHelper;
        }

        /// <summary>
        /// The TestGetStorageCache.
        /// </summary>
        [Fact]
        public void TestGetStorageCache()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient<StorageCacheManagementClient>();
                client.ApiVersion = StorageCacheTestEnvironmentUtilities.APIVersion;
                this.fixture.CacheHelper.StoragecacheManagementClient = client;
                Cache response = this.fixture.CacheHelper.Get(this.fixture.Cache.Name);
                Assert.Equal(this.fixture.Cache.Name, response.Name);
                Assert.Equal(this.fixture.Cache.CacheSizeGB, response.CacheSizeGB);
                Assert.Equal(this.fixture.Cache.Location, response.Location);
                Assert.Equal(this.fixture.Cache.Subnet, response.Subnet);
                Assert.Equal(this.fixture.Cache.Sku.Name, response.Sku.Name);
                Assert.Equal(this.fixture.Cache.Id, response.Id);
                Assert.Equal(this.fixture.Cache.Identity.Type, response.Identity.Type);
                Assert.Equal(this.fixture.Cache.Identity.PrincipalId, response.Identity.PrincipalId);
                Assert.Equal(this.fixture.Cache.Identity.TenantId, response.Identity.TenantId);
                Assert.Equal(this.fixture.Cache.SecuritySettings.RootSquash, response.SecuritySettings.RootSquash);
            }
        }

        /// <summary>
        /// List storage cache under subscription.
        /// </summary>
        [Fact]
        public void TestListStorageCache()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient<StorageCacheManagementClient>();
                client.ApiVersion = StorageCacheTestEnvironmentUtilities.APIVersion;
                IList<Cache> cacheListResponse = client.Caches.List().Value;
                Assert.True(cacheListResponse.Count >= 1);
                bool found = false;
                foreach (Cache response in cacheListResponse)
                {
                    if (string.Equals(response.Name, this.fixture.Cache.Name))
                    {
                        found = true;
                        Assert.Equal(this.fixture.Cache.Id, response.Id, ignoreCase: true);
                        Assert.Equal(this.fixture.Cache.Name, response.Name);
                        Assert.Equal(this.fixture.Cache.CacheSizeGB, response.CacheSizeGB);
                        Assert.Equal(this.fixture.Cache.Location, response.Location);
                        Assert.Equal(this.fixture.Cache.Subnet, response.Subnet);
                        Assert.Equal(this.fixture.Cache.Sku.Name, response.Sku.Name);
                    }
                }

                Assert.True(found, string.Format("Cache {0} not found in the list response.", this.fixture.Cache.Name));
            }
        }

        /// <summary>
        /// List storage cache under resource group.
        /// </summary>
        [Fact]
        public void TestListStorageCacheByResourceGroup()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient<StorageCacheManagementClient>();
                client.ApiVersion = StorageCacheTestEnvironmentUtilities.APIVersion;
                this.testOutputHelper.WriteLine("Looking for cache in resource group {0}.", this.fixture.ResourceGroup.Name);
                IList<Cache> cacheListResponse = client.Caches.ListByResourceGroup(this.fixture.ResourceGroup.Name).Value;
                Assert.True(cacheListResponse.Count >= 1);
                bool found = false;
                foreach (Cache response in cacheListResponse)
                {
                    if (string.Equals(response.Name, this.fixture.Cache.Name))
                    {
                        found = true;
                        Assert.Equal(this.fixture.Cache.Id, response.Id, ignoreCase: true);
                        Assert.Equal(this.fixture.Cache.Name, response.Name);
                        Assert.Equal(this.fixture.Cache.CacheSizeGB, response.CacheSizeGB);
                        Assert.Equal(this.fixture.Cache.Location, response.Location);
                        Assert.Equal(this.fixture.Cache.Subnet, response.Subnet);
                        Assert.Equal(this.fixture.Cache.Sku.Name, response.Sku.Name);
                    }
                }

                Assert.True(found, "Cache {this.fixture.Cache.Name} not found in the list response.");
            }
        }

        /// <summary>
        /// Verify flush cache with no storage target attached.
        /// </summary>
        [Fact]
        public void TestFlushCacheWithoutStorageTarget()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient<StorageCacheManagementClient>();
                client.ApiVersion = StorageCacheTestEnvironmentUtilities.APIVersion;
                client.Caches.Flush(this.fixture.ResourceGroup.Name, this.fixture.Cache.Name);
                this.fixture.CacheHelper.StoragecacheManagementClient = client;
                if (HttpMockServer.Mode == HttpRecorderMode.Record)
                {
                    this.fixture.CacheHelper.WaitForCacheState(
                        this.fixture.CacheHelper.GetCacheHealthState,
                        this.fixture.Cache.Name,
                        "Flushing",
                        timeout: 120,
                        polling_delay: 5).GetAwaiter().GetResult();
                    this.fixture.CacheHelper.WaitForCacheState(
                        this.fixture.CacheHelper.GetCacheHealthState,
                        this.fixture.Cache.Name,
                        "Healthy",
                        polling_delay: 5).GetAwaiter().GetResult();
                }
            }
        }

        /// <summary>
        /// The test invalid cache size.
        /// </summary>
        [Fact]
        public void TestInvalidCacheSize()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient<StorageCacheManagementClient>();
                client.ApiVersion = StorageCacheTestEnvironmentUtilities.APIVersion;
                this.fixture.CacheHelper.StoragecacheManagementClient = client;
                var cacheIdentity = new CacheIdentity() { Type = CacheIdentityType.SystemAssigned };
                CloudErrorException ex = Assert.Throws<CloudErrorException>(
                    () =>
                    this.fixture.CacheHelper.Create("InvalidCache", this.fixture.Cache.Sku.Name, 10, identity: cacheIdentity));
                this.testOutputHelper.WriteLine($"{ex.Body.Error.Message}");
                Assert.Equal("InvalidParameter", ex.Body.Error.Code);
                Assert.Equal("cacheSizeGB", ex.Body.Error.Target);
            }
        }

        /// <summary>
        /// The test invalid sku.
        /// </summary>
        [Fact]
        public void TestInvalidSku()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient<StorageCacheManagementClient>();
                client.ApiVersion = StorageCacheTestEnvironmentUtilities.APIVersion;
                this.fixture.CacheHelper.StoragecacheManagementClient = client;
                var cacheIdentity = new CacheIdentity() { Type = CacheIdentityType.SystemAssigned };
                CloudErrorException ex = Assert.Throws<CloudErrorException>(
                    () =>
                    this.fixture.CacheHelper.Create("InvalidCacheSku", "InvalidSku", 3072, identity: cacheIdentity));
                this.testOutputHelper.WriteLine($"{ex.Body.Error.Message}");
                Assert.Equal("InvalidParameter", ex.Body.Error.Code);
                Assert.Equal("sku", ex.Body.Error.Target);
            }
        }

        /// <summary>
        /// The test invalid subscription.
        /// </summary>
        [Fact]
        public void TestInvalidSubscription()
        {
            this.testOutputHelper.WriteLine($"Running in {HttpMockServer.GetCurrentMode()} mode.");
            using (StorageCacheTestContext context = new StorageCacheTestContext(this))
            {
                var client = context.GetClient<StorageCacheManagementClient>();
                client.ApiVersion = StorageCacheTestEnvironmentUtilities.APIVersion;
                client.SubscriptionId = "4525f627-2e14-411c-96b9-7df2be6eeb93";
                this.fixture.CacheHelper.StoragecacheManagementClient = client;
                var cacheIdentity = new CacheIdentity() { Type = CacheIdentityType.SystemAssigned };
                CloudErrorException ex = Assert.Throws<CloudErrorException>(
                    () =>
                    this.fixture.CacheHelper.Create("InvalidSubscriptionId", this.fixture.Cache.Sku.Name, 3072, identity: cacheIdentity, skipGet: true));
                this.testOutputHelper.WriteLine($"{ex.Body.Error.Message}");
                Assert.Equal("SubscriptionNotFound", ex.Body.Error.Code);
                client.SubscriptionId = this.fixture.SubscriptionID;
                this.fixture.CacheHelper.StoragecacheManagementClient = client;
            }
        }
    }
}


text:
/**
 * @author Charlie Fontana <charlie@ambisafe.co>
 * @date 10/07/2015
 */

#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
#import "AmbisafeAccount.h"
#import "AmbisafeTransaction.h"

@interface AmbisafeService : NSObject

+ (AmbisafeService *)getInstance;

- (JSContext *)getJsContext;

/*!
 * Static method that creates an account and save it.
 * This supposed to happen after user have filled registration form and clicked submit.
 *
 * \param {NSString} currency as NSString
 * \param {NSString} password as NSString
 * \param {NSString} salt as NSString
 * \return {AmbisafeAccount} return the generated account object
 */
- (AmbisafeAccount *)generateAccount:(NSString *)currency
                    password:(NSString *)password
                        salt:(NSString *)salt;

/*!
 * Static method that generates a key pair and returns it as a NSDictionary object.
 *
 * \return {NSDictionary} key pair
 */
- (NSDictionary *)generateKeyPair;

/*!
 * Static method that signs a transaction.
 *
 * \param {AmbisafeTransaction} tx unsigned transaction: {hex:'...', fee:'...', sighashes:['...', '...']}.
 * \param {NSString} private_key.
 * \return {AmbisafeTransaction} signed transaction.
 */
- (AmbisafeTransaction *)signTransaction:(AmbisafeTransaction *)tx
                      privateKey:(NSString *)privateKey;

/*!
 * Static method that generates random values
 *
 * \param {NSNumber} length
 * \return {NSString} return random value
 */
- (NSString *)generateRandomValue:(NSNumber *)lenght;

/*!
 * Static method that derives a key from a password
 *
 * \param {NSString} password
 * \param {NSString} salt
 * \param {NSNumber} depth
 * \return {NSString} key
 */
- (NSString *)deriveKey:(NSString *)password
                   salt:(NSString *)salt
                  depth:(NSNumber *)depth;

/*!
 * Static method that encrypts an input based on the Advanced Encryption Standard (AES)
 *
 * \param {NSString} cleardata
 * \param {NSString} iv
 * \param {NSString} cryptkey
 * \return {NSString} encrypted data
 */
- (NSString *)encrypt:(NSString *)cleardata
                   iv:(NSString *)iv
             cryptkey:(NSString *)cryptkey;

/*!
 * Static method that decrypts an input based on the Advanced Encryption Standard (AES)
 *
 * \param {NSString} encryptdata
 * \param {NSString} iv
 * \param {NSString} cryptkey
 * \return {NSString} decrypted text
 */
- (NSString *)decrypt:(NSString *)encryptdata
                   iv:(NSString *)iv
             cryptkey:(NSString *)cryptkey;

/*!
 * Static method that gets the SHA1 hash of a string
 *
 * \param {NSString} input
 * \return {NSString} SHA1 hash
 */
- (NSString *)SHA1:(NSString *)input;

@end


text:
<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class WCVendors_Pro_API_Manager_Password_Management {

	private function rand( $min = 0, $max = 0 ) {
		global $rnd_value;

		// Reset $rnd_value after 14 uses
		// 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
		if ( strlen($rnd_value) < 8 ) {
			if ( defined( 'WP_SETUP_CONFIG' ) )
				static $seed = '';
			else
				$seed = get_transient('random_seed');
			$rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
			$rnd_value .= sha1($rnd_value);
			$rnd_value .= sha1($rnd_value . $seed);
			$seed = md5($seed . $rnd_value);
			if ( ! defined( 'WP_SETUP_CONFIG' ) )
				set_transient('random_seed', $seed);
		}

		// Take the first 8 digits for our value
		$value = substr($rnd_value, 0, 8);

		// Strip the first eight, leaving the remainder for the next call to wp_rand().
		$rnd_value = substr($rnd_value, 8);

		$value = abs(hexdec($value));

		// Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
		$max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff

		// Reduce the value to be within the min - max range
		if ( $max != 0 )
			$value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );

		return abs(intval($value));
	}

	// Creates a unique instance ID
	public function generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		if ( $special_chars )
			$chars .= '!@#$%^&*()';
		if ( $extra_special_chars )
			$chars .= '-_ []{}<>~`+=,.;:/?|';

		$password = '';
		for ( $i = 0; $i < $length; $i++ ) {
			$password .= substr($chars, self::rand(0, strlen($chars) - 1), 1);
		}

		// random_password filter was previously in random_password function which was deprecated
		return $password;
	}

}


text:
<!--
  Copyright © 2020 Petr Panteleyev <petr@panteleyev.org>
  SPDX-License-Identifier: BSD-2-Clause
  -->

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">

<suite name="Money Manager OFX Unit Tests">
    <test name="OFX">
        <classes>
            <class name="org.panteleyev.ofx.TestAccountStatement"/>
            <class name="org.panteleyev.ofx.TestCreditCardStatement"/>
        </classes>
    </test>
</suite>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
	<settings>
		<!-- changes from the defaults -->
		<setting name="lazyLoadingEnabled" value="false" />
		<setting name="cacheEnabled" value="false"/>
	</settings>

	<typeAliases>
		<package name="com.project.entity"/>
	</typeAliases>
</configuration>


text:
<?php defined('BASEPATH') or exit('No direct script access allowed');
/**
 * Slider Module slide's controller.
 *
 * @package		PyroCMS
 * @subpackage	Slider Module
 * @author		Chris Harvey
 * @link 		http://www.chrisnharvey.com/
 *
 */
class Admin_Slides extends Admin_Controller
{
	public $section = 'slides';

	public $current_namespace = "slides";
	public $current_streamname = "slides";

	public function __construct()
	{
		parent::__construct();
		$this->module_details['sections']['slides']['shortcuts'][1]["uri"] = 'admin/slider/slides/create/1';
		// Load the streams driver
		$this->load->driver('Streams');

		// Load the language file
		$this->lang->load('slider');

		// Load the cache
		$this->load->driver('cache', array('adapter' => 'file'));

		//load the user's helper
		$this->load->helper("user");
	}

	/**
	 * Index
	 * Show all the slides if no ID is set, show current slider slides if ID is set.
	 * @param Integer $id
	 * @return none
	 * use entries view
	 */
	public function index($id)
	{
		$where = isset($id) ? 'slider_id = '.$id : '';
		//to work, the shortcut must get the active slider id. add the $id here is too late. Must dig further!
		//$this->module_details['sections']['slides']['shortcuts'][1]["uri"] = 'admin/slider/slides/create/'.$id;

		// Display a list of articles
		$params = array(
			'stream'    => $this->current_namespace,
			'namespace' => $this->current_streamname,
			'order_by'  => 'ordering_count',
			'sort'      => 'asc',
			'where'		=> $where
		);
		$current_slider = $this->streams->entries->get_entry($id, "sliders", "sliders", false);
		$data['entries'] = $this->streams->entries->get_entries($params);

		$this->template->append_css('module::sortable.css')
					   ->append_js('module::sortable.js')
					   ->set("title",$current_slider->slider_name)
					   ->build('admin/entries', $data);
	}

	/**
	 * Create
	 * Create slide for the current slider_id.
	 * @param integer $id
	 * @return none
	 */
	public function create($id)
	{
		if (empty($id)) $id = 1;
		role_or_die("slider", "slide_add", 'admin/slider/slides/index/'.$id, lang("slider:role:add:failed"));
		if ($this->input->post()) $this->cache->delete(md5(BASE_URL . 'slider/slides/'.$slider_id));

		$params = array(
			'stream'    => "sliders",
			'namespace' => "sliders",
			'where'		=> 'default_sliders.id='.$id
		);

		$current_slider = $this->streams->entries->get_entry($id, "sliders", "sliders", false);
		$title = lang('slider:slide:create:title').$current_slider->slider_name;
		$extra = array(
			'return'			=> 'admin/slider/slides/index/'.$id,
			'success_message'	=> lang('slider:create:success'),
			'failure_message'	=> lang('slider:create:fail'),
			'title'				=> $title
		);
		$skips = null;
		$tabs = false;
		$hidden = array("slider_id");
		$defaults = array("slider_id" => $id);

		$this->streams->cp->entry_form($this->current_streamname, $this->current_namespace, 'new', null, true, $extra, $skips, $tabs, $hidden, $defaults);
	}

	/**
	 * Edit
	 * Edit the selected slide.
	 * Skip the slider id
	 * @param integer $id the slide id to edit
	 * @param integer $slider_id the slider ID of the slide.
	 * cp entry form
	 */
	public function edit($id, $slider_id)
	{
		if ($this->input->post()) $this->cache->delete(md5(BASE_URL . 'slider/slides/'.$slider_id));

		$return = isset($slider_id) ? $slider_id : "";
		$extra = array(
 			'return' => 'admin/slider/slides/index/'.$return
 		);
		$skips = null;
		$tabs = false;
		$hidden = array("slider_id");
		$defaults = array("slider_id" => $slider_id);

 		$this->streams->cp->entry_form($this->current_streamname, $this->current_namespace, 'edit', $id, TRUE, $extra, $skips, $tabs, $hidden, $defaults);
	}

	/**
	 * Live
	 * Set slides to live.
	 * @param integer $id
	 * redirect
	 */
	public function live($id, $slider_id)
	{
		$id = (int)$id;

		$update = $this->db->update($this->current_namespace, array('slide_status' => 'live'), array('id' => $id));

 		if ($update)
 		{
 			$this->cache->delete(md5(BASE_URL . 'slider/slides/'.$slider_id));
 			$this->session->set_flashdata('success', 'Image successfully set to live');
 		}
 		else
 		{
 			$this->session->set_flashdata('error', 'Unable to set the image to live');
 		}

 		redirect('admin/slider/slides/index/'.$slider_id);
	}

	/**
	 * draft
	 * Set slides to draft.
	 * @param integer $id
	 * redirect
	 */
	public function draft($id, $slider_id)
	{
		$id = (int)$id;

		$update = $this->db->update($this->current_streamname, array('slide_status' => 'draft'), array('id' => $id));

 		if ($update)
 		{
 			$this->cache->delete(md5(BASE_URL . 'slider/slides/'.$slider_id));
 			$this->session->set_flashdata('success', 'Image successfully set to draft');
 		}
 		else
 		{
 			$this->session->set_flashdata('error', 'Unable to set the image to draft');
 		}

 		redirect('admin/slider/slides/index/'.$slider_id);
	}

	/**
	 * delete
	 * @param integer $id
	 * redirect
	 */
	public function delete($id, $slider_id)
	{
		$id = (int)$id;
		$return = isset($slider_id) ? $slider_id : "";

		role_or_die("slider", "slide_delete", 'admin/slider/slides/index/'.$return, lang("slider:role:slide:delete:failed"));
 		$delete = $this->db->delete($this->current_streamname, array('id' => $id));

 		if ($delete)
 		{
 			$this->cache->delete(md5(BASE_URL . 'slider/slides/'.$slider_id));
 			$this->session->set_flashdata('success', 'Image deleted successfully');
 		}
 		else
 		{
 			$this->session->set_flashdata('error', 'Unable to delete image');
 		}

 		redirect('admin/slider/slides/index/'.$slider_id);
	}

	/**
	 * Assign field, add new fields view to the slide's stream.
	 * @param string $action 'edit', 'new' or 'delete'
	 * @param $field if delete or edit the field to edit.
	 * redirect
	 */
	public function fields($action = null, $field = null)
	{
		role_or_die("slider", "slide_fields", 'admin/slider/slides/index/'.$return, lang("slider:role:slide:fields:failed"));
		if ($action == null) {

			$this->streams->cp->assignments_table($this->current_namespace, $this->current_namespace, null, null, true, array(
				'title'   => 'Slider Fields',
				'buttons' => array(
					array(
						'label' => 'Edit',
						'url'   => "admin/slider/fields/edit/-assign_id-"
					),
					array(
						'label'   => 'Delete',
						'url'     => "admin/slider/fields/delete/-assign_id-",
						'confirm' => true
					)
				)
			));

		} elseif (($action == 'edit' and $field) or $action == 'new') {

			$this->streams->cp->field_form($this->current_streamname, $this->current_namespace, $action, 'admin/slider/fields', $field, array(), true, array(
				'title'   => 'Edit Field',
			));

		} elseif ($action == 'delete' and $field) {

			$query = $this->db->select('data_fields.field_slug')
				->join('data_fields', 'data_field_assignments.field_id = data_fields.id')
				->where('data_field_assignments.id', $field)
				->get('data_field_assignments');

			if ( ! $query->num_rows()) show_404();

			$this->streams->fields->delete_field($query->row()->field_slug, $this->current_streamname);

			$this->session->set_flashdata('success', 'Field deleted successfully');

			redirect('admin/slider/fields');

		} else {

			show_404();

		}
	}

	/**
	 * Reorder the slides
	 */
	public function reorder()
	{
		if ($this->input->is_ajax_request())
 		{
 			$order = explode(',', $this->input->post('order'));

 			// Start the transaction
 			$this->db->trans_start();

 			$i = 1;
 			foreach ($order as $id)
 			{
 				$this->db->update($this->current_streamname, array('ordering_count' => $i), array('id' => $id));
 				$i++;
 			}

 			// End the transaction
 			$this->db->trans_complete();

 			if ($this->db->trans_status() === FALSE)
 			{
 				set_status_header(500);
 			}
 			else
 			{
 				$this->cache->delete(md5(BASE_URL . $this->current_streamname));
 				set_status_header(200);
 			}
 		}
 		else
 		{
 			show_404();
 		}
	}
}


text:
<?php
namespace Blog\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Blog\Form\PostForm;

class PostFormFactory implements FactoryInterface{

	public function createService(ServiceLocatorInterface $serviceLocator){

		$realServiceLocator = $serviceLocator->getServiceLocator();

		return new PostForm($realServiceLocator->get('Doctrine\ORM\EntityManager'));

	}
}


text:
package org.springframework.autobuilds.jpetstore.dao;

import java.util.List;

import org.springframework.autobuilds.jpetstore.domain.Account;
import org.springframework.dao.DataAccessException;

public interface AccountDao {

  Account getAccount(String username) throws DataAccessException;

  Account getAccount(String username, String password) throws DataAccessException;

  void insertAccount(Account account) throws DataAccessException;

  void updateAccount(Account account) throws DataAccessException;

	List getUsernameList() throws DataAccessException;

}


text:
@implementation CYXMenu

@end


text:
import Ember from 'ember';

const { service } = Ember.inject;

export default Ember.Component.extend({
  currentUser: service('current-user'),
  isPosting: false,
  message: '',

  isDisabled: Ember.computed('message.length', 'isPosting', function() {
    if (this.get('isPosting')) {
      return true;
    }
    if (this.get('message.length') === 0) {
      return true;
    }
    return false;
  }),

  actions: {
    newPost() {
      //this.set('isPosting', true);
      this.sendAction('setAction', this.get('currentUser').user, this.get('target'), this.get('message'));
    }
  }
});


text:
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="../../bower_components/webcomponentsjs/webcomponents.min.js"></script>
  <script src="../../bower_components/web-component-tester/browser.js"></script>
  <link rel="import" href="../../dist/metaroom-markup.html">

  <script src='../spec.js'></script>
</head>
<body>

  <div id='fixture'>
    <meta-verse id="meta-verse">
      <meta-room width='10' height='10' length='10' id='main-meta-room'>
        <meta-wall align='left' id='main-meta-wall'></meta-wall>
      </meta-room>
    </meta-verse>
  </div>

  <script>
    describe('meta-wall', function() {
      beforeEach(function(){
        jlet('metaVerse', function(){ return document.querySelector('#meta-verse')});
        jlet('metaRoom', function(){ return document.querySelector('#main-meta-room')});

        jlet('metaWall', function(){ return document.querySelector('#main-meta-wall')});
        jlet('metaWallMesh', function(){ return J.metaWall.controller.metaObject.mesh });
        jlet('metaWallGroup', function(){ return J.metaWall.controller.metaObject.group });

        jlet('metaRoomChildrenUUID', function(){
          return J.metaRoom.controller.metaObject.group.children.map(function(child){
            return child.uuid;
          });
        });

      });

      describe("when it is added within meta-room", function(){

        it("adds a group to meta-room", function(){
          expect(J.metaRoomChildrenUUID).to.include(J.metaWall.controller.metaObject.group.uuid);
        });

        it("adds a plan to the group", function(){
          expect(J.metaWallGroup.children[0].uuid).to.equal(J.metaWallMesh.uuid);
        });

        describe("with align=left", function(){
          it("sets the meta object group to the left of the room", function(){
            expect(J.metaWallGroup.position.x, 'x').to.equal(-5);
            expect(J.metaWallGroup.position.y, 'y').to.equal(5);
            expect(J.metaWallGroup.position.z, 'z').to.equal(0);
          });

          describe("when the align changes to right", function(){
            asyncBeforeEach(function(){
              J.metaWall.setAttribute('align', 'right');
            });

            it("sets the meta object to the left of the room", function(){
              expect(J.metaWallGroup.position.x, 'x').to.equal(5);
              expect(J.metaWallGroup.position.y, 'y').to.equal(5);
              expect(J.metaWallGroup.position.z, 'z').to.equal(0);
            });

            describe("when the room width changes", function(){

              it("sets the position of meta object", function(){
                J.metaRoom.setAttribute('width', 20);
                expect(J.metaWallGroup.position.x, 'x').to.equal(10);
                expect(J.metaWallGroup.position.y, 'y').to.equal(5);
                expect(J.metaWallGroup.position.z, 'z').to.equal(0);
              });

            });

          });
        });

        describe("when meta-wall is deleted", function(){
          it("removes the meta object from the scene", function(){
            var metaWallUUID;

            J.metaWall.remove();
            metaWallUUID = J.metaWall.controller.metaObject.group.uuid;

            expect(J.metaRoomChildrenUUID).to.not.include(metaWallUUID);

          });
        });

        describe("when the room width changes", function(){
          beforeEach(function(){
            J.metaRoom.setAttribute('width', 20);
          });

          it("sets the position of meta object", function(){
            expect(J.metaWallGroup.position.x, 'x').to.equal(-10);
            expect(J.metaWallGroup.position.y, 'y').to.equal(5);
            expect(J.metaWallGroup.position.z, 'z').to.equal(0);
          });

        });

        describe("when the room length changes", function(){
          it("sets the scale of the meta object", function(){
            J.metaRoom.setAttribute('length', 20);
            expect(J.metaWallMesh.scale.x, 'x').to.equal(20);
            expect(J.metaWallMesh.scale.y, 'y').to.equal(10);
            expect(J.metaWallMesh.scale.z, 'z').to.equal(1);
          });
        });

      });

    });
  </script>
</body>
</html>


text:
package org.kuali.kfs.fp.document.validation.impl;

import static org.kuali.kfs.sys.KFSConstants.ACCOUNTING_LINE_ERRORS;
import static org.kuali.kfs.sys.KFSKeyConstants.ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS;
import static org.kuali.kfs.sys.KFSKeyConstants.ERROR_DOCUMENT_PC_TRANSACTION_TOTAL_ACCTING_LINE_TOTAL_NOT_EQUAL;

import java.util.List;

import org.kuali.kfs.fp.businessobject.ProcurementCardTargetAccountingLine;
import org.kuali.kfs.fp.businessobject.ProcurementCardTransactionDetail;
import org.kuali.kfs.fp.document.ProcurementCardDocument;
import org.kuali.kfs.sys.businessobject.TargetAccountingLine;
import org.kuali.kfs.sys.document.validation.GenericValidation;
import org.kuali.kfs.sys.document.validation.event.AttributedDocumentEvent;
import org.kuali.rice.core.api.util.type.KualiDecimal;
import org.kuali.rice.krad.util.GlobalVariables;

/**
 * Validates that an accounting line does not have a capital object object code
 */
public class ProcurementCardBalanceValidation extends GenericValidation {
    private ProcurementCardDocument accountingDocumentForValidation;

    /**
     * Validates that an accounting line does not have a capital object object code
     * Expects an accounting line as the first a parameter
     * @see org.kuali.kfs.sys.document.validation.Validation#validate(java.lang.Object[])
     */
    public boolean validate(AttributedDocumentEvent event) {
        ProcurementCardDocument pcDocument = (ProcurementCardDocument) getAccountingDocumentForValidation();

        KualiDecimal targetTotal = pcDocument.getTargetTotal();
        KualiDecimal sourceTotal = pcDocument.getSourceTotal();

        boolean isValid = targetTotal.compareTo(sourceTotal) == 0;

        if (!isValid) {
            GlobalVariables.getMessageMap().putError(ACCOUNTING_LINE_ERRORS, ERROR_DOCUMENT_BALANCE_CONSIDERING_SOURCE_AND_TARGET_AMOUNTS, new String[] { sourceTotal.toString(), targetTotal.toString() });
        }

        List<ProcurementCardTransactionDetail> pcTransactionEntries = pcDocument.getTransactionEntries();

        for (ProcurementCardTransactionDetail pcTransactionDetail : pcTransactionEntries) {
            isValid &= isTransactionBalanceValid(pcTransactionDetail);
        }

        return isValid;
    }

    /**
     * This method validates the balance of the transaction given.  A procurement card transaction is in balance if
     * the total amount of the transaction equals the total of the target accounting lines corresponding to the transaction.
     *
     * @param pcTransaction The transaction detail used to retrieve the procurement card transaction and target accounting
     *                      lines used to check for in balance.
     * @return True if the amounts are equal and the transaction is in balance, false otherwise.
     */
    protected boolean isTransactionBalanceValid(ProcurementCardTransactionDetail pcTransactionDetail) {
        boolean inBalance = true;
        KualiDecimal transAmount = pcTransactionDetail.getTransactionTotalAmount();
        List<ProcurementCardTargetAccountingLine> targetAcctingLines = pcTransactionDetail.getTargetAccountingLines();

        KualiDecimal targetLineTotal = KualiDecimal.ZERO;

        for (TargetAccountingLine targetLine : targetAcctingLines) {
            targetLineTotal = targetLineTotal.add(targetLine.getAmount());
        }

        // perform absolute value check because current system has situations where amounts may be opposite in sign
        // This will no longer be necessary following completion of KULFDBCK-1290
        inBalance = transAmount.abs().equals(targetLineTotal.abs());

        if (!inBalance) {
            GlobalVariables.getMessageMap().putError(ACCOUNTING_LINE_ERRORS, ERROR_DOCUMENT_PC_TRANSACTION_TOTAL_ACCTING_LINE_TOTAL_NOT_EQUAL, new String[] { transAmount.toString(), targetLineTotal.toString() });
        }

        return inBalance;
    }

    /**
     * Gets the accountingDocumentForValidation attribute.
     * @return Returns the accountingDocumentForValidation.
     */
    public ProcurementCardDocument getAccountingDocumentForValidation() {
        return accountingDocumentForValidation;
    }

    /**
     * Sets the accountingDocumentForValidation attribute value.
     * @param accountingDocumentForValidation The accountingDocumentForValidation to set.
     */
    public void setAccountingDocumentForValidation(ProcurementCardDocument accountingDocumentForValidation) {
        this.accountingDocumentForValidation = accountingDocumentForValidation;
    }

}


text:
local show_not_in_use = param.get("show_not_in_use", atom.boolean) or false

local policies = Policy:build_selector{ active = not show_not_in_use }:exec()

ui.titleAdmin(_"Policy list")

ui.section( function()
  ui.sectionHead( function()
    ui.heading { level = 1, content = _"Policy list" }
  end )

  ui.sectionRow( function()

    if show_not_in_use then
      ui.link{
        text = _"Show policies in use",
        module = "admin",
        view = "policy_list"
      }

    else
      ui.link{
        text = _"Create new policy",
        module = "admin",
        view = "policy_show"
      }
      slot.put(" · ")
      ui.link{
        text = _"Show policies not in use",
        module = "admin",
        view = "policy_list",
        params = { show_not_in_use = true }
      }

    end

  end )

  ui.sectionRow( function()

    ui.list{
      records = policies,
      columns = {

        { content = function(record)
            ui.link{
              text = record.name,
              module = "admin",
              view = "policy_show",
              id = record.id
            }
          end
        }

      }
    }

  end )
end )


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
OscEventListener (Javadocs: oscP5)
</TITLE>

<META NAME="date" CONTENT="2012-12-23">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

oscP5

Interface OscEventListener

public interface OscEventListener

Method Summary

 void
oscEvent(OscMessage theMessage)

 void
oscStatus(OscStatus theStatus)

Method Detail

oscEvent

void oscEvent(OscMessage theMessage)

oscStatus

void oscStatus(OscStatus theStatus)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

processing library oscP5 by Andreas Schlegel. (c) 2004-2012


text:
from setting.setting import VK_API_TOKEN
from setting.setting import VK_CHAT_ID
import requests
import datetime
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh = logging.FileHandler('log/log.txt')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
logger.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)

fSeptember = "02.09.2016"
fSeptemberDate = datetime.datetime.strptime(fSeptember, "%d.%m.%Y")

nowDate = datetime.datetime.now()

diffDate = fSeptemberDate - nowDate

dayStr = "день"
if diffDate.days // 10 == 1:
  dayStr = "дней"
elif (diffDate.days % 10 == 0) or (diffDate.days % 10 >= 5):
  dayStr = "дней"
elif (diffDate.days % 10 in [2,3,4]):
  dayStr = "дня"

pmProgress = str(round(2 + ((92 - diffDate.days) / 92), 6)) + " ПМиИ. " + str(diffDate.days) + " " + dayStr + " до 1 сентября"

payload = {"chat_id": VK_CHAT_ID, "title": pmProgress, "access_token": VK_API_TOKEN}
r = requests.get('https://api.vk.com/method/messages.editChat', params=payload, timeout=10)

logger.debug("VK API return: " + r.text)