text:
<?php

namespace Nette\Database\Drivers;

use Nette;

/**
 * Supplemental MS SQL database driver.
 *
 * @author     David Grudl
 */
class MsSqlDriver extends Nette\Object implements Nette\Database\ISupplementalDriver
{
	/** @var Nette\Database\Connection */
	private $connection;

	public function __construct(Nette\Database\Connection $connection, array $options)
	{
		$this->connection = $connection;
	}

	/********************* SQL ****************d*g**/

	/**
	 * Delimites identifier for use in a SQL statement.
	 */
	public function delimite($name)
	{
		// @see http://msdn.microsoft.com/en-us/library/ms176027.aspx
		return '[' . str_replace(array('[', ']'), array('[[', ']]'), $name) . ']';
	}

	/**
	 * Formats boolean for use in a SQL statement.
	 */
	public function formatBool($value)
	{
		return $value ? '1' : '0';
	}

	/**
	 * Formats date-time for use in a SQL statement.
	 */
	public function formatDateTime(/*\DateTimeInterface*/ $value)
	{
		return $value->format("'Y-m-d H:i:s'");
	}

	/**
	 * Encodes string for use in a LIKE statement.
	 */
	public function formatLike($value, $pos)
	{
		$value = strtr($value, array("'" => "''", '%' => '[%]', '_' => '[_]', '[' => '[[]'));
		return ($pos <= 0 ? "'%" : "'") . $value . ($pos >= 0 ? "%'" : "'");
	}

	/**
	 * Injects LIMIT/OFFSET to the SQL query.
	 */
	public function applyLimit(& $sql, $limit, $offset)
	{
		if ($limit >= 0) {
			$sql = preg_replace('#^\s*(SELECT|UPDATE|DELETE)#i', '$0 TOP ' . (int) $limit, $sql, 1, $count);
			if (!$count) {
				throw new Nette\InvalidArgumentException('SQL query must begin with SELECT, UPDATE or DELETE command.');
			}
		}

		if ($offset) {
			throw new Nette\NotSupportedException('Offset is not supported by this database.');
		}
	}

	/**
	 * Normalizes result row.
	 */
	public function normalizeRow($row)
	{
		return $row;
	}

	/********************* reflection ****************d*g**/

	/**
	 * Returns list of tables.
	 */
	public function getTables()
	{
		throw new Nette\NotImplementedException;
	}

	/**
	 * Returns metadata for all columns in a table.
	 */
	public function getColumns($table)
	{
		throw new Nette\NotImplementedException;
	}

	/**
	 * Returns metadata for all indexes in a table.
	 */
	public function getIndexes($table)
	{
		throw new Nette\NotImplementedException;
	}

	/**
	 * Returns metadata for all foreign keys in a table.
	 */
	public function getForeignKeys($table)
	{
		throw new Nette\NotImplementedException;
	}

	/**
	 * Returns associative array of detected types (IReflection::FIELD_*) in result set.
	 */
	public function getColumnTypes(\PDOStatement $statement)
	{
		return Nette\Database\Helpers::detectTypes($statement);
	}

	/**
	 * @param  string
	 * @return bool
	 */
	public function isSupported($item)
	{
		return $item === self::SUPPORT_SUBSELECT;
	}

}


text:
namespace JoinRpg.Web.Models;

public class InviteRequestViewModel
{
    public const string AccommodationRequestPrefix = "ar";
    public int ProjectId { get; set; }
    public int ClaimId { get; set; }
    public int RequestId { get; set; }
    public int InviteId { get; set; }
    public string ReceiverClaimOrAccommodationRequest { get; set; }
}

redpajama_set_name: RedPajamaGithub


text:
require "cgi"
require 'zlib'

module FederazioneTrentina
  module Saml
    module Coding
      def decode(encoded)
        Base64.decode64(encoded)
      end

      def encode(encoded)
        Base64.encode64(encoded).gsub(/\n/, "")
      end

      def escape(unescaped)
        CGI.escape(unescaped)
      end

      def unescape(escaped)
        CGI.unescape(escaped)
      end

      def inflate(deflated)
        zlib = Zlib::Inflate.new(-Zlib::MAX_WBITS)
        zlib.inflate(deflated)
      end

      def deflate(inflated)
        Zlib::Deflate.deflate(inflated, 9)[2..-5]
      end

    end
  end
end


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 60(11): 2293 (1982)

#### Original name
Calonectria camelliae Shipton, 1979

### Remarks
null


text:
layout: post
title:  "When Breath Becomes Air"
date:   2016-10-27 19:16:49 +0100
author: Paul Kalanithi
book:
  cover: https://d3by36x8sj6cra.cloudfront.net/assets/images/book/large/9781/8479/9781847923677.jpg
  format: hardback
  pages: 256
  publisher: Vintage Publishing
  ISBN10: 1847923674
  ISBN13: 9781847923677
  rank: 40
price:
  usd: 16.92
  eur: 15.98
tags: Memoirs,Neurosurgery,Doctors
---

THE NEW YORK TIMES NUMBER ONE BESTSELLER THE SUNDAY TIMES BESTSELLER 'Finishing this book and then forgetting about it is simply not an option...Unmissable' New York Times At the age of thirty-six, on the verge of completing a decade's training as a neurosurgeon, Paul Kalanithi was diagnosed with inoperable lung cancer.

One day he was a doctor treating the dying, the next he was a patient struggling to live. When Breath Becomes Air chronicles Kalanithi's transformation from a medical student asking what makes a virtuous and meaningful life into a neurosurgeon working in the core of human identity - the brain - and finally into a patient and a new father. What makes life worth living in the face of death? What do you do when when life is catastrophically interrupted? What does it mean to have a child as your own life fades away?

Paul Kalanithi died while working on this profoundly moving book, yet his words live on as a guide to us all. When Breath Becomes Air is a life-affirming reflection on facing our mortality and on the relationship between doctor and patient, from a gifted writer who became both.


text:
"""Administration form for privacy settings."""

from __future__ import unicode_literals

from django import forms
from django.utils.translation import ugettext_lazy as _
from djblets.avatars.registry import AvatarServiceRegistry
from djblets.siteconfig.forms import SiteSettingsForm

class PrivacySettingsForm(SiteSettingsForm):
    """Site-wide user privacy settings for Review Board."""

    terms_of_service_url = forms.URLField(
        label=_('Terms of service URL'),
        required=False,
        help_text=_('URL to your terms of service. This will be displayed on '
                    'the My Account page and during login and registration.'),
        widget=forms.widgets.URLInput(attrs={
            'size': 80,
        }))

    privacy_policy_url = forms.URLField(
        label=_('Privacy policy URL'),
        required=False,
        help_text=_('URL to your privacy policy. This will be displayed on '
                    'the My Account page and during login and registration.'),
        widget=forms.widgets.URLInput(attrs={
            'size': 80,
        }))

    privacy_info_html = forms.CharField(
        label=_('Privacy information'),
        required=False,
        help_text=_('A description of the privacy guarantees for users on '
                    'this server. This will be displayed on the My Account '
                    '-> Your Privacy page. HTML is allowed.'),
        widget=forms.widgets.Textarea(attrs={
            'cols': 60,
        }))

    privacy_enable_user_consent = forms.BooleanField(
        label=_('Require consent for usage of personal information'),
        required=False,
        help_text=_('Require consent from users when using their personally '
                    'identifiable information (usernames, e-mail addresses, '
                    'etc.) for when talking to third-party services, like '
                    'Gravatar. This is required for EU GDPR compliance.'))

    def save(self):
        """Save the privacy settings form.

        This will write the new configuration to the database.
        """
        self.siteconfig.set(AvatarServiceRegistry.ENABLE_CONSENT_CHECKS,
                            self.cleaned_data['privacy_enable_user_consent'])

        super(PrivacySettingsForm, self).save()

    class Meta:
        title = _('User Privacy Settings')
        fieldsets = (
            {
                'classes': ('wide',),
                'fields': (
                    'terms_of_service_url',
                    'privacy_policy_url',
                    'privacy_info_html',
                    'privacy_enable_user_consent',
                ),
            },
        )


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   FSEGTCamera.h
 * Author: demensdeum
 *
 * Created on February 19, 2017, 12:32 PM
 */

#ifndef FSEGTCAMERA_H
#define FSEGTCAMERA_H

#include <FlameSteelEngineGameToolkit/Data/Components/Vector/FSEGTVector.h>

#include <memory>

class FSEGTCamera: FSCObject {
public:
    FSEGTCamera();
    FSEGTCamera(const FSEGTCamera& orig);
    virtual ~FSEGTCamera();

    shared_ptr<FSEGTVector> position;
    shared_ptr<FSEGTVector> direction;
    shared_ptr<FSEGTVector> plane;

    void rotate(float diff);

    void setPosition(float x, float y);
    void setRotation(float angle);

    void reset();

private:

};

#endif /* FSEGTCAMERA_H */


text:
/* @test
   @bug 6860433
   @summary Tests variuos techniques of Nimbus color customization
   @author Peter Zhelezniakov
   @run main ColorCustomizationTest
*/

import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import javax.swing.plaf.synth.Region;

public class ColorCustomizationTest
{
    final static int WIDTH = 200;
    final static int HEIGHT = 100;

    static NimbusLookAndFeel nimbus;

    final JLabel label;
    final Graphics g;

    ColorCustomizationTest() {
        label = new JLabel();
        label.setSize(200, 100);

        g = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB).getGraphics();
    }

    public static void main(String[] args) throws Exception {
        nimbus = new NimbusLookAndFeel();
        try {
            UIManager.setLookAndFeel(nimbus);
        } catch (UnsupportedLookAndFeelException e) {
            throw new Error("Unable to set Nimbus LAF");
        }
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override public void run() {
                new ColorCustomizationTest().test();
            }
        });
    }

    void check(Color c) {
        SwingUtilities.updateComponentTreeUI(label);
        label.paint(g);
        if (label.getBackground().getRGB() != c.getRGB()) {
            System.err.println("Color mismatch!");
            System.err.println("   found: " + label.getBackground());
            System.err.println("   expected: " + c);
            throw new RuntimeException("Test failed");
        }
    }

    void test() {
        testOverrides();
        testInheritance();
        testNames();
        testBaseColor();
    }

    void testOverrides() {
        Color defaultColor = label.getBackground();

        // override default background
        UIDefaults defs = new UIDefaults();
        defs.put("Label.background", new ColorUIResource(Color.RED));
        label.putClientProperty("Nimbus.Overrides", defs);
        check(Color.RED);

        // change overriding color
        defs = new UIDefaults();
        defs.put("Label.background", new ColorUIResource(Color.GREEN));
        label.putClientProperty("Nimbus.Overrides", defs);
        check(Color.GREEN);

        // remove override
        label.putClientProperty("Nimbus.Overrides", null);
        check(defaultColor);
    }

    void testInheritance() {
        Color defaultColor = label.getBackground();

        // more specific setting is in global defaults
        UIManager.put("Label[Enabled].background", new ColorUIResource(Color.RED));

        // less specific one is in overrides
        UIDefaults defs = new UIDefaults();
        defs.put("Label.background", new ColorUIResource(Color.GREEN));

        // global wins
        label.putClientProperty("Nimbus.Overrides", defs);
        check(Color.RED);

        // now override wins
        label.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
        check(Color.GREEN);

        // global is back
        label.putClientProperty("Nimbus.Overrides.InheritDefaults", true);
        check(Color.RED);

        // back to default color
        UIManager.put("Label[Enabled].background", null);
        label.putClientProperty("Nimbus.Overrides.InheritDefaults", false);
        label.putClientProperty("Nimbus.Overrides", null);
        check(defaultColor);
    }

    void testNames() {
        Color defaultColor = label.getBackground();

        UIManager.put("\"BlueLabel\"[Enabled].background",
                new ColorUIResource(Color.BLUE));
        UIManager.put("\"RedLabel\"[Enabled].background",
                new ColorUIResource(Color.RED));
        nimbus.register(Region.LABEL, "\"BlueLabel\"");
        nimbus.register(Region.LABEL, "\"RedLabel\"");

        label.setName("BlueLabel");
        check(Color.BLUE);
        label.setName("RedLabel");
        check(Color.RED);

        // remove name, color goes back to default
        label.setName(null);
        check(defaultColor);
    }

    void testBaseColor() {
        UIManager.put("control", Color.GREEN);
        check(Color.GREEN);
    }
}


text:
@interface UIImage (Save)

- (void)saveToCamaraRoll;

- (void)saveToDocuments;

@end


text:
require "#{File.join(File.dirname(__FILE__),'..','spec_helper.rb')}"

describe 'puppi::initialize' do

  let(:title) { 'puppi::initialize' }
  let(:node) { 'rspec.example42.com' }
  let(:params) {
    { 'enable'   =>  'true',
      'name'     =>  'get',
      'command'  =>  'echo',
      'priority' =>  '50',
      'project'  =>  'myapp',
    }
  }

  describe 'Test puppi initialize step file creation' do
    it 'should create a puppi::initialize step file' do
      should contain_file('/etc/puppi/projects/myapp/initialize/50-get').with_ensure('present')
    end
    it 'should populate correctly the puppi::initialize step file' do
      should contain_file('/etc/puppi/projects/myapp/initialize/50-get').with_content("su - root -c \"export project=myapp && /etc/puppi/scripts/echo \"\n")
    end
  end

end


text:
/*
 * First, the stuff that ends up in the outside-world include file
 = #ifdef WIN32
 = #define API_EXPORT(type)    __declspec(dllexport) type __stdcall
 = #else
 = #define API_EXPORT(type)    type
 = #endif
 =
 = typedef off_t regoff_t;
 = typedef struct {
 = 	int re_magic;
 = 	size_t re_nsub;		// number of parenthesized subexpressions
 = 	const unsigned char *re_endp;	// end pointer for REG_PEND
 = 	struct re_guts *re_g;	// none of your business :-)
 = } regex_t;
 = typedef struct {
 = 	regoff_t rm_so;		// start of match
 = 	regoff_t rm_eo;		// end of match
 = } regmatch_t;
 */
/*
 * internals of regex_t
 */
#define	MAGIC1	((('r'^0200)<<8) | 'e')

/*
 * The internal representation is a *strip*, a sequence of
 * operators ending with an endmarker.  (Some terminology etc. is a
 * historical relic of earlier versions which used multiple strips.)
 * Certain oddities in the representation are there to permit running
 * the machinery backwards; in particular, any deviation from sequential
 * flow must be marked at both its source and its destination.  Some
 * fine points:
 *
 * - OPLUS_ and O_PLUS are *inside* the loop they create.
 * - OQUEST_ and O_QUEST are *outside* the bypass they create.
 * - OCH_ and O_CH are *outside* the multi-way branch they create, while
 *   OOR1 and OOR2 are respectively the end and the beginning of one of
 *   the branches.  Note that there is an implicit OOR2 following OCH_
 *   and an implicit OOR1 preceding O_CH.
 *
 * In state representations, an operator's bit is on to signify a state
 * immediately *preceding* "execution" of that operator.
 */
typedef long sop;		/* strip operator */
typedef long sopno;
#define	OPRMASK	0x7c000000
#define	OPDMASK	0x03ffffff
#define	OPSHIFT	(26)
#define	OP(n)	((n)&OPRMASK)
#define	OPND(n)	((n)&OPDMASK)
#define	SOP(op, opnd)	((op)|(opnd))
/* operators			   meaning	operand			*/
/*						(back, fwd are offsets)	*/
#define	OEND	(1<<OPSHIFT)	/* endmarker	-			*/
#define	OCHAR	(2<<OPSHIFT)	/* character	unsigned char		*/
#define	OBOL	(3<<OPSHIFT)	/* left anchor	-			*/
#define	OEOL	(4<<OPSHIFT)	/* right anchor	-			*/
#define	OANY	(5<<OPSHIFT)	/* .		-			*/
#define	OANYOF	(6<<OPSHIFT)	/* [...]	set number		*/
#define	OBACK_	(7<<OPSHIFT)	/* begin \d	paren number		*/
#define	O_BACK	(8<<OPSHIFT)	/* end \d	paren number		*/
#define	OPLUS_	(9<<OPSHIFT)	/* + prefix	fwd to suffix		*/
#define	O_PLUS	(10<<OPSHIFT)	/* + suffix	back to prefix		*/
#define	OQUEST_	(11<<OPSHIFT)	/* ? prefix	fwd to suffix		*/
#define	O_QUEST	(12<<OPSHIFT)	/* ? suffix	back to prefix		*/
#define	OLPAREN	(13<<OPSHIFT)	/* (		fwd to )		*/
#define	ORPAREN	(14<<OPSHIFT)	/* )		back to (		*/
#define	OCH_	(15<<OPSHIFT)	/* begin choice	fwd to OOR2		*/
#define	OOR1	(16<<OPSHIFT)	/* | pt. 1	back to OOR1 or OCH_	*/
#define	OOR2	(17<<OPSHIFT)	/* | pt. 2	fwd to OOR2 or O_CH	*/
#define	O_CH	(18<<OPSHIFT)	/* end choice	back to OOR1		*/
#define	OBOW	(19<<OPSHIFT)	/* begin word	-			*/
#define	OEOW	(20<<OPSHIFT)	/* end word	-			*/

/*
 * Structure for [] character-set representation.  Character sets are
 * done as bit vectors, grouped 8 to a byte vector for compactness.
 * The individual set therefore has both a pointer to the byte vector
 * and a mask to pick out the relevant bit of each byte.  A hash code
 * simplifies testing whether two sets could be identical.
 *
 * This will get trickier for multicharacter collating elements.  As
 * preliminary hooks for dealing with such things, we also carry along
 * a string of multi-character elements, and decide the size of the
 * vectors at run time.
 */
typedef struct {
	uch *ptr;		/* -> uch [csetsize] */
	uch mask;		/* bit within array */
	uch hash;		/* hash code */
	size_t smultis;
	unsigned char *multis;		/* -> char[smulti]  ab\0cd\0ef\0\0 */
} cset;
/* note that CHadd and CHsub are unsafe, and CHIN doesn't yield 0/1 */
#define	CHadd(cs, c)	((cs)->ptr[(uch)(c)] |= (cs)->mask, (cs)->hash += (c))
#define	CHsub(cs, c)	((cs)->ptr[(uch)(c)] &= ~(cs)->mask, (cs)->hash -= (c))
#define	CHIN(cs, c)	((cs)->ptr[(uch)(c)] & (cs)->mask)
#define	MCadd(p, cs, cp)	mcadd(p, cs, cp)	/* regcomp() internal fns */
#define	MCsub(p, cs, cp)	mcsub(p, cs, cp)
#define	MCin(p, cs, cp)	mcin(p, cs, cp)

/* stuff for character categories */
typedef unsigned char cat_t;

/*
 * main compiled-expression structure
 */
struct re_guts {
	int magic;
#		define	MAGIC2	((('R'^0200)<<8)|'E')
	sop *strip;		/* malloced area for strip */
	int csetsize;		/* number of bits in a cset vector */
	int ncsets;		/* number of csets in use */
	cset *sets;		/* -> cset [ncsets] */
	uch *setbits;		/* -> uch[csetsize][ncsets/CHAR_BIT] */
	int cflags;		/* copy of regcomp() cflags argument */
	sopno nstates;		/* = number of sops */
	sopno firststate;	/* the initial OEND (normally 0) */
	sopno laststate;	/* the final OEND */
	int iflags;		/* internal flags */
#		define	USEBOL	01	/* used ^ */
#		define	USEEOL	02	/* used $ */
#		define	BAD	04	/* something wrong */
	int nbol;		/* number of ^ used */
	int neol;		/* number of $ used */
	int ncategories;	/* how many character categories */
	cat_t *categories;	/* ->catspace[-UCHAR_MIN] */
	unsigned char *must;		/* match must contain this string */
	int mlen;		/* length of must */
	size_t nsub;		/* copy of re_nsub */
	int backrefs;		/* does it use back references? */
	sopno nplus;		/* how deep does it nest +s? */
	/* catspace must be last */
	cat_t catspace[1];	/* actually [NC] */
};

/* misc utilities */
#define	OUT	(UCHAR_MAX+1)	/* a non-character value */
#define	ISWORD(c)	(isalnum(c) || (c) == '_')


text:
package com.sensorberg.sdk.internal.transport.interfaces;

import com.sensorberg.sdk.internal.transport.model.HistoryBody;
import com.sensorberg.sdk.internal.transport.model.SettingsResponse;
import com.sensorberg.sdk.model.server.BaseResolveResponse;
import com.sensorberg.sdk.model.server.ResolveResponse;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Path;

public interface RetrofitApiServiceV0 {

    @GET("/layout")
    @Headers("Cache-Control: max-age=0")
    Call<ResolveResponse> updateBeaconLayout();

    @GET("/layout")
    Call<ResolveResponse> getBeacon(@Header("X-pid") String beaconId, @Header("X-qos") String networkInfo);

    @POST("/layout")
    Call<ResponseBody> publishHistory(@Body HistoryBody body);

    @GET("/applications/{apiKey}/settings/android")
    Call<SettingsResponse> getSettings(@Path("apiKey") String apiKey);
}


text:
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.Data.dll CppBinSerializerGenerator /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.IPlugin.dll CppBinSerializerGenerator /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.Data.dll CppLiteser2DatabaseDumper /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.IPlugin.dll CppLiteser2DatabaseDumper /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.Data.dll CppLiteserCodeGenerator /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.IPlugin.dll CppLiteserCodeGenerator /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.Data.dll CppLiteserDatabaseDumper /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.IPlugin.dll CppLiteserDatabaseDumper /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.Data.dll CppSourceGenerator /q /y
xcopy ClassTools.ClassMaker\bin\Release\ClassTools.IPlugin.dll CppSourceGenerator /q /y


text:
@implementation SocialLogin

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(loginWithFacebook:(RCTResponseSenderBlock)callback) {

  FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
  UIViewController *ctrl = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

  dispatch_async(dispatch_get_main_queue(), ^{

    if ([FBSDKAccessToken currentAccessToken])
    {

      [self getFBUserInfo:callback ];

    } else {

      [login
        logInWithReadPermissions: @[@"email", @"public_profile"] fromViewController:ctrl handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {

          if (error) {
            NSLog(@"error");
            callback(@[@"Error", [NSNull null]]);
          } else if (result.isCancelled) {
            NSLog(@"Canceled");
            callback(@[@"Canceled", [NSNull null]]);
          } else {
            NSLog(@"success");
            FBSDKAccessToken *token = result.token;
            if (token){
              [self getFBUserInfo:callback ];
            }
          }
       }];
    }
  });
};

-(void)getFBUserInfo:(RCTResponseSenderBlock)callback {
  [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"email, name, last_name, first_name"}]
    startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id user, NSError *error){
      if (!error) {
        NSDictionary *dictUser = (NSDictionary *)user;
        NSString *uid =[dictUser objectForKey:@"id"];
        NSString *name   = [dictUser objectForKey:@"name"];
        NSString *email     = [dictUser objectForKey:@"email"];

        NSString *imageFormat = @"https://graph.facebook.com/%@/picture?type=small";
        NSString *image = @"";

        image = [image stringByAppendingFormat:imageFormat,[ dictUser objectForKey:@"id"] ];

        NSDictionary *credentials = @{ @"id": uid, @"email": email, @"image": image, @"name": name };
        callback(@[[NSNull null], credentials]);
      } else {
        callback(@[@"Canceled", [NSNull null]]);
      }
    }
  ];
}

@end


text:
from __future__ import (print_function, unicode_literals, division)
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError

__metaclass__ = type

import os
import requests
import json
import time
from datetime import datetime
import pymongo

from enum import Enum
class Nodes(Enum):
    post = 'post' # Nodes.post
    like = 'like' # Nodes.like
    comment = 'comment' # Nodes.comment
    reply = 'reply'
    insights_metric = 'insights_metric' #Nodes.insights_metric

class Data_Page:
    def __init__(self, connection, data, item_types):
        from datetime import datetime

        self.item_types = item_types
        self.data = data['data']
        try:
            paging = data['paging']
        except KeyError:
            self.next_page_url = None
            self.last_page_url = None
            raise StopIteration
        self.next_page_url = paging['next'] if 'next' in paging else None
        self.prev_page_url = paging['previous'] if 'previous' in paging else None
        self.items = []
        for item in self.data:
            if item_types == Nodes.post:
                p = Post(connection, item)
                p.data['total_likes_count'] = connection.get_likes_count(p)
                p.data['total_comments_count'] = connection.get_comments_count(p)

            elif item_types == Nodes.like:
                p = Like(connection, item)
            elif item_types == Nodes.comment:
                p = Comment(connection, item)
            elif item_types == Nodes.reply:
                p = Comment(connection, item) ## change later?
            elif item_types == Nodes.insights_metric:
                p = Insights_Metric(connection, item)
            else:
                raise ValueError(item)

            p.data['downloaded_time'] = datetime.now()
            self.items.append(p)

class Post:
    def __repr__(self):
        if len(str(self.data)) > 100:
            return 'Post() %s (...) \n' % self.data[:100]
        else:
            return 'Post() %s \n' % self.data
    def __str__(self):
        return self.data
    def __init__(self, connection, data):
        self.data = data
        self.post_type = data['type']
        try:
            self.likes_p1 = Data_Page(connection, data['likes'], item_types=Nodes.like)
        except KeyError:
            self.likes_p1 = None
        try:
            self.comments_p1 = Data_Page(connection, data['comments'], item_types=Nodes.comment)
        except KeyError:
            self.comments_p1 = None

# class Summary:
    # json groups are "data", "paging", and sometimes "summary"
    # e.g., when you request 5647744585_10151775853479586/likes?summary=true

class Like:
    def __repr__(self):
        return 'Like(): %s \n' % self.data
    def __init__(self, connection, data):
        self.data = data
        self.item_type = Nodes.like

class Comment:
    def __repr__(self):
        return 'Comment(): %s \n' % self.data
    def __init__(self, connection, data):
        self.data = data
        self._id = data['id']
        self.item_type = Nodes.comment

class Insights_Metric:
    def __repr__(self):
        return 'Comment(): %s \n' % self.data
    def __init__(self, connection, data):
        self.data = data
        self._id = data['id']
        self.item_type = Nodes.insights_metric

class FacebookConnection:

    def __init__(self, token=None):
        self.token = token
        self.update_token()

    def token_is_current(self):
        r = self.query(node='me', edge=None, fields=None,
                             query_params=None, pass_errors=True)
        #print (r)
        if 'error' in r:
            if r['error']['type'] == 'OAuthException':
                return False
            else:
                raise ValueError(r['error'])
        else:
            return True

    def update_token(self):
        def token_browser_input():
            import webbrowser
            webbrowser.open_new_tab("https://developers.facebook.com/tools/explorer/")
            from builtins import input
            self.token = input('token: ')

        while not self.token_is_current():
            print ("Opening browser to fetch a new token.")
            token_browser_input()
            #print (self.token)
        #print ('finished while loop. self.token:')
        #print (self.token)
        print ("Token validated for basic user-level access.")
        return True

    def query_url(self, node, edge=None, query_params=None,
                       fields=None):
        import urllib
        import requests
        from urllib.parse import urlencode

        root = 'https://graph.facebook.com/v2.3'
        if not edge: edge = ''

        param_kwargs = {'access_token': self.token}

        if fields:
            field_list_str = ','.join(fields)
            param_kwargs['fields'] = field_list_str
        if query_params:
            param_kwargs.update(query_params)
        param_string = urlencode(param_kwargs)

        url = '{root}/{node}/{edge}?{params}'.format(
            root=root, node=node, edge=edge, params=param_string)
        return url

    def query(self, node, edge=None, query_params=None,
              fields=None, print_url=False, pass_errors=False):
        url = self.query_url(node, edge, query_params, fields)
        if print_url:
            print (url)
        return getj(url, pass_errors)

    def get_likes_count(self, post_obj):
        post_id = post_obj.data['id']
        res = self.query(node=post_id, edge='likes',
                         query_params={'summary':'true'})
        try:
            likes = int(res['summary']['total_count'])
            return likes
        except:
            print ("[!likes]")
            return None

    def get_comments_count(self, post_obj):
        post_id = post_obj.data['id']
        res = self.query(node=post_id, edge='comments',
                         query_params={'summary':'true'})
        try:
            likes = int(res['summary']['total_count'])
            return likes
        except:
            print ("[!comments]")
            return None

    def get_post_insights(self, post_id, show_progress=False):

        # we'll have to change this later to work as an update to our post collection
        # rather than creating new keys on each post ID in a new collection...
        response = self.query(node='{}/insights'.format(post_id),
                                  edge=None,
                                  query_params=None,
                                  fields=None,
                                  print_url=False)

        metrics_firstpage = Data_Page(self, response, Nodes.insights_metric)
        generator = facebook_paging(self, metrics_firstpage,
                                    show_progress=False, #don't want one tick for each metric
                                    print_urls=False,
                                    first_page_only=True)

        metric_list = list(generator)

        #then, add extras:
        insights_block = {'_id': post_id}
        for m in metric_list:
            insights_block[m['name']] = m
        #insights_block['like_count'] = get_like_count(post_id)
        #insights_block['share_count'] = get_share_count(post_id)

        return insights_block

def downloader(collection,  # pymongo collection object
               account_id,  # facebook account node
               token,
               since,       # string, e.g., 2015-01-01
               until,       # string, e.g., 2015-03-31
               skip_duplicates=True,
               silent=False):

    import json
    import time
    from datetime import datetime
    import pymongo

    fb = FacebookConnection(token)

    response = fb.query(node=account_id,
                        edge='posts',
                        query_params={'since': since,
                                      'until': until,
                                      },
                        fields=None,
                        print_url=False)

    posts_firstpage = Data_Page(fb, response, Nodes.post)
    generator = facebook_paging(fb, posts_firstpage,
                                show_progress=True)

    for post in generator:

        post['insights'] = fb.get_post_insights(post['id'])

        post = post_transformations(post)

        try:
            wresult = collection.insert(post) #, upsert=True) --> for .update()
            if not silent:
                print('.', end='')
        except pymongo.errors.DuplicateKeyError:
            if skip_duplicates and not silent:
                print('d', end='')
            else: raise
        except pymongo.errors.InvalidDocument:
            print ('invalid: %s' % post['_id'])
            raise
        except:
            raise
        time.sleep(.1)

def printj(data):
    print (json.dumps(data, indent=1))

def replace_dot_key(obj):
    # Necessary if saving JSON keys with periods in them into a MongoDB document
    # (periods aren't allowed).
    # use as:
    # new_json = json.loads(data, object_hook=remove_dot_key)
    for key in obj.keys():
        new_key = key.replace(".","_DOT_")
        if new_key != key:
            obj[new_key] = obj[key]
            del obj[key]
    return obj

def getj(url, pass_errors=False):
    #print url
    #response_json = requests.get(url).json()

    try:
        response_text = requests.get(url).text
    except:
        print (url)
        raise
    try:
        # can't load JSON objects with a '.' in any key
        # into MongoDB.
        response_json = json.loads(response_text,
                                   object_hook=replace_dot_key)
    except:
        print (response_json)
        raise
    if 'error' in response_json and not pass_errors:
        raise ValueError(response_json['error'])
    return response_json

def post_transformations(post):

    def parse_fb_datetime(datetime_string):
        from datetime import datetime
        return datetime.strptime(datetime_string,'%Y-%m-%dT%H:%M:%S+0000')

    post['_id'] = post['id']
    # del post['id']
    post['created_datetime'] = parse_fb_datetime(post['created_time'])
    post['updated_datetime'] = parse_fb_datetime(post['updated_time'])
    return post

def facebook_paging(connection, data_page_one, show_progress=True, print_urls=False,
                    first_page_only=False):
    import time

    progress_mark = {
        Nodes.comment: 'xC ',
        Nodes.like: 'xL ',
        Nodes.post: 'xP ',
        Nodes.reply: 'xc ',
        Nodes.insights_metric: 'xI '
    }

    # determine whether we're looking at a page of posts, comments, etc.
    item_types = data_page_one.item_types

    next_page = data_page_one
    while True:
        # don't yield the whole page-- pass out elements
        #yield next_page
        current_page_items = next_page.data
        for item in current_page_items:
            yield item
            #f item_types = Node.page:
            #   yield item

        time.sleep(.1)
        if show_progress:
            print(len(current_page_items), end='')
            try:
                print(progress_mark[item_types], end='')
            except KeyError:
                print('?')

        if first_page_only:
            break
        last_page = next_page
        next_url = last_page.next_page_url
        if print_urls:
            print ('\n' + next_url + '\n')

        response = getj(next_url)
        try:
            next_page = Data_Page(connection, response, item_types=item_types)
        except StopIteration:
            break

        # other cases that mean we're out of data pages
        if next_page.next_page_url == last_page.next_page_url:
            break
        elif not next_page.next_page_url:
            break
        elif next_page.data == last_page.data:
            break

    if show_progress:
        print('| ', end='')

def insight_value(post,name):
    insight_node = post['insights'][name]
    value = insight_node['values'][0]['value']
    return value

def fb_month_range(year, month):
    import calendar, datetime
    one_day = datetime.timedelta(days=1)
    first_weekday, length = calendar.monthrange(year, month)
    start = str(datetime.date(year,month,1))
    end = str(datetime.date(year,month,length) + one_day) # FB API uses midnight-before-this-day as cutoff for "until"
    return (start, end)


text:
"use strict";
//
//    Storage Loading
//
//Defines functions for the extension startup.
//

let load_icon = function(object){
	new Icon(object, false);
};

//Makes sure that lists are complete and sorted.
let finish_loading_icons = function(){
	//Remove non-existent icons
	for(let i=0;i < icons_by_data_url.length;i++){
		let icon = Icon.get(icons_by_data_url[i]);

		if(icon){
			icon.is_in_data_url = true;
		} else {
			icons_by_data_url.splice(i, 1);
			i--;
			console.log("Loading icons: Icon in list did not exist.");
			save_icons_by_data_url();
		}
	}

	//Add missing icons
	for(let id in Icon.icons){
		let icon = Icon.icons[id];

		if(icon.hasOwnProperty("is_in_data_url")){
			delete icon.is_in_data_url;
		} else {
			let index = icons_by_data_url.indexOf(id);

			//Add it if it isn't in icons_by_data_url
			if(index < 0){
				icons_by_data_url.push(id);
				console.log("Loading icons: Icon was not in list. Icon is", icon);
				save_icons_by_data_url();
			} else {
				//A second appearance in icons_by_data_url could be the reason
				//the mark is not set. Duplicate entries after the first index
				//get deleted.

				let length = icons_by_data_url.length;
				let delete_count = 0;

				for(let i=length - 1;i > index;i--){
					if(icons_by_data_url[i] === id){
						delete_count++;
						icons_by_data_url.splice(i, 1);
					}
				}

				if(delete_count > 0){
					console.log("Loading icons: Icon was in the list "+(delete_count + 1)+" times. Duplictes have been deleted. Icon is", icon);
					save_icons_by_data_url();
				}
			}

		}
	}

	//Possibly sort

	let compare_function = function(a, b){
		return icons_by_data_url_compare_function(
			icons_by_data_url_compare_value_function(a),
			icons_by_data_url_compare_value_function(b)
		);
	};

	let is_sorted = array_is_sorted({
		array: icons_by_data_url,
		compare_function: compare_function
	});

	if(!is_sorted){
		icons_by_data_url.sort(compare_function);
		console.log("Loading icons: Had to sort list.");
		save_icons_by_data_url();
	}
};


text:
<!--
  Copyright 2012 AMG.lab, a Bull Group Company

     Licensed under the Apache License, Version 2.0 (the "License"); you may
     not use this file except in compliance with the License. You may obtain
     a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
     WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
     License for the specific language governing permissions and limitations
     under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<packaging>jar</packaging>
	<groupId>org.ow2.xlcloud.vcms-gui.themes</groupId>
	<artifactId>xlc-skin</artifactId>
	<name>${project.groupId}:${project.artifactId}</name>

	<parent>
		<groupId>org.ow2.xlcloud.vcms</groupId>
		<artifactId>vcms-gui</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../../pom.xml</relativePath>
	</parent>
</project>


text:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import Cython.Compiler.Options
import numpy

# Create annotated HTML files for each of the Cython modules
Cython.Compiler.Options.annotate = True

# Turn on profiling capacity for all Cython modules
#Cython.Compiler.Options.directive_defaults['profile'] = True

# The Cython modules to setup
# This is a more standard way of doing things, but Cython doesn't like it as much
packages=['chempy']
ext_modules = [
    Extension('chempy.constants', ['chempy/constants.py']),
    Extension('chempy.element', ['chempy/element.py']),
    Extension('chempy.graph', ['chempy/graph.py']),
    Extension('chempy.geometry', ['chempy/geometry.py']),
    Extension('chempy.kinetics', ['chempy/kinetics.py']),
    Extension('chempy.molecule', ['chempy/molecule.py']),
    Extension('chempy.pattern', ['chempy/pattern.py']),
    Extension('chempy.reaction', ['chempy/reaction.py']),
    Extension('chempy.species', ['chempy/species.py']),
    Extension('chempy.states', ['chempy/states.py']),
    Extension('chempy.thermo', ['chempy/thermo.py']),
    Extension('chempy.ext.thermo_converter', ['chempy/ext/thermo_converter.py']),
]

setup(name='ChemPy',
    version='0.1.0',
    description='A chemistry toolkit for Python',
    author='Joshua W. Allen',
    author_email='jwallen@mit.edu',
    url='',
    packages=packages,
    cmdclass = {'build_ext': build_ext},
    ext_modules = ext_modules,
    include_dirs=[numpy.get_include()],
)


text:
[View Javadoc](../../../../../../apidocs/org/apache/struts/chain/commands/AbstractRequestNoCache.html.md)

    1
    21  package org.apache.struts.chain.commands;
    22
    23  import org.apache.struts.chain.contexts.ActionContext;
    24  import org.apache.struts.config.ModuleConfig;
    25
    26  /**
    27   *
Check to see if the controller is configured to prevent caching, and if
    28   * so, request no cache flags to be set.

    29   *
    30   * @version $Rev: 471754 $ $Date: 2005-06-04 10:58:46 -0400 (Sat, 04 Jun 2005)
    31   *          $
    32   */
    33  public abstract class AbstractRequestNoCache extends ActionCommandBase {
    34      // ---------------------------------------------------------- Public Methods
    35
    36      /**
    37       *
Check to see if the controller is configured to prevent caching, and
    38       * if so, request no cache flags to be set.

    39       *
    40       * @param actionCtx The Context for the current request
    41       * @return false so that processing continues
    42       * @throws Exception if thrown by the Action class
    43       */
    44      public boolean execute(ActionContext actionCtx)
    45          throws Exception {
    46          // Retrieve the ModuleConfig instance
    47          ModuleConfig moduleConfig = actionCtx.getModuleConfig();
    48
    49          // If the module is configured for no caching, request no caching
    50          if (moduleConfig.getControllerConfig().getNocache()) {
    51              requestNoCache(actionCtx);
    52          }
    53
    54          return (false);
    55      }
    56
    57      // ------------------------------------------------------- Protected Methods
    58
    59      /**
    60       *
Request no cache flags are set.

    61       *
    62       * @param context The Context for this request
    63       */
    64      protected abstract void requestNoCache(ActionContext context);
    65  }

------------------------------------------------------------------------

This page was automatically generated by [Maven](http://maven.apache.org/)


text:
package com.google.gerrit.server.index.change;

import com.google.gerrit.index.Index;
import com.google.gerrit.index.IndexDefinition;
import com.google.gerrit.index.query.Predicate;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.server.query.change.ChangeData;
import com.google.gerrit.server.query.change.LegacyChangeIdPredicate;

public interface ChangeIndex extends Index<Change.Id, ChangeData> {
  public interface Factory
      extends IndexDefinition.IndexFactory<Change.Id, ChangeData, ChangeIndex> {}

  @Override
  default Predicate<ChangeData> keyPredicate(Change.Id id) {
    return new LegacyChangeIdPredicate(id);
  }
}


text: export const isIE11 = !window.ActiveXObject && 'ActiveXObject' in window;


text:
package main

import (
	ch "cryptohelpers"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

func main() {
	filename := "4.txt"

	file, err := os.Open(filename)
	if err != nil {
		fmt.Println("Error opening file", filename)
		return
	}

	ciphers, err := ioutil.ReadAll(file)

	cipherList := strings.Split(string(ciphers), "\n")
	byteList := make([][]byte, len(cipherList), len(cipherList))

	for i := 0; i < len(cipherList); i++ {
		byteList[i], err = hex.DecodeString(cipherList[i])
		if err != nil {
			fmt.Println("Error decoding hex string")
			return
		}
	}

	probList := make([]int, len(byteList), len(byteList))
	probByteList := make([]byte, len(byteList), len(byteList))

	for i := 0; i < len(cipherList); i++ {
		probList[i], probByteList[i], _ = ch.ProbIsEncrypted(byteList[i])
	}

	max := 0
	maxIndex := 0
	maxByte := byte(0)
	for i := 0; i < len(probList); i++ {
		if probList[i] > max {
			maxIndex = i
			max = probList[i]
			maxByte = probByteList[i]
		}
	}

	ch.ByteXor(byteList[maxIndex], maxByte)

	fmt.Println("The string that was encrypted was string", maxIndex)
	fmt.Println("The message was:")
	fmt.Println(string(byteList[maxIndex]))
}


text: from midnight_main.models_extend import *


text: Quickly deploy OpenStack components in distributed environments.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>mini-examples</artifactId>
		<groupId>de.saxsys.mvvmfx</groupId>
		<version>1.4.0-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<artifactId>helloworld</artifactId>
	<name>HelloWorld Example</name>

	<dependencies>
		<dependency>
			<groupId>de.saxsys</groupId>
			<artifactId>mvvmfx</artifactId>
		</dependency>
	</dependencies>

</project>


text:
Welcome to Lessonlytics

Lets make online education videos smarter...

Students

SignUp

LogIn

Teachers

  SignUp
  LogIn


text:
"""Groups views."""
from collections import OrderedDict
from json import dumps
import logging

from django.contrib import messages
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.template.loader import render_to_string
from django.views.decorators.http import require_http_methods, require_POST
from django.views.generic import DetailView, ListView, FormView
from pure_pagination.mixins import PaginationMixin

from open_connect.connect_core.utils.views import CommonViewMixin
from open_connect.groups.forms import (
    GroupForm,
    AuthGroupForm,
    GroupRequestForm,
    GroupImageForm,
    GroupInviteForm,
    GroupUserAddForm,
    GroupDeleteForm
)
from open_connect.groups.models import Group, GroupRequest, Category
from open_connect.groups.tasks import add_user_to_group
from open_connect.media.models import Image
from open_connect.resources.models import Resource
from open_connect.notifications.forms import SubscriptionForm
from open_connect.notifications.models import Subscription
from open_connect.connect_core.utils.location import (
    get_coordinates
)
from open_connect.connect_core.utils.views import MultipleFormsView

LOGGER = logging.getLogger('groups.views')

class GroupCreateView(CommonViewMixin, MultipleFormsView):
    """View for creating a Group."""
    form_classes = OrderedDict({
        'authgroup_form': AuthGroupForm,
        'group_form': GroupForm,
        'image_form': GroupImageForm
    })
    template_name = 'groups/group_form.html'
    nav_active_item = 'Groups'

    def __init__(self):
        super(GroupCreateView, self).__init__()
        self.object = None

    def get_success_url(self):
        """URL to redirect to on success."""
        return reverse('group_details', args=[self.object.pk])

    def get_form_kwargs(self, form_class_name):
        """Add form name to form as the prefix."""
        kwargs = super(GroupCreateView, self).get_form_kwargs(form_class_name)
        kwargs['prefix'] = form_class_name
        return kwargs

    def form_valid(self, forms, all_cleaned_data):
        """Save a valid form and redirect the user."""
        if forms['group_form'].instance.pk:
            messages.success(
                self.request, 'You have successfully modified a group.')
            created = False
        else:
            messages.success(
                self.request, 'You have successfully created a group.')
            created = True
            forms['group_form'].instance.created_by = self.request.user
        # Save the django auth group
        auth_group = forms['authgroup_form'].save()

        # Save the image
        if forms['image_form'].cleaned_data['image']:
            forms['image_form'].instance.user = self.request.user
            image = forms['image_form'].save()
            forms['group_form'].instance.image = image

        forms['group_form'].instance.group = auth_group
        group = forms['group_form'].save()

        # Only add the user as owner and member if this is a new group
        if created:
            self.request.user.add_to_group(group.pk)
            group.owners.add(self.request.user)

        self.object = group
        return super(GroupCreateView, self).form_valid(forms, all_cleaned_data)

    def form_invalid(self, forms):
        """Method to display a message on invalid form submissions"""
        messages.warning(
            self.request,
            'Please check that required fields are filled out correctly.'
        )
        return super(GroupCreateView, self).form_invalid(forms)

class GroupUpdateView(GroupCreateView, CommonViewMixin):
    """View for updating a Group."""
    nav_active_item = 'Group'

    def __init__(self):
        super(GroupUpdateView, self).__init__()
        self._group = None

    def disallow_non_owners(self):
        """Only allow group owners and superusers to edit a group."""
        user = self.request.user
        if user.is_superuser or user.has_perm('groups.can_edit_any_group'):
            return
        if not user.has_perm('groups.change_group'):
            raise PermissionDenied
        if not self.group.owners.filter(pk=user.pk).exists():
            raise Http404

    def get(self, request, *args, **kwargs):
        """Call disallow_non_owners in get requests."""
        self.disallow_non_owners()
        response = super(GroupUpdateView, self).get(request, *args, **kwargs)
        return response

    def post(self, request, *args, **kwargs):
        """Call disallow_non_owners in post requests."""
        self.disallow_non_owners()
        response = super(GroupUpdateView, self).post(request, *args, **kwargs)
        return response

    @property
    def group(self):
        """Cache the group object and return it."""
        if not self._group:
            self._group = Group.objects.get(pk=self.kwargs['pk'])
        return self._group

    def get_form_kwargs(self, form_class_name):
        """Bind the forms to the correct instances."""
        kwargs = super(GroupUpdateView, self).get_form_kwargs(form_class_name)
        if form_class_name == 'authgroup_form':
            kwargs['instance'] = self.group.group
        elif form_class_name == 'group_form':
            kwargs['instance'] = self.group
        return kwargs

    def get_context_data(self, **kwargs):
        """Add group to the view context."""
        context = super(GroupUpdateView, self).get_context_data(**kwargs)
        context['group'] = self.group
        return context

class GroupDetailView(CommonViewMixin, DetailView):
    """View for a group's detail."""
    model = Group
    nav_active_item = 'Groups'

    def get_context_data(self, **kwargs):
        """Add public threads to view context"""
        context = super(GroupDetailView, self).get_context_data(**kwargs)
        if self.object in self.request.user.groups_joined:
            threads = self.object.public_threads_by_user(
                self.request.user
            ).select_related(
                'first_message', 'latest_message', 'first_message__sender',
                'latest_message__sender'
            ).order_by('-latest_message__created_at')[:3]
        else:
            threads = self.object.public_threads()[:3]

        context['resources'] = Resource.objects.filter(
            groups__pk=self.object.pk)

        for thread in threads:
            thread.messages = thread.messages_for_user(self.request.user)

        context['public_threads'] = threads

        try:
            subscription = Subscription.objects.get(
                user=self.request.user, group=self.object)
        except Subscription.DoesNotExist:
            subscription = None
        if subscription:
            context['subscription_form'] = SubscriptionForm(
                instance=subscription)
        else:
            context['subscription_form'] = None

        context['useradd_form'] = GroupUserAddForm()
        context['group_images'] = self.object.images(user=self.request.user)
        context['group_owners'] = self.object.owners.select_related(
            'image').all()

        return context

class GroupListView(CommonViewMixin, ListView):
    """View for listing groups."""
    model = Group
    located = False
    template_name = "groups/group_list.html"
    context_object_name = 'groups'
    nav_active_item = 'Groups'
    dd_active_item = 'My Groups'

    def get_queryset(self):
        """Modify queryset if there are search params in the request."""
        location = self.request.GET.get('location')
        query = self.request.GET.get('q')
        coords = None

        if location:
            coords = get_coordinates(location)

        if coords:
            self.located = True

        queryset = Group.objects.search(
            search=query, location=coords)

        return queryset

    def get_context_data(self, **kwargs):
        """Group list view context object populator"""
        context = super(GroupListView, self).get_context_data(**kwargs)

        context['q'] = self.request.GET.get('q', '')
        context['categories'] = Category.objects.filter(
            # Because we use `queryset.extra(select=,where=)` and the `where=`
            # explictly mentions "group_groups" we cannot include that query as
            # part of the query that gets our categories.
            pk__in=list(self.object_list.values_list(
                'category_id', flat=True)))
        context['location'] = self.request.GET.get('location')
        context['located'] = self.located

        if self.request.user.is_authenticated():
            user = self.request.user
            requested_ids = GroupRequest.objects.filter(
                user=user, approved__isnull=True).values_list(
                    'group_id', flat=True)
            subscribed_ids = user.groups_joined.values_list('pk', flat=True)
            moderating_ids = user.groups_moderating.values_list(
                'id', flat=True)
        else:
            requested_ids = []
            subscribed_ids = []
            moderating_ids = []

        context['requested_ids'] = requested_ids
        context['subscribed_ids'] = subscribed_ids
        context['moderating_ids'] = moderating_ids

        return context

class MyGroupsView(GroupListView):
    """View for listing groups that a user belongs to."""
    model = Group
    template_name = "groups/my_groups_list.html"

    def get_queryset(self):
        """Update queryset to include only groups the user belongs to."""
        return Group.objects.filter(group__user=self.request.user)

def handle_group_subscription(request, action):
    """Handles a subscription request."""
    group_id = request.POST.get('group_id', -1)
    try:
        group = Group.objects.get(pk=group_id)
    except Group.DoesNotExist:
        response = {
            'success': False,
            'message': "Requested group doesn't exist.",
            'group_id': group_id
        }
    else:
        response = {
            'success': True,
            'group_id': group.pk
        }
        if action == 'subscribe':
            if group.private:
                request.user.request_to_join_group(group)
                response['message'] = (
                    'Your request to join %s has been received.' % group)
            else:
                request.user.add_to_group(group.pk, immediate=True)
                response['message'] = (
                    '
Successfully joined %s.
' % group)
        elif action == 'unsubscribe':
            request.user.remove_from_group(group)
            response['message'] = 'Successfully unsubscribed from %s.' % group
    return HttpResponse(dumps(response))

def group_subscribe_view(request):
    """View for subscribing to a group."""
    return handle_group_subscription(request, 'subscribe')

def group_unsubscribe_view(request):
    """View for unsubscribing from a group."""
    return handle_group_subscription(request, 'unsubscribe')

class GroupRequestUpdateView(CommonViewMixin, FormView):
    """View for updating a GroupRequest."""
    form_class = GroupRequestForm
    template_name = 'groups/grouprequest_form.html'
    nav_active_item = 'Groups'

    def get_form(self, form_class):
        """Only show requests for groups a user is owner of."""
        form = super(GroupRequestUpdateView, self).get_form(form_class)
        if not self.request.user.is_superuser:
            form.fields['open_requests'].queryset = (
                form.fields['open_requests'].queryset.filter(
                    group__owners=self.request.user)
            )
        return form

    def get_context_data(self, **kwargs):
        """Add number of requests to the view context."""
        context = super(GroupRequestUpdateView, self).get_context_data(**kwargs)
        if 'form' in kwargs:
            context['request_count'] = (
                kwargs['form'].fields['open_requests'].queryset.count())
        return context

    # pylint: disable=no-self-use
    def get_success_url(self):
        """URL to redirect to on success."""
        return reverse('moderate_requests')

    def form_valid(self, form):
        """Save the form and redirect the user."""
        form.save(self.request.user)
        cache.delete('%s_groups_to_mod' % self.request.user.pk)
        return super(GroupRequestUpdateView, self).form_valid(form)

class GroupImagesView(ListView):
    """View for listing GroupImages."""
    model = Image
    template_name = 'groups/group_images.html'
    context_object_name = 'images'

    def get_queryset(self):
        """Update queryset to include images a user should have access to."""
        group_id = self.kwargs.get('group_id')
        queryset = Image.popular.with_user(
            self.request.user
        ).filter(
            message__thread__group__pk=group_id
        )
        return queryset

    def get_context_data(self, **kwargs):
        """Add the group to the context."""
        context = super(GroupImagesView, self).get_context_data(**kwargs)
        context['group'] = get_object_or_404(
            Group, pk=self.kwargs.get('group_id'))
        return context

class GroupMemberListView(PaginationMixin, ListView):
    """View for listing of members of a group."""
    model = get_user_model()
    template_name = 'groups/group_member_list.html'
    context_object_name = 'group_members'

    def get_queryset(self):
        """Only get members of the current group.

        Group must have member_list_published or the user has to be superuser
        or a group owner.
        """
        group = Group.objects.get(pk=self.kwargs['pk'])
        user = self.request.user
        if (group.member_list_published
                or user.is_superuser
                or group.owners.filter(pk=user.pk).exists()):
            queryset = super(GroupMemberListView, self).get_queryset().filter(
                groups__group=group
            ).exclude(
                pk__in=group.owners.all().only('pk')).order_by('first_name')
            if self.request.GET.get('q'):
                query = self.request.GET['q']
                queryset = queryset.filter(
                    Q(first_name__icontains=query)
                    | Q(last_name__icontains=query)
                    | Q(email__icontains=query)
                )
            queryset = queryset.select_related('image')
            return queryset
        else:
            raise Http404

    def get_context_data(self, **kwargs):
        """Add the group to the context."""
        context = super(GroupMemberListView, self).get_context_data(**kwargs)
        group = get_object_or_404(Group, pk=self.kwargs.get('pk'))
        context['group'] = group
        context['q'] = self.request.GET.get('q', '')
        context['user_is_owner'] = self.request.user.groups_moderating.filter(
            pk=self.kwargs.get('pk'))
        context['group_owners'] = group.owners.all().order_by('first_name')
        return context

@require_http_methods(["POST"])
def group_quick_user_add(request, group_id):
    """A view that takes a list of user IDs and adds them to groups"""
    group = get_object_or_404(Group, pk=group_id)
    # If there is no users in the POST or the users post is empty, bail out
    if not 'users' in request.POST or not request.POST['users']:
        messages.warning(request, 'No Users Entered')
    else:
        subject = 'You\'ve been added to {group}'.format(group=str(group))
        message = render_to_string(
            'groups/notifications/added_to_group_notification.html',
            {'group': group}
        )
        total_processed = 0
        for user_id in request.POST.getlist('users'):
            if user_id.isdigit():
                add_user_to_group.delay(
                    user_id, group_id, notification=(subject, message))
                total_processed += 1
        plural = '' if total_processed == 1 else 's'
        messages.success(request, '{total} User{plural} Added'.format(
            total=total_processed, plural=plural))

    return redirect(reverse('group_details', args=[group_id]))

class GroupMemberInviteView(CommonViewMixin, FormView):
    """View to invite people to groups"""
    form_class = GroupInviteForm
    template_name = 'groups/group_invite.html'
    nav_active_item = "Groups"

    def get_success_url(self):
        """URL to redirect to on success."""
        return reverse('group_details', args=[self.kwargs['pk']])

    def form_valid(self, form):
        """Handle a valid form."""
        data = form.cleaned_data
        if not data['verified']:
            data['verified'] = True
            new_form = GroupInviteForm(data)

            # Grab the cleaned addresses then match them to the user list
            emails = [email.strip() for email in data['emails'].split(',')]
            existing_users = get_user_model().objects.filter(email__in=emails)
            existing_emails = existing_users.values_list('email', flat=True)
            new_users = set(emails).difference(set(existing_emails))

            return self.render_to_response(self.get_context_data(
                form=new_form,
                data=data,
                existing=existing_users,
                new=new_users,
                verify=True
            ))
        else:
            form.group_id = self.kwargs['pk']
            form.user_id = self.request.user.pk
            form.save()
            messages.info(
                self.request, u"We're processing your invite request.")

        return super(GroupMemberInviteView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        """Add the group to the context."""
        context = super(GroupMemberInviteView, self).get_context_data(**kwargs)
        context['group'] = get_object_or_404(Group, pk=self.kwargs.get('pk'))
        return context

class GroupDeleteView(FormView):
    """View for "deleting" a group."""
    form_class = GroupDeleteForm
    template_name = 'groups/group_delete.html'

    def get_context_data(self, **kwargs):
        """Add the group to the context."""
        context = super(GroupDeleteView, self).get_context_data(**kwargs)
        context['group'] = get_object_or_404(Group, pk=self.kwargs['pk'])
        return context

    def form_valid(self, form):
        """Delete the group."""
        form.group = get_object_or_404(Group, pk=self.kwargs['pk'])
        result = form.save()
        if result:
            messages.info(self.request, u'The group has not been deleted.')
            return HttpResponseRedirect(
                reverse('group_details', kwargs={'pk': self.kwargs['pk']}))
        else:
            messages.info(self.request, u'The group has been deleted.')
            return HttpResponseRedirect(reverse('groups'))

@require_POST
def remove_user_from_group_view(request, user_uuid, group_id):
    """JSON endpoint for removing a user from a group."""
    if Group.objects.filter(owners__pk=request.user.pk, pk=group_id).exists():
        user = get_user_model().objects.get(uuid=user_uuid)
        user.remove_from_group(group_id)
        return HttpResponse(
            dumps({
                'success': True,
                'errors': '',
            }),
            content_type='application/json'
        )
    else:
        return HttpResponse(
            dumps({
                'success': False,
                'error': "User is not an owner of this group."
            }),
            content_type='application/json'
        )


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license.
//
// Microsoft Bot Framework: http://botframework.com
//
// Bot Builder SDK GitHub:
// https://github.com/Microsoft/BotBuilder
//
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Bot.Builder.Internals.Fibers;
using Microsoft.Bot.Builder.Scorables.Internals;

namespace Microsoft.Bot.Builder.Scorables
{
    /// <summary>
    /// This attribute is used to specify that a method will participate in the
    /// scoring process for overload resolution.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    [Serializable]
    public sealed class MethodBindAttribute : Attribute
    {
    }

    /// <summary>
    /// This attribute is used to specify that a method parameter is bound to an entity
    /// that can be resolved by an implementation of <see cref="IResolver"/>.
    /// </summary>
    [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
    [Serializable]
    public sealed class EntityAttribute : Attribute
    {
        /// <summary>
        /// The entity name.
        /// </summary>
        public readonly string Name;

        /// <summary>
        /// Construct the <see cref="EntityAttribute"/>.
        /// </summary>
        /// <param name="name">The entity name.</param>
        public EntityAttribute(string name)
        {
            SetField.NotNull(out this.Name, nameof(name), name);
        }
    }
}

namespace Microsoft.Bot.Builder.Scorables.Internals
{
    public sealed class MethodScorableFactory : IScorableFactory<IResolver, IBinding>
    {
        IScorable<IResolver, IBinding> IScorableFactory<IResolver, IBinding>.ScorableFor(IEnumerable<MethodInfo> methods)
        {
            var specs =
                from method in methods
                from bind in InheritedAttributes.For<MethodBindAttribute>(method)
                select new { method, bind };

            var scorables = from spec in specs
                            select new MethodScorable(spec.method);

            var all = scorables.ToArray().Fold(BindingComparer.Instance);
            return all;
        }
    }

    [Serializable]
    public abstract class MethodScorableBase : ScorableBase<IResolver, IBinding, IBinding>
    {
        public abstract MethodBase Method { get; }

        public override string ToString()
        {
            return $"{this.GetType().Name}({this.Method.Name})";
        }

        protected override bool HasScore(IResolver resolver, IBinding state)
        {
            return state != null;
        }

        protected override IBinding GetScore(IResolver resolver, IBinding state)
        {
            return state;
        }

        protected override Task PostAsync(IResolver item, IBinding state, CancellationToken token)
        {
            try
            {
                return state.InvokeAsync(token);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

        protected override Task DoneAsync(IResolver item, IBinding state, CancellationToken token)
        {
            return Task.CompletedTask;
        }
    }

    /// <summary>
    /// Scorable to represent binding arguments to a method's parameters.
    /// </summary>
    [Serializable]
    public sealed class MethodScorable : MethodScorableBase
    {
        private readonly MethodBase method;
        public MethodScorable(MethodInfo method)
        {
            SetField.NotNull(out this.method, nameof(method), method);
        }

        public override MethodBase Method => this.method;

        protected override Task<IBinding> PrepareAsync(IResolver item, CancellationToken token)
        {
            try
            {
                IBinding binding;
                if (Binder.Instance.TryBind(this.method, item, out binding))
                {
                    return Task.FromResult(binding);
                }
                else
                {
                    return Tasks<IBinding>.Null;
                }
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled<IBinding>(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException<IBinding>(error);
            }
        }
    }

    [Serializable]
    public sealed class DelegateScorable : MethodScorableBase
    {
        private readonly Delegate lambda;
        public DelegateScorable(Delegate lambda)
        {
            SetField.NotNull(out this.lambda, nameof(lambda), lambda);
        }

        public override MethodBase Method => this.lambda.Method;

        protected override Task<IBinding> PrepareAsync(IResolver item, CancellationToken token)
        {
            try
            {
                IBinding binding;
                if (Binder.Instance.TryBind(this.lambda, item, out binding))
                {
                    return Task.FromResult(binding);
                }
                else
                {
                    return Tasks<IBinding>.Null;
                }
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled<IBinding>(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException<IBinding>(error);
            }
        }
    }
}


text:
var Board = require('../../lib/board');

describe("Board", function() {
  var board;
  beforeEach(function(){
    board = new Board();
  });

  describe("initialization" , function() {
    it("has a blank 3x3 grid", function() {
      expect(board.grid[0][0].state).toBe("none");
      expect(board.grid[2][2].state).toBe("none");
      expect(board.grid[3]).toBe(undefined);
    });
  });

  describe("place3SpotShip", function() {
    var result, x = 0, y = 0, orientation = 'horizontal';

    beforeEach(function(){
      result = board.place3SpotShip(x, y, orientation);
    });

    it("is chainable (e.g. returns the board)", function () {
      expect(result).toBe(board);
    });

    it("marks the grid", function() {
      expect(board.grid[0][0].ship).toBe("ship");
      expect(board.grid[1][0].ship).toBe("ship");
      expect(board.grid[2][0].ship).toBe("ship");
    });

    // TODO: No placement off the board
  });

  describe("shoot", function() {
    beforeEach(function() {
      board.place3SpotShip(0,0, 'horizontal');
    });

    it("returns the result of a fire", function() {
      expect(board.shoot(0,0)).toBe("hit");
      expect(board.shoot(2,2)).toBe("miss");
    });

    it("mutates the state of the board on hits", function() {
      expect(board.grid[0][0].state).toBe("none");
      board.shoot(0,0);
      expect(board.grid[0][0].state).toBe("hit");
    });

    it("mutates the state of the board on misses", function() {
      expect(board.grid[2][2].state).toBe("none");
      board.shoot(2,2);
      expect(board.grid[2][2].state).toBe("miss");
    });
  });

  describe("shipIsSunk", function() {
    beforeEach(function() {
      board.place3SpotShip(0,0, 'horizontal');
    });

    it("is sunk with three hits", function() {
      expect(board.shipIsSunk()).toBe.false;
      board.shoot(0,0);
      expect(board.shipIsSunk()).toBe.false;
      board.shoot(0,1);
      expect(board.shipIsSunk()).toBe.false;
      board.shoot(0,2);
      expect(board.shipIsSunk()).toBe.true;
    });
  });
});


text:
package _06Animals;

public class Kitten extends Animal {

    public Kitten(String name, String age, String gender) {
        super(name, age, gender);
    }

    @Override
    protected void setGender(String gender) {
        if(!gender.equals("Female")){
            throw new IllegalArgumentException("Invalid input.");
        }
        super.setGender(gender);
    }

    @Override
    protected String produceSound() {
        return "Miau";
    }
}


text:
package ws.wamp.jawampa.roles;

import rx.subjects.AsyncSubject;
import ws.wamp.jawampa.ids.RequestId;
import ws.wamp.jawampa.io.BaseClient;
import ws.wamp.jawampa.messages.ErrorMessage;
import ws.wamp.jawampa.messages.PublishMessage;
import ws.wamp.jawampa.messages.PublishedMessage;
import ws.wamp.jawampa.messages.WampMessage;
import ws.wamp.jawampa.messages.handling.BaseMessageHandler;
import ws.wamp.jawampa.roles.RequestTracker.MessageFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class Publisher extends BaseMessageHandler {
    private final ObjectMapper mapper;
    private final RequestTracker<Void> requestTracker;

    public Publisher( BaseClient baseClient, ObjectMapper mapper ) {
        this.mapper = mapper;
        this.requestTracker = new RequestTracker<Void>( baseClient );
    }

    public void publish( final String topic, final ArrayNode arguments, final ObjectNode argumentsKw, AsyncSubject<Void> resultSubject ) {
        requestTracker.sendRequest( resultSubject, new MessageFactory() {
            @Override
            public WampMessage fromRequestId( RequestId requestId ) {
                return new PublishMessage( requestId,
                                           mapper.createObjectNode().put( "acknowledge", true ),
                                           topic,
                                           arguments,
                                           argumentsKw );
            }
        });
    }

    @Override
    public void onPublished( PublishedMessage msg ) {
        requestTracker.onSuccess( msg.requestId, null );
    }

    @Override
    public void onPublishError( ErrorMessage msg ) {
        requestTracker.onError( msg );
    }
}


text:
import WALLET_TYPES from '@/modules/access-wallet/common/walletTypes';
import ledgerPaths from './ledgerPaths';
import trezorPaths from './trezorPaths';
import bitbox02Paths from './bitbox02Paths';
import keepkeyPaths from './keepkeyPaths';
import mnemonicPaths from './mnemonicPaths';
import coolWalletPaths from './coolWalletPaths';

export default {
  [WALLET_TYPES.LEDGER]: ledgerPaths,
  [WALLET_TYPES.TREZOR]: trezorPaths,
  [WALLET_TYPES.BITBOX2]: bitbox02Paths,
  [WALLET_TYPES.KEEPKEY]: keepkeyPaths,
  [WALLET_TYPES.MNEMONIC]: mnemonicPaths,
  [WALLET_TYPES.COOL_WALLET]: coolWalletPaths
};


text:
var searchData=
[
  ['allowsceneobjects',['AllowSceneObjects',['../class_u_forms_1_1_controls_1_1_fields_1_1_object_field.html#abffc258f049df4c55e3de0b52fcb6630',1,'UForms::Controls::Fields::ObjectField']]],
  ['allowshrinkhorizontal',['AllowShrinkHorizontal',['../class_u_forms_1_1_decorators_1_1_fit_content.html#a132d27ba8ce8805b4ad873d9b938b9e8',1,'UForms::Decorators::FitContent']]],
  ['allowshrinkvertical',['AllowShrinkVertical',['../class_u_forms_1_1_decorators_1_1_fit_content.html#a9cd0487944ca95b89a5918ff06f54029',1,'UForms::Decorators::FitContent']]]
];


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Rhus thyrsiflora Balf. f.

### Remarks
null


text:
action_activate = function (action) {
    if (action.set) action.stage = sets.findOne(action.set).stage;
    else if (action.schedule) action.stage = schedules.findOne(action.schedule).stage;

    if (action.type == 'media' || action.type == 'playlist' ||
        action.type == 'clear-layer' || action.type == 'timer' ||
        action.type == 'song' || action.type == 'presentation' ||
        action.type == 'presentationslide' || action.type == 'camera') {

        var l = {}; l['layers.' + action.layer] = action;
        stages.update(action.stage, {$set: l});
    }

    else if (action.type == 'light') {
        var settings = {
            time: action.time,
            fade: parseFloat(combineSettings(action.settings).lights_fade)
        };

        Meteor.call('lightValues', action.light, action.settings.values, settings);
    }

    else if (action.type == 'lightgroup') {
        var settings = {
            time: action.time,
            fade: parseFloat(combineSettings(action.settings).lights_fade)
        };

        Meteor.call('lightGroupValues', action.lightgroup, action.settings.values, settings);
    }

    else if (action.type == 'lightscene') {
        Meteor.call('sceneActionActivate', action);
    }

    else if (action.type == 'sequence') {
        Meteor.call('sequenceActionActivate', action);
    }

    else if (action.type == 'clear-channel') {
        Meteor.call('sequenceClearChannel', action.settings.sequence_channel);
    }

    else if (action.type == 'custom') {
        Meteor.call('customActionTriggered', action.settings.action_string || '');
    }
};


text:
from __future__ import annotations

import json
import logging
from threading import Lock
from typing import Any, Callable, Optional

from boto3.session import Session
from botocore.client import BaseClient
from botocore.exceptions import ClientError

from securicad.aws_collector import region_collector, utils
from securicad.aws_collector.exceptions import AwsRegionError

log = logging.getLogger("securicad-aws-collector")

def get_account_data(
    credentials: dict[str, str], threads: Optional[int]
) -> Optional[dict[str, Any]]:
    session = Session(**credentials)  # type: ignore

    client_lock: Lock = Lock()
    client_cache: dict[str, BaseClient] = {}
    unpaginated = utils.get_unpaginated(session, client_lock, client_cache)
    paginate = utils.get_paginate(session, client_lock, client_cache)

    tasks: list[Callable[[], tuple[list[str], Any]]] = []

    def sts_get_caller_identity() -> tuple[list[str], Any]:
        log.debug("Executing sts get-caller-identity")
        return ["account_id"], unpaginated("sts", "get_caller_identity")["Account"]

    tasks.append(sts_get_caller_identity)

    def iam_list_account_aliases() -> tuple[list[str], Any]:
        log.debug("Executing iam list-account-aliases")
        return ["account_aliases"], paginate(
            "iam", "list_account_aliases", key="AccountAliases"
        )

    tasks.append(iam_list_account_aliases)

    return utils.execute_tasks(tasks, threads)

def collect(
    credentials: dict[str, str],
    regions: list[str],
    account_data: dict[str, Any],
    include_inspector: bool,
    include_guardduty: bool,
    threads: Optional[int],
) -> None:
    session = Session(**credentials)  # type: ignore

    account_data["global"] = get_global_data(session, threads)
    account_data["regions"] = []
    region_names = set()
    for region in regions:
        if not utils.is_valid_region(session, region):
            log.warning(f'"{region}" is not a valid AWS Region')
            continue
        if region in region_names:
            log.warning(f'Duplicate AWS Region "{region}"')
            continue
        log.info(f'Collecting AWS environment information of region "{region}"')
        region_data = {"region_name": region}
        region_collector.collect(
            credentials, region_data, include_inspector, include_guardduty, threads
        )
        account_data["regions"].append(region_data)
        region_names.add(region)
    account_data["global"].update(
        region_collector.collect_cloudfront_waf(credentials, threads)
    )
    if not account_data["regions"]:
        raise AwsRegionError("No valid AWS Region found")

def get_global_data(session: Session, threads: Optional[int]) -> dict[str, Any]:
    client_lock: Lock = Lock()
    client_cache: dict[str, BaseClient] = {}
    unpaginated = utils.get_unpaginated(session, client_lock, client_cache)
    paginate = utils.get_paginate(session, client_lock, client_cache)

    tasks: list[Callable[[], tuple[list[str], Any]]] = []

    def iam_list_users() -> tuple[list[str], Any]:
        log.debug(
            "Executing iam list-virtual-mfa-devices, list-users, list-access-keys, list-attached-user-policies, list-user-policies, get-user-policy, list-groups-for-user, list-mfa-devices, get-login-profile, list-user-tags"
        )

        def get_virtual_mfa_devices() -> list[dict[str, Any]]:
            return paginate("iam", "list_virtual_mfa_devices", key="VirtualMFADevices")

        def get_user_virtual_mfa_devices() -> dict[str, list[dict[str, Any]]]:
            virtual_mfa_devices = get_virtual_mfa_devices()
            user_virtual_mfa_devices: dict[str, list[dict[str, Any]]] = {}
            for virtual_mfa_device in virtual_mfa_devices:
                if (
                    "User" not in virtual_mfa_device
                    or "UserName" not in virtual_mfa_device["User"]
                ):
                    continue
                user_name = virtual_mfa_device["User"]["UserName"]
                if user_name not in user_virtual_mfa_devices:
                    user_virtual_mfa_devices[user_name] = []
                user_virtual_mfa_devices[user_name].append(virtual_mfa_device)
            return user_virtual_mfa_devices

        def get_access_keys(user_name: str) -> list[dict[str, Any]]:
            return paginate(
                "iam",
                "list_access_keys",
                key="AccessKeyMetadata",
                param={"UserName": user_name},
            )

        def get_attached_policies(user_name: str) -> list[dict[str, Any]]:
            return paginate(
                "iam",
                "list_attached_user_policies",
                key="AttachedPolicies",
                param={"UserName": user_name},
            )

        def get_user_policy(user_name: str, policy_name: str) -> dict[str, Any]:
            return unpaginated(
                "iam",
                "get_user_policy",
                param={"UserName": user_name, "PolicyName": policy_name},
            )

        def list_user_tags(user_name: str) -> list[dict[str, Any]]:
            return paginate(
                "iam",
                "list_user_tags",
                key="Tags",
                param={"UserName": user_name},
            )

        def get_user_policies(user_name: str) -> list[dict[str, Any]]:
            policy_names = paginate(
                "iam",
                "list_user_policies",
                key="PolicyNames",
                param={"UserName": user_name},
            )
            return [
                get_user_policy(user_name, policy_name) for policy_name in policy_names
            ]

        def get_groups(user_name: str) -> list[dict[str, Any]]:
            return paginate(
                "iam",
                "list_groups_for_user",
                key="Groups",
                param={"UserName": user_name},
            )

        def get_mfa_devices(user_name: str) -> list[dict[str, Any]]:
            return paginate(
                "iam",
                "list_mfa_devices",
                key="MFADevices",
                param={"UserName": user_name},
            )

        def get_login_profile(user_name: str) -> Optional[dict[str, Any]]:
            try:
                # TODO: Don't wrap result in dict
                return {
                    "LoginProfile": unpaginated(
                        "iam", "get_login_profile", param={"UserName": user_name}
                    )["LoginProfile"]
                }
            except ClientError as e:
                if e.response.get("Error", {}).get("Code") == "NoSuchEntity":
                    return None
                raise

        user_virtual_mfa_devices = get_user_virtual_mfa_devices()
        users = paginate("iam", "list_users", key="Users")
        for user in users:
            user_name = user["UserName"]
            user["AccessKeyMetadata"] = get_access_keys(user_name)
            user["AttachedPolicies"] = get_attached_policies(user_name)
            user["UserPolicies"] = get_user_policies(user_name)
            user["Groups"] = get_groups(user_name)
            user["MFADevices"] = get_mfa_devices(user_name)
            user["Tags"] = list_user_tags(user_name)
            if user_name in user_virtual_mfa_devices:
                user["VirtualMFADevices"] = user_virtual_mfa_devices[user_name]
            # TODO: Use key "LoginProfile"
            user["HasLoginProfile"] = get_login_profile(user_name)
        return ["iam", "Users"], users

    tasks.append(iam_list_users)

    def iam_list_roles() -> tuple[list[str], Any]:
        log.debug(
            "Executing iam list-roles, list-attached-role-policies, list-role-policies, get-role-policy, list-role-tags"
        )

        def get_attached_policies(role_name: str) -> list[dict[str, Any]]:
            return paginate(
                "iam",
                "list_attached_role_policies",
                key="AttachedPolicies",
                param={"RoleName": role_name},
            )

        def get_role_policy(role_name: str, policy_name: str) -> dict[str, Any]:
            return unpaginated(
                "iam",
                "get_role_policy",
                param={"RoleName": role_name, "PolicyName": policy_name},
            )

        def list_role_tags(role_name: str) -> list[dict[str, Any]]:
            return unpaginated(
                "iam",
                "list_role_tags",
                param={"RoleName": role_name},
            )["Tags"]

        def get_role_policies(role_name: str) -> list[dict[str, Any]]:
            policy_names = paginate(
                "iam",
                "list_role_policies",
                key="PolicyNames",
                param={"RoleName": role_name},
            )
            return [
                get_role_policy(role_name, policy_name) for policy_name in policy_names
            ]

        roles = paginate("iam", "list_roles", key="Roles")
        for role in roles:
            role_name = role["RoleName"]
            role["AttachedPolicies"] = get_attached_policies(role_name)
            role["RolePolicies"] = get_role_policies(role_name)
            role["Tags"] = list_role_tags(role_name)
        return ["iam", "Roles"], roles

    tasks.append(iam_list_roles)

    def iam_list_groups() -> tuple[list[str], Any]:
        log.debug(
            "Executing iam list-groups, list-attached-group-policies, list-group-policies, get-group-policy"
        )

        def get_attached_policies(group_name: str) -> list[dict[str, Any]]:
            return paginate(
                "iam",
                "list_attached_group_policies",
                key="AttachedPolicies",
                param={"GroupName": group_name},
            )

        def get_group_policy(group_name: str, policy_name: str) -> dict[str, Any]:
            return unpaginated(
                "iam",
                "get_group_policy",
                param={"GroupName": group_name, "PolicyName": policy_name},
            )

        def get_group_policies(group_name: str) -> list[dict[str, Any]]:
            policy_names = paginate(
                "iam",
                "list_group_policies",
                key="PolicyNames",
                param={"GroupName": group_name},
            )
            return [
                get_group_policy(group_name, policy_name)
                for policy_name in policy_names
            ]

        groups = paginate("iam", "list_groups", key="Groups")
        for group in groups:
            group_name = group["GroupName"]
            group["AttachedPolicies"] = get_attached_policies(group_name)
            group["GroupPolicies"] = get_group_policies(group_name)
        return ["iam", "Groups"], groups

    tasks.append(iam_list_groups)

    def iam_list_policies() -> tuple[list[str], Any]:
        log.debug("Executing iam list-policies, get-policy-version")

        def get_policy_version(policy_arn: str, version_id: str) -> dict[str, Any]:
            return unpaginated(
                "iam",
                "get_policy_version",
                param={"PolicyArn": policy_arn, "VersionId": version_id},
            )["PolicyVersion"]

        # TODO: Remove OnlyAttached to get all policies?
        policies = paginate(
            "iam", "list_policies", key="Policies", param={"OnlyAttached": True}
        )
        for policy in policies:
            policy_arn = policy["Arn"]
            # TODO: Use list_policy_versions instead to get all policy versions?
            version_id = policy["DefaultVersionId"]
            policy["Statement"] = get_policy_version(policy_arn, version_id)[
                "Document"
            ]["Statement"]
        return ["iam", "Policies"], policies

    tasks.append(iam_list_policies)

    def iam_list_instance_profiles() -> tuple[list[str], Any]:
        log.debug("Executing iam list-instance-profiles")

        return ["iam", "InstanceProfiles"], paginate(
            "iam", "list_instance_profiles", key="InstanceProfiles"
        )

    tasks.append(iam_list_instance_profiles)

    def iam_get_account_summary() -> tuple[list[str], Any]:
        log.debug("Executing iam get-account-summary")

        return ["iam", "SummaryMap"], unpaginated("iam", "get_account_summary")[
            "SummaryMap"
        ]

    tasks.append(iam_get_account_summary)

    def s3api_list_buckets() -> tuple[list[str], Any]:
        log.debug(
            "Executing s3api list-buckets, get-bucket-encryption, get-bucket-policy-status, get-bucket-policy, get-bucket-tagging"
        )

        def get_encryption(bucket_name: str) -> dict[str, Any]:
            return unpaginated(
                "s3", "get_bucket_encryption", param={"Bucket": bucket_name}
            )["ServerSideEncryptionConfiguration"]

        def get_policy_status(bucket_name: str) -> dict[str, Any]:
            return unpaginated(
                "s3", "get_bucket_policy_status", param={"Bucket": bucket_name}
            )["PolicyStatus"]

        def get_policy(bucket_name: str) -> dict[str, Any]:
            return json.loads(
                unpaginated("s3", "get_bucket_policy", param={"Bucket": bucket_name})[
                    "Policy"
                ]
            )

        def get_tagging(bucket_name: str) -> dict[str, Any]:
            return unpaginated(
                "s3", "get_bucket_tagging", param={"Bucket": bucket_name}
            )["TagSet"]

        def get_acl(bucket_name: str, policy) -> tuple[dict[str, Any], bool]:
            acl = unpaginated("s3", "get_bucket_acl", param={"Bucket": bucket_name})
            statements = []
            public = False
            for grant in acl.get("Grants", []):
                grantee = grant.get("Grantee", {})
                uri_grantee = grantee.get("URI")
                if uri_grantee in [
                    "http://acs.amazonaws.com/groups/global/AllUsers",
                    "http://acs.amazonaws.com/groups/global/AuthenticatedUsers",
                ]:
                    permission = grant.get("Permission")
                    if permission == "FULL_CONTROL":
                        action = "s3:*"
                    elif permission == "READ":
                        action = ["s3:GetObject"]
                    elif permission == "WRITE":
                        action = ["s3:PutObject"]
                    else:
                        continue
                    public = True
                    statement = {
                        "Effect": "Allow",
                        "Principal": "*",
                        "Action": action,
                        "Resource": [
                            f"arn:aws:s3:::{bucket_name}",
                            f"arn:aws:s3:::{bucket_name}/*",
                        ],
                    }
                    statements.append(statement)

            if policy:
                statement = policy["Statement"]
                if isinstance(statement, list):
                    policy["Statement"].extend(statements)
                else:
                    statements.append(statement)
                    policy["Statement"] = statements
                return policy, public

            return {
                "Version": "2012-10-17",
                "Statement": statements,
            }, public

        buckets = unpaginated("s3", "list_buckets")["Buckets"]
        for bucket in buckets:
            bucket_name = bucket["Name"]
            try:
                # TODO: Use key "ServerSideEncryptionConfiguration"
                bucket["Encryption"] = get_encryption(bucket_name)
            except ClientError as e:
                if e.response.get("Error", {}).get("Code") not in {
                    "NoSuchBucket",
                    "ServerSideEncryptionConfigurationNotFoundError",
                }:
                    raise
            try:
                # TODO: Use key "PolicyStatus" and don't use "IsPublic"
                bucket["Public"] = get_policy_status(bucket_name)["IsPublic"]
            except ClientError as e:
                if e.response.get("Error", {}).get("Code") != "NoSuchBucketPolicy":
                    raise
                bucket["Public"] = False
            try:
                bucket["Policy"] = get_policy(bucket_name)
            except ClientError as e:
                if e.response.get("Error", {}).get("Code") != "NoSuchBucketPolicy":
                    raise
            try:
                policy, public = get_acl(bucket_name, bucket.get("Policy"))
                bucket["Policy"] = policy
                bucket["Public"] = bucket["Public"] or public
            except ClientError as e:
                pass
            try:
                # TODO: Use key "TagSet"
                bucket["Tags"] = get_tagging(bucket_name)
            except ClientError as e:
                if e.response.get("Error", {}).get("Code") != "NoSuchTagSet":
                    raise
        # TODO: Change to ["s3", "Buckets"]
        return ["s3buckets"], buckets

    tasks.append(s3api_list_buckets)

    def cloudfront_list_distributions() -> tuple[list[str], Any]:
        log.debug("Executing cloudfront list-distributions")
        distributions = paginate(
            "cloudfront",
            "list_distributions",
            key=["DistributionList", "Items"],
        )
        return ["cloudfront", "DistributionList"], distributions

    tasks.append(cloudfront_list_distributions)

    global_data = utils.execute_tasks(tasks, threads)
    if global_data is None:
        raise RuntimeError("utils.execute_tasks returned None")
    return global_data


text:
<?php

namespace App\Listeners;

use App\Events\ModelUpdatedEvent;
use App\Models\SysLog;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class ModelUpdatedHandler //implements ShouldQueue
{
    //use InteractsWithQueue;
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  ModelUpdatedEvent  $event
     * @return void
     */
    public function handle(ModelUpdatedEvent $event)
    {
        SysLog::create([
            'module' => $event->model->getTable().'模型',
            'action' => '修改',
            'content' => json_encode($event->model->toArray()),
            'status' => 1
        ]);
    }
}


text:
import warnings
warnings.warn('cherrypy.lib.http has been deprecated and will be removed '
              'in CherryPy 3.3 use cherrypy.lib.httputil instead.',
              DeprecationWarning)

from cherrypy.lib.httputil import *


text:
{% extends 'layouts/page.html' %}

{% block content %}
	{% include 'objects/hero.html' %}
	{% include 'objects/banner-text-right.html' %}
	{% include 'objects/banner-text-left.html' %}
	{% include 'objects/banner-text-center.html' %}

{% endblock %}

{% block javascript %}

{% endblock %}