text:
/*
 * This file is here to test things that glamor does when
 * NODE_ENV === 'development'
 *
 * Because glamor stores the value in the module level of
 * it's implementation files, we have to do some funny things
 * to make sure that glamor gets the value we want.
 */
import React from 'react'
import {render} from 'enzyme'

const nodeEnv = process.env.NODE_ENV

jest.mock('../constants')

beforeEach(() => {
  process.env.NODE_ENV = 'development'
  jest.resetModules()
})

afterEach(() => {
  process.env.NODE_ENV = nodeEnv
})

test('can be configured to use the displayName in the className', () => {
  // eslint-disable-next-line
  const glamorous = require('../').default
  const MyComp = glamorous(props => <div {...props} />, {
    displayName: 'Hi There',
  })({color: 'red'})
  const wrapper = render(<MyComp />)
  expect(wrapper).toMatchSnapshot()
  expect(wrapper[0].attribs.class).toMatch(/hi-there/)
})

redpajama_set_name: RedPajamaGithub


text:
require 'sensu-plugin/check/cli'
require 'carrot-top'
require 'inifile'

# main plugin class
class CheckRabbitMQPartitions < Sensu::Plugin::Check::CLI
  option :host,
         description: 'RabbitMQ management API host',
         short: '-w',
         long: '--host HOST',
         default: 'localhost'

  option :port,
         description: 'RabbitMQ management API port',
         long: '--port PORT',
         proc: proc(&:to_i),
         default: 15_672

  option :username,
         description: 'RabbitMQ management API user',
         short: '-u',
         long: '--username USERNAME',
         default: 'guest'

  option :password,
         description: 'RabbitMQ management API password',
         short: '-p',
         long: '--password PASSWORD',
         default: 'guest'

  option :ssl,
         description: 'Enable SSL for connection to the API',
         long: '--ssl',
         boolean: true,
         default: false

  option :ini,
         description: 'Configuration ini file',
         short: '-i',
         long: '--ini VALUE'

  def run
    critical 'network partition detected' if partition?
    ok 'no network partition detected'
  rescue Errno::ECONNREFUSED => e
    critical e.message
  rescue StandardError => e
    unknown e.message
  end

  def partition?
    rabbitmq_management.nodes.map { |node| node['partitions'] }.any?(&:any?)
  end

  def rabbitmq_management
    if config[:ini]
      ini = IniFile.load(config[:ini])
      section = ini['auth']
      username = section['username']
      password = section['password']
    else
      username = config[:username]
      password = config[:password]
    end

    CarrotTop.new(
      host: config[:host],
      port: config[:port],
      user: username,
      password: password,
      ssl: config[:ssl]
    )
  end
end


text:
package com.cerner.beadledom.stagemonitor.request

import com.cerner.beadledom.stagemonitor.JsonRequestTraceLoggerPlugin
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.ObjectMapper
import org.mockito.ArgumentCaptor
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.{never, verify, when}
import org.scalatest._
import org.scalatest.mockito.MockitoSugar
import org.slf4j.Logger
import org.stagemonitor.requestmonitor.reporter.RequestTraceReporter.{IsActiveArguments, ReportArguments}
import org.stagemonitor.requestmonitor.{RequestMonitorPlugin, RequestTrace}

/**
 * Spec tests for [[LogJsonRequestTraceReporter]].
 *
 * @author John Leacox
 */
class LogJsonRequestTraceReporterSpec extends FunSpec with MustMatchers with MockitoSugar {
  describe("LogJsonRequestTraceReporter") {
    val jsonRequestLoggerPlugin = mock[JsonRequestTraceLoggerPlugin]
    when(jsonRequestLoggerPlugin.getMinJsonExecutionTimeMillis).thenReturn(1000L)

    describe("#reportRequestTrace") {
      val requestMonitorPlugin = mock[RequestMonitorPlugin]

      it("does not log if info logging is disabled") {
        val logger = mock[Logger]
        when(logger.isInfoEnabled).thenReturn(false)

        val errorLogger = mock[Logger]

        val reporter = new LogJsonRequestTraceReporter(logger, errorLogger, new ObjectMapper(),
          requestMonitorPlugin, jsonRequestLoggerPlugin)

        val trace = mock[RequestTrace]
        when(trace.getExecutionTime).thenReturn(2000)

        val args = new ReportArguments(trace)

        reporter.reportRequestTrace(args)

        verify(logger, never()).info(any())
      }

      it("does not log if the execution time is faster than the specified minimum") {
        val logger = mock[Logger]
        val errorLogger = mock[Logger]

        when(logger.isInfoEnabled).thenReturn(true)
        val reporter = new LogJsonRequestTraceReporter(logger, errorLogger, new ObjectMapper(),
          requestMonitorPlugin, jsonRequestLoggerPlugin)

        val trace = mock[RequestTrace]
        when(trace.getExecutionTime).thenReturn(500)

        val args = new ReportArguments(trace)

        reporter.reportRequestTrace(args)

        verify(logger, never()).info(any())
      }

      it("logs the request trace as info") {
        val logger = mock[Logger]
        when(logger.isInfoEnabled).thenReturn(true)

        val errorLogger = mock[Logger]

        val reporter = new LogJsonRequestTraceReporter(logger, errorLogger, new ObjectMapper(),
          requestMonitorPlugin, jsonRequestLoggerPlugin)

        val trace = mock[RequestTrace]
        when(trace.getExecutionTime).thenReturn(2000)

        val args = new ReportArguments(trace)

        reporter.reportRequestTrace(args)

        verify(logger).info(any())
      }

      it("logs the JsonProcessingException if the request trace if conversion to JSON fails") {
        val logger = mock[Logger]
        when(logger.isInfoEnabled).thenReturn(true)

        val errorLogger = mock[Logger]

        val trace = mock[RequestTrace]
        when(trace.getExecutionTime).thenReturn(2000)

        val objectMapper = mock[ObjectMapper]

        val exception = mock[JsonProcessingException]
        when(objectMapper.writeValueAsString(any[RequestTraceWrapper])).thenThrow(exception)

        val reporter = new LogJsonRequestTraceReporter(logger, errorLogger, objectMapper,
          requestMonitorPlugin, jsonRequestLoggerPlugin)

        val args = new ReportArguments(trace)

        reporter.reportRequestTrace(args)

        val exceptionArgCaptor = ArgumentCaptor.forClass(classOf[Object])
        val traceArgCaptor = ArgumentCaptor.forClass(classOf[Object])

        // Must use asInstanceOf[Any] to workaround ambiguous method declaration with Java interop
        verify(errorLogger)
            .error(any(),
              exceptionArgCaptor.capture().asInstanceOf[Any],
              traceArgCaptor.capture().asInstanceOf[Any])
        exceptionArgCaptor.getValue mustBe exception
        traceArgCaptor.getValue mustBe trace
      }
    }

    describe("#isActive") {
      it("is false if requestMonitorPlugin is not logging call stacks") {
        val logger = mock[Logger]
        when(logger.isInfoEnabled).thenReturn(true)

        val errorLogger = mock[Logger]

        val requestMonitorPlugin = mock[RequestMonitorPlugin]
        when(requestMonitorPlugin.isLogCallStacks).thenReturn(false)

        val reporter = new LogJsonRequestTraceReporter(logger, errorLogger, new ObjectMapper(),
          requestMonitorPlugin, jsonRequestLoggerPlugin)

        val trace = mock[RequestTrace]

        val args = new IsActiveArguments(trace)

        reporter.isActive(args) must be(false)
      }

      it("is true if requestMonitorPlugin is logging call stacks") {
        val logger = mock[Logger]
        when(logger.isInfoEnabled).thenReturn(true)

        val errorLogger = mock[Logger]

        val requestMonitorPlugin = mock[RequestMonitorPlugin]
        when(requestMonitorPlugin.isLogCallStacks).thenReturn(true)

        val reporter = new LogJsonRequestTraceReporter(logger, errorLogger, new ObjectMapper(),
          requestMonitorPlugin, jsonRequestLoggerPlugin)

        val trace = mock[RequestTrace]

        val args = new IsActiveArguments(trace)

        reporter.isActive(args) must be(true)
      }
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
  <head>
    <title>Documentation for jjtraveler.graph</title>
  </head>
  <body bgcolor="white">

Provides classes and interfaces for visiting graph structures.

</body>
</html>


text:
package com.katsuraf.demoarchitecture.db.cache;

import android.content.Context;

import com.katsuraf.demoarchitecture.db.DBHelper;
import com.katsuraf.demoarchitecture.db.bean.ListItemEntity;
import com.katsuraf.demoarchitecture.db.bean.PageStateEntity;
import com.katsuraf.demoarchitecture.net.exception.ResultException;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;

/**
 * {@link ListCache} implementation.
 */
public class ListCacheImpl implements ListCache {
    private static final long EXPIRATION_TIME = 60 * 1000;

    private final DBHelper dbHelper;

    /**
     * Constructor of the class {@link ListCacheImpl}.
     *
     * @param context  A
     */
    public ListCacheImpl(Context context) {
        if (context == null) {
            throw new IllegalArgumentException("Invalid null parameter");
        }
        this.dbHelper = new DBHelper(context);
    }

    @Override
    public Observable<List<ListItemEntity>> getListData(int listType) {
        return Observable.create(subscriber -> {
            List<ListItemEntity> listItemEntityList = dbHelper.queryListData(listType);
            if (listItemEntityList != null && listItemEntityList.size() > 0) {
                subscriber.onNext(listItemEntityList);
                subscriber.onComplete();
            } else {
                subscriber.onError(
                        new ResultException(ResultException.NO_DATA, ResultException.MSG_NO_DATA_FOUND));
            }
        });
    }

    @Override
    public void putListData(List<ListItemEntity> listItems, int listType) {
        this.executeAsynchronously(new CacheWriter(dbHelper, listItems));
    }

    @Override
    public void putPageState(int listType, Integer page, Long timestamp) {
        dbHelper.addPageState(listType, page, timestamp);
    }

    @Override
    public PageStateEntity getPageState(int listType) {
        return dbHelper.queryPageState(listType);
    }

    @Override
    public boolean isExpired(int listType) {
        PageStateEntity pageState = getPageState(listType);
        Long currentTime = System.currentTimeMillis();
        return (pageState == null
                || pageState.getTimestamp() == null
                || currentTime - pageState.getTimestamp() * 1000 > EXPIRATION_TIME);
    }

    @Override
    public boolean hasCache(int listType) {
        return dbHelper.hasListData(listType);
    }

    @Override
    public void clearList(int listType) {
        this.executeAsynchronously(new CacheCleaner(this.dbHelper, listType));
    }

    /**
     * Executes a {@link Runnable} in another Thread.
     *
     * @param runnable {@link Runnable} to execute
     */
    private void executeAsynchronously(Runnable runnable) {
        Observable.just(runnable).subscribeOn(Schedulers.io());
    }

    /**
     * {@link Runnable} class for writing to disk.
     */
    private static class CacheWriter implements Runnable {
        private final DBHelper dbHelper;
        private final List<ListItemEntity> listItems;

        CacheWriter(DBHelper dbHelper, List<ListItemEntity> listItems) {
            this.dbHelper = dbHelper;
            this.listItems = listItems;
        }

        @Override
        public void run() {
            this.dbHelper.insertListBeans(listItems);
        }
    }

    /**
     * {@link Runnable} class for evicting all the cached files
     */
    private static class CacheCleaner implements Runnable {
        private final DBHelper dbHelper;
        private final int listType;

        CacheCleaner(DBHelper dbHelper, int listType) {
            this.dbHelper = dbHelper;
            this.listType = listType;
        }

        @Override
        public void run() {
            this.dbHelper.deleteListData(this.listType);
        }
    }
}


text:
tinymce.addI18n('uz',{
"Redo": "Bekor qilish",
"Undo": "Orqaga qaytarish",
"Cut": "Kesib olish",
"Copy": "Nusxa olish",
"Paste": "Qo\u2018yish",
"Select all": "Barchasini belgilash",
"New document": "Yangi hujjat",
"Ok": "Bajarish",
"Cancel": "Bekor qilish",
"Visual aids": "Ko\u2018rgazmali o\u2018quv qurollar",
"Bold": "Yo'g'on",
"Italic": "Yotiq",
"Underline": "Tagi chizilgan",
"Strikethrough": "O'chirilgan yozuv",
"Superscript": "Yuqori yozuv",
"Subscript": "Quyi yozuv",
"Clear formatting": "Formatlashni tozalash",
"Align left": "Chapga tekislash",
"Align center": "Markazga tekislash",
"Align right": "O'ngga tekislash",
"Justify": "Ikki tomondan tekislash",
"Bullet list": "Nuqtali ro\u2018yxat",
"Numbered list": "Raqamli ro\u2018yxat",
"Decrease indent": "Satr boshini kamaytirish",
"Increase indent": "Satr boshini oshirish",
"Close": "Yopish",
"Formats": "Formatlar",
"Your browser doesn't support direct access to the clipboard. Please use the Ctrl+X\/C\/V keyboard shortcuts instead.": "Sizning brauzeringiz buferga to\u2018g\u2018ridan-to\u2018g\u2018ri kirish qo\u2018llab-quvvatlamaydi. O\u2018rniga klaviaturaning Ctrl+X\/C\/V qisqartirishlarni foydalaning.",
"Headers": "Sarlavhalar",
"Header 1": "Sarlavha 1",
"Header 2": "Sarlavha 2",
"Header 3": "Sarlavha 3",
"Header 4": "Sarlavha 4",
"Header 5": "Sarlavha 5",
"Header 6": "Sarlavha 6",
"Headings": "Sarlavhalar",
"Heading 1": "Sarlavha 1",
"Heading 2": "Sarlavha 2",
"Heading 3": "Sarlavha 3",
"Heading 4": "Sarlavha 4",
"Heading 5": "Sarlavha 5",
"Heading 6": "Sarlavha 6",
"Div": "Div",
"Pre": "Pre",
"Code": "Kod",
"Paragraph": "Paragraf",
"Blockquote": "Matn blok parchasi",
"Inline": "Bir qator ketma-ketlikda",
"Blocks": "Bloklar",
"Paste is now in plain text mode. Contents will now be pasted as plain text until you toggle this option off.": "Qo'shish oddiy matn rejimida amalga oshiriladi. Ushbu hususiyatni o'chirmaguningizcha, kontent oddiy matn sifatida qo'shiladi.",
"Font Family": "Srift turi",
"Font Sizes": "Shrift kattaligi",
"Class": "Klass",
"Browse for an image": "Rasmni yuklash",
"OR": "YOKI",
"Drop an image here": "Bu erga rasmni olib o'ting",
"Upload": "Yuklash",
"Default": "Standart",
"Circle": "Doira",
"Disc": "Disk",
"Square": "Kvadrat",
"Lower Alpha": "Kichik lotincha",
"Lower Greek": "Pastki yunon",
"Lower Roman": "Kichik kirilcha",
"Upper Alpha": "Katta lotincha",
"Upper Roman": "Katta kirilcha",
"Anchor": "Langar",
"Name": "Nomi",
"Id": "Id",
"Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.": "Id faqat harf bilan boshlanishi lozim, o'z ichiga faqat harflar, sonlar, tire, nuqtalar, pastgi chiziqlardan iborat bo'lishi mumkin",
"You have unsaved changes are you sure you want to navigate away?": "Sizda saqlanmagan o'zgartirishlar bor. Boshqa yerga chiqib ketish uchun ishonchingiz komilmi?",
"Restore last draft": "Oxirgi ",
"Special character": "Maxsus belgilar",
"Source code": "Manba kodi",
"Insert\/Edit code sample": "Kod namunasini qo'shish \/ tahrirlash",
"Language": "Til",
"Color": "Rang",
"R": "R",
"G": "G",
"B": "B",
"Left to right": "Chapdan o'ngga",
"Right to left": "O'ngdan chapga",
"Emoticons": "Hissiyot ikonkalari",
"Document properties": "Hujjatning xususiyatlari",
"Title": "Nomi",
"Keywords": "Kalit so'zlar",
"Description": "Tavsif",
"Robots": "Robotlar",
"Author": "Muallif",
"Encoding": "Kodlash",
"Fullscreen": "Butun ekran rejimi",
"Action": "Harakat",
"Shortcut": "Yorliq",
"Help": "Yordam",
"Address": "Manzil",
"Focus to menubar": "Menubarga e'tibor qaratish",
"Focus to toolbar": "Vositalar paneliga e'tibor qaratish",
"Focus to element path": "Elementlar manziliga e'tibor qaratish",
"Focus to contextual toolbar": "Kontekstli vositalar paneliga e'tibor qaratish",
"Insert link (if link plugin activated)": "Havolani qo'shish (havola plagini o'rnatilgan bo'lsa)",
"Save (if save plugin activated)": "Saqlash (saqlash plagini o'rnatilgan bo'lsa)",
"Find (if searchreplace plugin activated)": "Qidirish (qidirish plagini o'rnatilgan bo'lsa)",
"Plugins installed ({0}):": "O'rnatilgan plaginlar ({0})",
"Premium plugins:": "Premium plaginlar:",
"Learn more...": "Batafsil ma'lumot...",
"You are using {0}": "Siz {0} ishlatmoqdasiz",
"Horizontal line": "Gorizontal chiziq",
"Insert\/edit image": "Rasmni qo'shish \/ tahrirlash",
"Image description": "Rasm tavsifi",
"Source": "Manba",
"Dimensions": "O'lchamlari",
"Constrain proportions": "Nisbatlarni cheklash",
"General": "Umumiy",
"Advanced": "Ilg'or",
"Style": "Uslub",
"Vertical space": "Vertikal o'lchov",
"Horizontal space": "Gorizontal o'lchov",
"Border": "Chegara",
"Insert image": "Rasm qo'shish",
"Image": "Rasm",
"Image list": "Rasmlar ro'yhati",
"Rotate counterclockwise": "Soatga qarshi yo'nalishda aylantirish",
"Rotate clockwise": "Soat yo'nalishda aylantirish",
"Flip vertically": "Vertikal o'girish",
"Flip horizontally": "Gorizontal o'girish",
"Edit image": "Rasmni tahrirlash",
"Image options": "Rasm imkoniyatlari",
"Zoom in": "Yaqinlashtirish",
"Zoom out": "Uzoqlashtirish",
"Crop": "Kesib olish",
"Resize": "O'lchamini o'zgartirish",
"Orientation": "Orientatsiya",
"Brightness": "Yorqinligi",
"Sharpen": "Keskinligi",
"Contrast": "Ravshanligi",
"Color levels": "Rang sathi",
"Gamma": "Gamma",
"Invert": "Ranglarni ag'darish",
"Apply": "Qo'llash",
"Back": "Ortga qaytish",
"Insert date\/time": "Kun \/ vaqtni qo'shish",
"Date\/time": "Kun\/vaqt",
"Insert link": "Havola qo'shish",
"Insert\/edit link": "Havola qo'shish \/ tahrirlash",
"Text to display": "Ko'rsatiladigan matn",
"Url": "URL",
"Target": "Nishon",
"None": "Hech bir",
"New window": "Yangi oyna",
"Remove link": "Havolani olib tashlash",
"Anchors": "Langarlar",
"Link": "Havola",
"Paste or type a link": "Havolani joylashtirish yoki kiritish",
"The URL you entered seems to be an email address. Do you want to add the required mailto: prefix?": "Siz kiritgan URL elektron pochta manziliga oxshayapti. \"mailto:\" prefiksi qo'shilsinmi?",
"The URL you entered seems to be an external link. Do you want to add the required http:\/\/ prefix?": "Siz kiritgan URL tashqi havolaga oxshayapti. \"http:\/\/\" prefiksi qo'shilsinmi?",
"Link list": "Havolalar ro'yhati",
"Insert video": "Video qo'shish",
"Insert\/edit video": "Videoni qo'shish \/ tahrirlash",
"Insert\/edit media": "Media qo'shish \/ tahrirlash",
"Alternative source": "Muqobil manba",
"Poster": "Poster",
"Paste your embed code below:": "Kodni quyiga joylashtiring:",
"Embed": "Ichiga olgan",
"Media": "Media",
"Nonbreaking space": "Buzilmas bo'sh joy",
"Page break": "Yangi bet",
"Paste as text": "Tekst qo'shish",
"Preview": "Tahrirni avvaldan ko'rish",
"Print": "Chop etish",
"Save": "Saqlash",
"Find": "Qidirish",
"Replace with": "bilan almashtirish",
"Replace": "Almashtirish",
"Replace all": "Barchasini almashtirish",
"Prev": "Avvalgisi",
"Next": "Keyingisi",
"Find and replace": "Topib almashtirish",
"Could not find the specified string.": "Belgilangan satr topilmadi.",
"Match case": "O'xshashliklar",
"Whole words": "Butun so'z",
"Spellcheck": "Imloni tekshirish",
"Ignore": "E'tiborsiz qoldirish",
"Ignore all": "Barchasini e'tiborsiz qoldirish",
"Finish": "Tugatish",
"Add to Dictionary": "Lug'atga qo'shish",
"Insert table": "Jadvalni qo'shish",
"Table properties": "Jadval xususiyatlari",
"Delete table": "Jadvalni o'chirib tashlash",
"Cell": "Katak",
"Row": "Satr",
"Column": "Ustun",
"Cell properties": "Katak hususiyatlari",
"Merge cells": "Kataklarni birlashtirish",
"Split cell": "Kataklarni bo'lish",
"Insert row before": "Yuqorisiga satr qo'shish",
"Insert row after": "Ketidan satr qo'shish",
"Delete row": "Satrni olib tashlash",
"Row properties": "Satr hususiyatlari",
"Cut row": "Satrni kesib olish",
"Copy row": "Satrdan nusxa ko'chirish",
"Paste row before": "Yuqorisiga satrni joylashtirish",
"Paste row after": "Ketidan satrni joylashtirish",
"Insert column before": "Ustunni oldi tomoniga qo'shish",
"Insert column after": "Ustunni ketidan qo'shish",
"Delete column": "Ustunni olib tashlash",
"Cols": "Ustunlar",
"Rows": "Satrlar",
"Width": "Kengligi",
"Height": "Balandligi",
"Cell spacing": "Kataklar orasi",
"Cell padding": "Kataklar chegarasidan bo'sh joy",
"Caption": "Taglavha",
"Left": "Chapga",
"Center": "Markazga",
"Right": "O'ngga",
"Cell type": "Katak turi",
"Scope": "Muhit",
"Alignment": "Tekislash",
"H Align": "Gorizontal tekislash",
"V Align": "Vertikal tekislash",
"Top": "Yuqoriga",
"Middle": "Markaziga",
"Bottom": "Tagiga",
"Header cell": "Sarlavha katagi",
"Row group": "Satrlar guruhi",
"Column group": "Ustunlar guruhi",
"Row type": "Satr turi",
"Header": "Sarlavha",
"Body": "Tanasi",
"Footer": "Tag qismi",
"Border color": "Chegara rangi",
"Insert template": "Andozani qo'shish",
"Templates": "Andozalar",
"Template": "Andoza",
"Text color": "Matn rangi",
"Background color": "Orqa fon rangi",
"Custom...": "O'zgacha...",
"Custom color": "O'zgacha rang",
"No color": "Rangsiz",
"Table of Contents": "Mundarija",
"Show blocks": "Bloklarni ko'rsatish",
"Show invisible characters": "Ko'rinmas belgilarni ko'rsatish",
"Words: {0}": "So'zlar soni: {0}",
"File": "Fayl",
"Edit": "Tahrirlash",
"Insert": "Qo'shish",
"View": "Ko'rish",
"Format": "Shakllar",
"Table": "Jadval",
"Tools": "Vositalar",
"Rich Text Area. Press ALT-F9 for menu. Press ALT-F10 for toolbar. Press ALT-0 for help": "Murakkab matn maydoni. Menyu uchun ALT-F9 tugmalarini bosing. Vositalar paneli uchun ALT-F10 tugmasini bosing. Yordamni chaqirish uchun ALT-0-ni bosing"
});


text:
extern NSString * const CBPAction;
extern NSString * const CBPAuthorId;
extern NSString * const CBPAuthorIndex;
extern NSString * const CBPAuthorPosts;
extern NSString * const CBPAuthorSlug;
extern NSString * const CBPCategoryId;
extern NSString * const CBPCategoryIndex;
extern NSString * const CBPCategoryPosts;
extern NSString * const CBPCategorySlug;
extern NSString * const CBPCount;
extern NSString * const CBPCurrentPage;
extern NSString * const CBPDate;
extern NSString * const CBPDateIndex;
extern NSString * const CBPDatePosts;
extern NSString * const CBPId;
extern NSString * const CBPPage;
extern NSString * const CBPPageChildren;
extern NSString * const CBPPageId;
extern NSString * const CBPPageIndex;
extern NSString * const CBPPageSlug;
extern NSString * const CBPPost;
extern NSString * const CBPPostId;
extern NSString * const CBPPostSlug;
extern NSString * const CBPPostType;
extern NSString * const CBPRecentPosts;
extern NSString * const CBPSearchQuery;
extern NSString * const CBPSearchResults;
extern NSString * const CBPSlug;
extern NSString * const CBPTagId;
extern NSString * const CBPTagIndex;
extern NSString * const CBPTagSlug;
extern NSString * const CBPTagPosts;


text:
package com.moarperipherals.handler;

public interface IPlayerEventHook {
    void onPlayerJoin(String username);

    void onPlayerLeave(String username);
}


text:
For more information, please see [our blog post](http://developers.500px.com/2015/03/17/a-blurring-view-for-android.html).

## Download

Define via Gradle:

``` groovy
repositories {
    maven { url 'https://github.com/500px/500px-android-blur/raw/master/releases/' }
}

dependencies {
    compile 'com.fivehundredpx:blurringview:1.0.0'
}
```

Enable renderscript in your module's `defaultConfig`:
```groovy
android {
    defaultConfig {

        renderscriptTargetApi 21
        renderscriptSupportModeEnabled true
        ...
    }
}

```

## Usage

First, give the blurring view a reference to the view to be blurred:

``` java
blurringView.setBlurredView(blurredView);
```

and then whenever the blurred view changes, invalidate the blurring view:

``` java
blurringView.invalidate();
```

## Demo

![500px Blurring View Demo](blurdemo.gif "500px Blurring View Demo")

## License

This project is licensed under the terms of [the MIT license](LICENSE.txt).


text:
title: 'Tracing Largest Botmaster who behind Waledac & Rustock'

author: dhanumurti
layout: post
permalink: /casperspy/
share: true
socialize:
  - 1,2,17,18
dsq_thread_id:
  - 2000051439
categories:
  - articles
  - Botnet
  - Cybercrime
tags:
  - Alan Ralsky
  - Dmitri A. Sergeev
  - ger-mes.ru
  - Peter Levashov
  - Peter Severa
  - Ralsky's 2008 indictment
  - Rustock botmaster
  - Rustock botnet
  - Spam Botnet
  - Spamdot.biz
  - Storm Worm
  - takedown of Rustock in March 2011
  - Tarelka
  - Viktor Sergeevich Ivashov
  - Waledac Botnet
---
Over the past 18 months, I've published a series of posts that provide clues about the ***possible*** ***real-life identities of the men*** responsible for building some of the largest and most disruptive spam botnets on the planet. I've since done a bit more digging into the backgrounds of the individuals thought to be responsible for the ***Rustock*** and ***Waledac*** spam botnets, which has produced some additional fascinating and corroborating details about these two characters.

### Never Before Published Details

In March 2011, KrebsOnSecurity featured ***never-before-published details*** about the financial accounts and nicknames used by the Rustock botmaster. That story was based on information leaked from **SpamIt**, a cybercrime business that paid spammers to promote rogue Internet pharmacies (think Viagra spam). In ***a follow-up post***, I wrote that the Rustock botmaster's personal email account was tied to a domain name **ger-mes.ru**, which at one time featured a ***résumé*** of a young man named **Dmitri A. Sergeev**.

Then, on Jan. 26. 2012, I ran a story featuring a trail of evidence suggesting ***a possible identity of "Severa"*** (a.k.a. "Peter Severa"), another SpamIt affiliate who is widely considered the author of the Waledac botnet (and likely the* **Storm Worm***). In that story, I included several screen shots of Severa chatting on **Spamdot.biz**, an extremely secretive Russian forum dedicated to those involved in the spam business. In*** one of the screen shots,*** Severa laments the arrest of ***Alan Ralsky,*** a convicted American spam kingpin who specialized in stock spam and who — according to the **U.S. Justice Department** – was partnered with Severa. Anti-spam activists at Spamhaus.org ***maintain*** that Peter Severa's real name is **Peter Levashov** (although the evidence I gathered also turned up another name, **Viktor Sergeevich Ivashov**).

It looks now like Spamhaus's conclusion on Severa was closer to the truth. More on that in a second. I was able to feature the Spamdot discussions because I'd obtained a backup copy of the forum. But somehow in all of my earlier investigations I overlooked a handful of private messages between Severa and the Rustock botmaster, who used the nickname "**Tarelka**" on Spamdot. Apparently, the two worked together on the same kind of ***pump-and-dump ***stock spam schemes, but also knew each other intimately enough to be on a first-name basis.

### Spamdot.biz chat between Tarelka and Severa

The following is from a series of private Spamdot message exchanged between Tarelka and Severa on May 25 and May 26, 2010. In it, Severa refers to Tarelka as "Dimas," a familiar form of "Dmitri." Likewise, Tarelka addresses Severa as "Petka," a common Russian diminutive of "Peter." They discuss a mysterious mutual friend named John, who apparently used the nickname "Apple."

> *From: Severa*
> * To: Tarelka*
> * Date: May 25, 2010, 10:28 a.m.*
> * Subject: Stocks*
>
> *"Dimas, hello.  How's everything?  What has happened with Apple?  Everything is understandable in regards to Ralka.  However, what's happened with them?  I used to have more people, they have also disappeared.  I think they got scared after Ralsky got shaken down."*
>
> *From: Tarelka*
> * To: Severa*
> * Date: May 25, 2010, 3:20 p.m.*
> * Subject: Re: Stocks*
>
> *"Everything is all right with John.  We drank with him recently in Europe. He is getting married soon. He is no longer spamming stocks.  He got squeezed [arrested/questioned] once very badly some time ago.  Now he is all clean.  His friend – SP – screwed him and also is not working with stocks now.  Rin is in total shit.  He is going to be in jail (or he is going to be hiding) for a long time.  He calls me pretty often, so he is alive so far.  I am helping his wife with money from time to time."*
>
> *The two exchange recommendations about their favorite nightclubs in St. Petersburg, Russia. Tarelka inquires how Severa is doing, which elicits the following reply:*
>
> *From: Severa*
> * To: Tarelka*
> * Date: May 25, 2010, 3:27 p.m.*
> * Subject: Re: Stocks*
>
> *"I am okay. Damn, where to find sponsors? I am sure I can spin off stocks even in the current market. Are there any more contacts? Maybe I will ask Apple. Maybe he can give me some referrals. Who could think two years ago that this "theme" would die, huh? Give my regards to Igor [possibly Igor Gusev, the co-curator of SpamIt]. I wish you luck and patience."*
>
> *Tarelka says he tried to convince John/Apple that there was still money to be made in stock spam, but that John insisted the market was dead, and that no one was coming forward to pay spammers to send pump-and-dump spam anymore.*
>
> *From: Tarelka*
> * To: Severa*
> * Date: May 26, 2010, 8:02 a.m.*
> * Subject; Re: Stocks*
>
> *"My friend….do you think that stocks was not the central theme of our conversation? I filled his ears with this topic. He does not see any possibilities. Not at all. So, we are sitting on our asses, sending pharmacy and replica [spam].*

The "John" in the conversation above may have one of the two Johns named as co-conspirators in ***Ralsky's 2008 indictment ***(PDF) on spam charges. According to*** his Wikipedia page***, Ralsky was sentenced in 2009 to four years and three months in prison after pleading guilty to wire fraud, mail fraud and violations of the ***CAN-SPAM Act.*** That sentence was later reduced to 35 months, when Ralsky agreed to assist in the prosecution of other spammers. He was reportedly released from prison on Sept. 14, 2012.

Both Severa and Tarelka remain free and quite active in the spam and malware scene. According to sources, Tarelka claims his botnet code was sold to three different miscreants prior to Microsoft's ***takedown of Rustock in March 2011***, although he still sells custom rootkits to vetted customers. In July 2011, Microsoft began offering ***a $250,000 reward ***for information leading to the arrest and conviction of the individual(s) responsible for Rustock


text:
import SignInForm from '../components/SignInForm.js';
import { connect } from 'react-redux';

const mapDispatchToProps = (dispatch) => {
  return {
   resetMe: () =>{
    //sign up is not reused, so we dont need to resetUserFields
    //in our case, it will remove authenticated users
     //dispatch(resetUserFields());
    }
  }
}

function mapStateToProps(state, ownProps) {
  return {
    user: state.user
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(SignInForm);


text:
<?php

use xPaw\MinecraftPing;
use xPaw\MinecraftQuery;

/**
 * Abstraction over xPaw\MinecraftQuery & xPaw\MinecraftPing to make them fit with our needs.
 *
 * @package NamelessMC\Minecraft
 * @author Samerton
 * @version 2.0.0-pr13
 * @license MIT
 */
class MCQuery {

    private const COLOUR_CHAR = '§';

    private const COLOURS = [
        'AA0000' => '4',
        'FF5555' => 'c',
        'FFAA00' => '6',
        'FFFF55' => 'e',
        '00AA00' => '2',
        '55FF55' => 'a',
        '55FFFF' => 'b',
        '00AAAA' => '3',
        '0000AA' => '1',
        '5555FF' => '9',
        'FF55FF' => 'd',
        'AA00AA' => '5',
        'FFFFFF' => 'f',
        'AAAAAA' => '7',
        '555555' => '8',
        '000000' => '0',
    ];

    /**
     * Query a single server
     *
     * @param array $ip Array ['ip' => string, 'pre' => int] - 'ip' contains ip:port, 'pre' 1 for pre-Minecraft 1.7 otherwise 0
     * @param string $type Type of query to use (`internal` or `external`).
     * @param bool $bedrock Whether this is a Bedrock server or not.
     * @param Language $language Query language object.
     * @return array Array containing query result.
     */
    public static function singleQuery(array $ip, string $type, bool $bedrock, Language $language): array {
        try {
            $query_ip = explode(':', $ip['ip']);
            if ($type == 'internal') {
                // Internal query
                if (count($query_ip) == 1 || (strlen($query_ip[1]) == 2 && empty($query_ip[1]))) {
                    $query_ip[1] = 25565;
                }

                if (count($query_ip) != 2) {
                    return [
                        'error' => true,
                        'value' => 'split IP by : must contain exactly two components'
                    ];
                }

                if (!$bedrock) {
                    $ping = new MinecraftPing($query_ip[0], $query_ip[1], 5);

                    if ($ip['pre'] == 1) {
                        $query = $ping->QueryOldPre17();
                    } else {
                        $query = $ping->Query();
                    }

                    $ping->close();

                    if (isset($query['players'])) {
                        $player_list = $query['players']['sample'] ?? [];

                        return [
                            'status_value' => 1,
                            'status' => $language->get('general', 'online'),
                            'player_count' => Output::getClean($query['players']['online']),
                            'player_count_max' => Output::getClean($query['players']['max']),
                            'player_list' => $player_list,
                            'format_player_list' => self::formatPlayerList($player_list),
                            'x_players_online' => $language->get('general', 'currently_x_players_online', ['count' => Output::getClean($query['players']['online'])]),
                            'motd' => self::getMotd(
                                is_string($text = $query['description']) ? $text : $text['text'],
                                $query['description']['extra'] ?? [],
                            ),
                            'version' => $query['version']['name']
                        ];
                    }
                } else {
                    $querier = new MinecraftQuery();
                    $querier->ConnectBedrock($query_ip[0], $query_ip[1], 5);
                    $query = $querier->GetInfo();
                    return [
                        'status_value' => 1,
                        'status' => $language->get('general', 'online'),
                        'player_count' => Output::getClean($query['Players']),
                        'player_count_max' => Output::getClean($query['MaxPlayers']),
                        'x_players_online' => $language->get('general', 'currently_x_players_online', ['count' => Output::getClean($query['Players'])]),
                        'motd' => $query['HostName'],
                        'version' => $query['Version']
                    ];
                }

                return [
                    'status_value' => 0,
                    'status' => $language->get('general', 'offline'),
                    'server_offline' => $language->get('general', 'server_offline')
                ];
            }

            // External query
            if (count($query_ip) > 2) {
                return [
                    'error' => true,
                    'value' => 'split IP by : contains more than two components'
                ];
            }

            $query = ExternalMCQuery::query($query_ip[0], ($query_ip[1] ?? ($bedrock ? 19132 : 25565)), $bedrock);

            if ($query !== false && !$query->error && isset($query->response)) {
                $player_list = $query->response->players->list ?? [];

                return [
                    'status_value' => 1,
                    'status' => $language->get('general', 'online'),
                    'player_count' => Output::getClean($query->response->players->online),
                    'player_count_max' => Output::getClean($query->response->players->max),
                    'player_list' => $player_list,
                    'format_player_list' => self::formatPlayerList($player_list),
                    'x_players_online' => $language->get('general', 'currently_x_players_online', ['count' => Output::getClean($query->response->players->online)]),
                    // TODO: external query does not return bedrock MOTD at all
                    'motd' => self::getMotd(
                        json_decode(json_encode($query->response->description->text), true) ?? '',
                        json_decode(json_encode($query->response->description->extra), true) ?? []
                    ),
                ];
            }

            return [
                'status_value' => 0,
                'status' => $language->get('general', 'offline'),
                'server_offline' => $language->get('general', 'server_offline')
            ];
        } catch (Exception $e) {
            $error = $e->getMessage();

            $query_ip = explode(':', $ip['ip']);

            DB::getInstance()->insert('query_errors', [
                    'date' => date('U'),
                    'error' => $error,
                    'ip' => $query_ip[0],
                    'port' => $query_ip[1] ?? 25565
            ]);

            return [
                'error' => true,
                'value' => $error
            ];
        }
    }

    /**
     * Formats a list of players into something useful for the frontend.
     *
     * @param array $player_list Unformatted array of players in format 'id' => string (UUID), 'name' => string (username)
     * @return array Array of formatted players
     **/
    private static function formatPlayerList(array $player_list): array {
        $formatted = [];

        $integration = Integrations::getInstance()->getIntegration('Minecraft');
        foreach ($player_list as $player) {
            $player = (array)$player;

            $integration_user = new IntegrationUser($integration, str_replace('-', '', $player['id']), 'identifier');
            if ($integration_user->exists()) {
                $user = $integration_user->getUser();
                if ($user->exists()) {
                    $avatar = $user->getAvatar();
                    $profile = $user->getProfileURL();
                } else {
                    $avatar = AvatarSource::getAvatarFromUUID($player['id']);
                    $profile = '#';
                }
            } else {
                $avatar = AvatarSource::getAvatarFromUUID($player['id']);
                $profile = '#';
            }

            $formatted[] = [
                'username' => Output::getClean($player['name']),
                'uuid' => Output::getClean($player['id']),
                'avatar' => $avatar,
                'profile' => $profile
            ];
        }

        return $formatted;
    }

    /**
     * Query multiple servers
     *
     * @param array $servers Servers
     * @param string $type Type of query to use (internal or external)
     * @param Language $language Query language object
     * @param bool $accumulate Whether to return as one accumulated result or not
     * @return array Array containing query result
     */
    public static function multiQuery(array $servers, string $type, Language $language, bool $accumulate): array {
        $to_return = [];
        $total_count = 0;
        $status = 0;

        if ($type === 'internal') {
            foreach ($servers as $server) {
                $query_ip = explode(':', $server['ip']);
                if (count($query_ip) > 2) {
                    continue;
                }

                try {
                    if ($server['bedrock']) {
                        $ping = new MinecraftQuery();
                        $ping->ConnectBedrock($query_ip[0], ($query_ip[1] ?? 19132), 5);
                        $query = $ping->GetInfo();
                    } else {
                        $ping = new MinecraftPing($query_ip[0], ($query_ip[1] ?? 25565), 5);

                        if ($server['pre'] == 1) {
                            $query = $ping->QueryOldPre17();
                        } else {
                            $query = $ping->Query();
                        }
                    }
                } catch (Exception $e) {
                    $query = [];

                    DB::getInstance()->insert('query_errors', [
                        'date' => date('U'),
                        'error' => $e->getMessage(),
                        'ip' => $query_ip[0],
                        'port' => ($query_ip[1] ?? ($server['bedrock'] ? 19132 : 25565))
                    ]);
                }

                // bedrock
                if ($server['bedrock']) {
                    if ($accumulate === false) {
                        $to_return[] = [
                            'name' => Output::getClean($server['name']),
                            'status_value' => 1,
                            'status' => $language->get('general', 'online'),
                            'player_count' => Output::getClean($query['Players']),
                            'player_count_max' => Output::getClean($query['MaxPlayers']),
                            'x_players_online' => $language->get('general', 'currently_x_players_online', ['count' => Output::getClean($query['Players'])]),
                        ];
                    } else {
                        if ($status == 0) {
                            $status = 1;
                        }
                        $total_count += $query['Players'];
                    }
                } else if (isset($query['players'])) {
                    if ($accumulate === false) {
                        $to_return[] = [
                            'name' => Output::getClean($server['name']),
                            'status_value' => 1,
                            'status' => $language->get('general', 'online'),
                            'player_count' => Output::getClean($query['players']['online']),
                            'player_count_max' => Output::getClean($query['players']['max']),
                            'x_players_online' => $language->get('general', 'currently_x_players_online', ['count' => Output::getClean($query['players']['online'])]),
                        ];
                    } else {
                        if ($status == 0) {
                            $status = 1;
                        }
                        $total_count += $query['players']['online'];
                    }
                } else if ($accumulate === true) {
                    $to_return[] = [
                        'name' => Output::getClean($server['name']),
                        'status_value' => 0,
                        'status' => $language->get('general', 'offline'),
                        'server_offline' => $language->get('general', 'server_offline')
                    ];
                }
            }

            if (isset($ping) && $ping instanceof MinecraftPing) {
                $ping->close();
            }

        } else {
            // External query
            foreach ($servers as $server) {
                $query_ip = explode(':', $server['ip']);
                if (count($query_ip) > 2) {
                    continue;
                }

                $is_bedrock = isset($server['bedrock']) && $server['bedrock'] === true;

                $query = ExternalMCQuery::query($query_ip[0], ($query_ip[1] ?? ($is_bedrock ? 19132 : 25565)), $is_bedrock);

                if ($query !== false && !$query->error && isset($query->response)) {
                    if ($accumulate === false) {
                        $to_return[] = [
                            'name' => Output::getClean($server['name']),
                            'status_value' => 1,
                            'status' => $language->get('general', 'online'),
                            'player_count' => Output::getClean($query->response->players->online),
                            'player_count_max' => Output::getClean($query->response->players->max),
                            'x_players_online' => $language->get('general', 'currently_x_players_online', ['count' => Output::getClean($query->response->players->online)]),
                        ];
                    } else {
                        if ($status == 0) {
                            $status = 1;
                        }
                        $total_count += $query->response->players->online;
                    }
                } else if ($accumulate === true) {
                    $to_return[] = [
                        'name' => Output::getClean($server['name']),
                        'status_value' => 0,
                        'status' => $language->get('general', 'offline'),
                        'server_offline' => $language->get('general', 'server_offline')
                    ];
                }
            }
        }

        if ($accumulate === true) {
            $to_return = [
                'status_value' => $status,
                'status' => $status == 1
                    ? $language->get('general', 'online')
                    : $language->get('general', 'offline'),
                'status_full' => $status == 1
                    ? $language->get('general', 'currently_x_players_online', ['count' => $total_count])
                    : $language->get('general', 'server_offline'),
                'player_count' => $total_count,
            ];
        }

        return $to_return;
    }

    /**
     * Convert a Minecraft MOTD to its legacy colour codes
     *
     * @param string $text Legacy MOTD single-line text
     * @param array $modern_format Array of modern MOTD format strings
     * @return string MOTD as legacy MC colours
     */
    private static function getMotd(string $text, array $modern_format): string {
        if ($text !== '') {
            return $text;
        }

        // some servers (originrealms) return a weird MOTD
        if (count($modern_format) === 1 && is_array($modern_format[0])) {
            $modern_format = $modern_format[0]['extra'] ?? [];
        }
        // and sometimes it's doubly nested...
        if (count($modern_format) === 1 && is_array($modern_format[0])) {
            $modern_format = $modern_format[0]['extra'] ?? [];
        }

        $motd = '';
        foreach ($modern_format as $word) {
            $motd .= self::COLOUR_CHAR . 'r';
            if (isset($word['color'])) {
                $motd .= self::getColor($word['color']);
            }

            if (isset($word['bold']) && $word['bold'] === true) {
                $motd .= self::COLOUR_CHAR . 'l';
            }

            $motd .= trim($word['text'], ' ');
        }

        return trim($motd);
    }

    /**
     * Find the closest MC colour to a given hex colour
     *
     * @param string $rgb RGB colour code
     * @return string The closest Minecraft colour code to the given RGB value
     */
    private static function getColor(string $rgb): string {
        if (strpos($rgb, '#') === 0) {
            $rgb = substr($rgb, 1);
        }

        $smallestDiff = null;
        $closestColor = "";
        foreach (self::COLOURS as $hex => $char) {
            $diff = self::colorDiff($hex, $rgb);
            if ($smallestDiff === null || $diff < $smallestDiff) {
                $smallestDiff = $diff;
                $closestColor = $char;
            }
        }

        return self::COLOUR_CHAR . $closestColor;
    }

    /**
     * Find the numerical difference between two RGB colours
     *
     * @param mixed $rgb1 RGB colour code
     * @param mixed $rgb2 RGB colour code
     * @return int The difference between two RGB colours
     */
    private static function colorDiff($rgb1, $rgb2): int {
        $red1 = hexdec(substr($rgb1, 0, 2));
        $green1 = hexdec(substr($rgb1, 2, 2));
        $blue1 = hexdec(substr($rgb1, 4, 2));

        $red2_substr = substr($rgb2, 0, 2);
        $green2_substr = substr($rgb2, 2, 2);
        $blue2_substr = substr($rgb2, 4, 2);

        $red2 = 0;
        if (ctype_xdigit($red2_substr)) {
            $red2 = hexdec($red2_substr);
        }

        $green2 = 0;
        if (ctype_xdigit($green2_substr)) {
            $green2 = hexdec($green2_substr);
        }

        $blue2 = 0;
        if (ctype_xdigit($blue2_substr)) {
            $blue2 = hexdec($blue2_substr);
        }

        return abs($red1 - $red2) + abs($green1 - $green2) + abs($blue1 - $blue2);
    }
}


text:
namespace autofill {

// Structure used for sending information from browser to renderer about on
// which fields password should be generated.
struct PasswordFormGenerationData {
  PasswordFormGenerationData();
  PasswordFormGenerationData(FieldRendererId new_password_renderer_id,
                             FieldRendererId confirmation_password_renderer_id);
#if defined(OS_IOS)
  PasswordFormGenerationData(FormRendererId form_renderer_id,
                             base::string16 new_password_element,
                             FieldRendererId new_password_renderer_id,
                             FieldRendererId confirmation_password_renderer_id);

  PasswordFormGenerationData(const PasswordFormGenerationData&);
  PasswordFormGenerationData& operator=(const PasswordFormGenerationData&);
  PasswordFormGenerationData(PasswordFormGenerationData&&);
  PasswordFormGenerationData& operator=(PasswordFormGenerationData&&);
  ~PasswordFormGenerationData();

  FormRendererId form_renderer_id;
  // TODO(crbug.com/1075444): Remove this once VotesUploader starts to use
  // unique renderer IDs.
  base::string16 new_password_element;
#endif
  FieldRendererId new_password_renderer_id;
  FieldRendererId confirmation_password_renderer_id;
};

}  // namespace autofill

#endif  // COMPONENTS_AUTOFILL_CORE_COMMON_PASSWORD_FORM_GENERATION_DATA_H_


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Unit_Tests
{
    [TestClass]
    public class BranchUnitTests
    {
        public sealed class ViewModel : ViewModelBase
        {
            public bool UseB
            {
                get { return Properties.Get(false); }
                set { Properties.Set(value); }
            }

            public int A
            {
                get { return Properties.Get(7); }
                set { Properties.Set(value); }
            }

            public int B
            {
                get { return Properties.Get(11); }
                set { Properties.Set(value); }
            }

            public int CalculatedValue
            {
                get
                {
                    return Properties.Calculated(() =>
                    {
                        ++CalculatedValueExecutionCount;
                        return UseB ? B : A;
                    });
                }
            }

            public int CalculatedValueExecutionCount;
        }

        [TestMethod]
        public void Calculated_InitialValueIsCalculated()
        {
            var vm = new ViewModel();
            Assert.AreEqual(7, vm.CalculatedValue);
            Assert.AreEqual(1, vm.CalculatedValueExecutionCount);
        }

        [TestMethod]
        public void IndependentPropertyChanges_DoesNotRaisePropertyChangedForCalculated()
        {
            var changes = new List<string>();
            var vm = new ViewModel();
            vm.PropertyChanged += (_, args) => changes.Add(args.PropertyName);
            var value = vm.B;
            value = vm.CalculatedValue;
            vm.B = 13;
            CollectionAssert.AreEquivalent(new[] { "B" }, changes);
        }

        [TestMethod]
        public void DependentPropertyChanges_RaisesPropertyChangedForCalculated()
        {
            var changes = new List<string>();
            var vm = new ViewModel();
            vm.PropertyChanged += (_, args) => changes.Add(args.PropertyName);
            var value = vm.A;
            value = vm.CalculatedValue;
            vm.A = 13;
            CollectionAssert.AreEquivalent(new[] { "A", "CalculatedValue" }, changes);
        }

        [TestMethod]
        public void Calculated_AfterBranchSwitch_IsRecalculated()
        {
            var vm = new ViewModel();
            var value = vm.CalculatedValue;
            vm.UseB = true;
            Assert.AreEqual(11, vm.CalculatedValue);
            Assert.AreEqual(2, vm.CalculatedValueExecutionCount);
        }

        [TestMethod]
        public void IndependentPropertyChanges_AfterBranchSwitch_DoesNotRaisePropertyChangedForCalculated()
        {
            var changes = new List<string>();
            var vm = new ViewModel();
            vm.PropertyChanged += (_, args) => changes.Add(args.PropertyName);
            var value = vm.CalculatedValue;
            vm.UseB = true;
            value = vm.CalculatedValue;

            vm.A = 13;

            CollectionAssert.AreEquivalent(new[] { "UseB", "CalculatedValue", "A" }, changes);
        }

        [TestMethod]
        public void DependentPropertyChanges_AfterBranchSwitch_RaisesPropertyChangedForCalculated()
        {
            var changes = new List<string>();
            var vm = new ViewModel();
            vm.PropertyChanged += (_, args) => changes.Add(args.PropertyName);
            var value = vm.CalculatedValue;
            vm.UseB = true;
            value = vm.CalculatedValue;

            vm.B = 13;

            CollectionAssert.AreEquivalent(new[] { "UseB", "CalculatedValue", "B", "CalculatedValue" }, changes);
        }
    }
}


text:
namespace ray {
namespace rpc {

#define RAY_OBJECT_MANAGER_RPC_HANDLERS           \
  RPC_SERVICE_HANDLER(ObjectManagerService, Push) \
  RPC_SERVICE_HANDLER(ObjectManagerService, Pull) \
  RPC_SERVICE_HANDLER(ObjectManagerService, FreeObjects)

/// Implementations of the `ObjectManagerGrpcService`, check interface in
/// `src/ray/protobuf/object_manager.proto`.
class ObjectManagerServiceHandler {
 public:
  /// Handle a `Push` request.
  /// The implementation can handle this request asynchronously. When handling is done,
  /// the `send_reply_callback` should be called.
  ///
  /// \param[in] request The request message.
  /// \param[out] reply The reply message.
  /// \param[in] send_reply_callback The callback to be called when the request is done.
  virtual void HandlePush(const PushRequest &request, PushReply *reply,
                          SendReplyCallback send_reply_callback) = 0;
  /// Handle a `Pull` request
  virtual void HandlePull(const PullRequest &request, PullReply *reply,
                          SendReplyCallback send_reply_callback) = 0;
  /// Handle a `FreeObjects` request
  virtual void HandleFreeObjects(const FreeObjectsRequest &request,
                                 FreeObjectsReply *reply,
                                 SendReplyCallback send_reply_callback) = 0;
};

/// The `GrpcService` for `ObjectManagerGrpcService`.
class ObjectManagerGrpcService : public GrpcService {
 public:
  /// Construct a `ObjectManagerGrpcService`.
  ///
  /// \param[in] port See `GrpcService`.
  /// \param[in] handler The service handler that actually handle the requests.
  ObjectManagerGrpcService(boost::asio::io_service &io_service,
                           ObjectManagerServiceHandler &service_handler)
      : GrpcService(io_service), service_handler_(service_handler){};

 protected:
  grpc::Service &GetGrpcService() override { return service_; }

  void InitServerCallFactories(
      const std::unique_ptr<grpc::ServerCompletionQueue> &cq,
      std::vector<std::unique_ptr<ServerCallFactory>> *server_call_factories) override {
    RAY_OBJECT_MANAGER_RPC_HANDLERS
  }

 private:
  /// The grpc async service object.
  ObjectManagerService::AsyncService service_;
  /// The service handler that actually handle the requests.
  ObjectManagerServiceHandler &service_handler_;
};

}  // namespace rpc
}  // namespace ray


text:
title: Blog
layout: post
author: alex.coyne
permalink: /blog/
source-id: 12r6_zsX8U1FoS4DITkIKL1V0ZBSvQ9CuB4fbG4L4rVs
published: true
---
**Blog**

This lesson we were talking about presentations, seeing what is a presentation and what is speaking about pictures and words on the board. We were playing around with the tools on Prezi. Most of the lesson we were discussing what is a presentation and what isn't.


text:
import { Component,Inject } from '@angular/core';

@Component({
    selector: 'widget',
    templateUrl: './widget.component.html'
})
export class WidgetComponent {

    constructor() {

    }

    public ngOnInit() {
    }

}


text:
from office365.sharepoint.base_entity import BaseEntity

class HostedAppAddResponse(BaseEntity):

    @property
    def entity_type_name(self):
        return "Microsoft.SharePoint.ClientSideComponent.HostedAppAddResponse"


text:
package com.box.l10n.mojito.boxsdk;

import com.box.sdk.BoxFile;

/** @author jaurambault */
public class BoxFileWithContent {

  BoxFile boxFile;
  String content;

  public BoxFile getBoxFile() {
    return boxFile;
  }

  public void setBoxFile(BoxFile boxFile) {
    this.boxFile = boxFile;
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }
}


text:
from flask import url_for

from ..core.tests import FlaskTest
from ..ext import db

class AuthTest(FlaskTest):

    def test_model_mixin(self):
        from .models import User
        self.assertTrue(User.do_true())

    def test_users(self):
        from .models import User

        response = self.client.post('/auth/login/', data=dict())
        self.assertRedirects(response, '/')

        user = User(username='test', pw_hash='test', email='test@test.com')
        db.session.add(user)
        db.session.commit()
        self.assertTrue(user.updated_at)

        response = self.client.post('/auth/login/', data=dict(
            email='test@test.com',
            action_save=True,
            password='test'))
        redirect_url = url_for(self.app.config.get('AUTH_PROFILE_VIEW', 'auth.profile'))
        self.assertRedirects(response, redirect_url)

        response = self.client.get('/auth/logout/')
        self.assertRedirects(response, '/')

        response = self.client.post('/auth/register/', data=dict(
            username='test2',
            email='test2@test.com',
            action_save=True,
            password='test',
            password_confirm='test',
        ))
        redirect_url = url_for(self.app.config.get('AUTH_PROFILE_VIEW', 'auth.profile'))
        self.assertRedirects(response, redirect_url)

        user = User.query.filter(User.username == 'test2').first()
        self.assertEqual(user.email, 'test2@test.com')

    def test_manager(self):
        from .models import Role, User
        from .manage import create_role, create_user, add_role

        create_role('test')
        role = Role.query.filter(Role.name == 'test').first()
        self.assertEqual(role.name, 'test')

        create_user('test', 'test@test.com', active=True, password='12345')
        user = User.query.filter(User.username == 'test').first()

        add_role('test', 'test')
        self.assertTrue(role in user.roles)

    def test_oauth(self):
        from flask import url_for

        if self.app.config.get('OAUTH_TWITTER'):
            self.assertTrue(url_for('oauth_twitter_login'))

        if self.app.config.get('OAUTH_GITHUB'):
            self.assertTrue(url_for('oauth_github_login'))

        if self.app.config.get('OAUTH_FACEBOOK'):
            self.assertTrue(url_for('oauth_facebook_login'))

class TestUserMixin(object):

    @staticmethod
    def do_true():
        return True


text:
@interface TrBasicAnimation () {

    TrCurve *_curve;

}

@end

@implementation TrBasicAnimation

#pragma mark - Creating an Animation

+ (instancetype)animationWithKeyPath:(NSString *)path {

    TrBasicAnimation* animation = [super animationWithKeyPath:path];

    if (animation)
        animation.curve = [TrCurve linear];

    return animation;

}

#pragma mark - Private Methods

- (void)applyInterpolationIfSetupComplete {

    if (self.duration && self.curve && self.fromValue && self.toValue) {

        NSMutableArray *keyTimes = [[NSMutableArray alloc] init];
        NSMutableArray *values = [[NSMutableArray alloc] init];

        for (NSTimeInterval t = .0 ; t <= 1.0 ; t += 1.0 / (60.0 * (self.duration / self.speed))) {

            [keyTimes addObject:@(t)];
            [values addObject:[self.fromValue interpolateWithValue:self.toValue
                                                        atPosition:[self.curve transform:t]]];

        }

        self.keyTimes = keyTimes;
        self.values = values;

    } else
        self.keyTimes = self.values = nil;

}

#pragma mark - Keyframe Timing

- (void)setSpeed:(float)speed {

    [super setSpeed:speed];

    [self applyInterpolationIfSetupComplete];

}

- (void)setDuration:(CFTimeInterval)duration {

    [super setDuration:duration];

    [self applyInterpolationIfSetupComplete];

}

- (void)setCurve:(TrCurve *)curve {

    _curve = [curve copy];

    [self applyInterpolationIfSetupComplete];

}

- (void)setFromValue:(id<TrInterpolatable>)fromValue {

    _fromValue = fromValue;

    [self applyInterpolationIfSetupComplete];

}

- (void)setToValue:(id<TrInterpolatable>)toValue {

    _toValue = toValue;

    [self applyInterpolationIfSetupComplete];

}

@end


text:
get '/posts/tag/:tag_id' do
  tags = Tag.find(params[:tag_id])
  @posts = tags.posts
  erb :posts_all
end


text:
"""Provides readers configured for different datasets."""

import tensorflow as tf
import utils

class BaseWriter(object):
  """Inherit from this class when implementing new readers."""

  def prepare_writer(self, unused_filename_queue):
    """Create a thread for generating prediction and label tensors."""
    raise NotImplementedError()

class YT8MAggregatedFeatureWriter(BaseWriter):
  """Reads TFRecords of pre-aggregated Examples.

  The TFRecords must contain Examples with a sparse int64 'labels' feature and
  a fixed length float32 feature, obtained from the features in 'feature_name'.
  The float features are assumed to be an average of dequantized values.
  """

  def __init__(self,
               num_classes=4716,
               feature_sizes=[1024],
               feature_names=["mean_inc3"]):
    """Construct a YT8MAggregatedFeatureReader.

    Args:
      num_classes: a positive integer for the number of classes.
      feature_sizes: positive integer(s) for the feature dimensions as a list.
      feature_names: the feature name(s) in the tensorflow record as a list.
    """

    assert len(feature_names) == len(feature_sizes), \
    "length of feature_names (={}) != length of feature_sizes (={})".format( \
    len(feature_names), len(feature_sizes))

    self.num_classes = num_classes
    self.feature_sizes = feature_sizes
    self.feature_names = feature_names

  def prepare_writer(self, filename_queue, batch_size=1024):
    """Creates a single reader thread for pre-aggregated YouTube 8M Examples.

    Args:
      filename_queue: A tensorflow queue of filename locations.

    Returns:
      A tuple of video indexes, features, labels, and padding data.
    """
    reader = tf.TFRecordReader()
    _, serialized_examples = reader.read_up_to(filename_queue, batch_size)

    # set the mapping from the fields to data types in the proto
    num_features = len(self.feature_names)
    assert num_features > 0, "self.feature_names is empty!"
    assert len(self.feature_names) == len(self.feature_sizes), \
    "length of feature_names (={}) != length of feature_sizes (={})".format( \
    len(self.feature_names), len(self.feature_sizes))

    feature_map = {"video_id": tf.FixedLenFeature([], tf.string),
                   "labels": tf.VarLenFeature(tf.int64)}
    for feature_index in range(num_features):
      feature_map[self.feature_names[feature_index]] = tf.FixedLenFeature(
          [self.feature_sizes[feature_index]], tf.float32)

    features = tf.parse_example(serialized_examples, features=feature_map)
    labels = tf.sparse_to_indicator(features["labels"], self.num_classes)
    labels.set_shape([None, self.num_classes])
    concatenated_features = tf.concat([
        features[feature_name] for feature_name in self.feature_names], 1)

    return features["video_id"], concatenated_features, labels, tf.ones([tf.shape(serialized_examples)[0]])


text:
<component name="DependencyValidationManager">
  <scope name="Apache" pattern="src:*..*||src:build||src:settings||test:*..*" />
</component>


text:
#include "core/blocklang.h"

#include "scanner.h"
#include "blk_parser.tab.hh"
#include <vector>
#include <memory>

namespace Lang {

struct Driver {
private:
	Scanner* scanner;
	Parser* parser;
	sptr<Expression> prog;

private:
	void parse();

private:
	//no copy
	Driver(const Driver& o);
	Driver& operator=(const Driver& o);

public:
	//move
	Driver(Driver&& o);
	Driver& operator=(Driver&& o);

public:
	virtual ~Driver();

	Driver(std::istream& is);
	Driver();

	void set_program(sptr<Expression> prog);
	sptr<Expression>& program();
};

}

#endif


text:
namespace chrono {
namespace vehicle {

/// @addtogroup vehicle_tracked_roller
/// @{

/// Double roller model constructed with data from file (JSON format).
class CH_VEHICLE_API DoubleRoller : public ChDoubleRoller {
  public:
    DoubleRoller(const std::string& filename);
    DoubleRoller(const rapidjson::Document& d);
    ~DoubleRoller() {}

    virtual double GetRadius() const override { return m_roller_radius; }
    virtual double GetWidth() const override { return m_roller_width; }
    virtual double GetGap() const override { return m_roller_gap; }

    virtual double GetMass() const override { return m_roller_mass; }
    virtual const ChVector<>& GetInertia() override { return m_roller_inertia; }

    virtual void AddVisualizationAssets(VisualizationType vis) override;

  private:
    virtual void Create(const rapidjson::Document& d) override;

    double m_roller_radius;
    double m_roller_width;
    double m_roller_gap;

    double m_roller_mass;
    ChVector<> m_roller_inertia;

    bool m_has_mesh;
    std::string m_meshName;
    std::string m_meshFile;
};

/// @} vehicle_tracked_roller

}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
CREATE TABLE IF NOT EXISTS `posts` (
  `user_id` int(11) NOT NULL,
  `status` text NOT NULL,
  `short_url` varchar(200) default NULL,
  `created` int(11) NOT NULL,
  KEY `user_id` (`user_id`,`created`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(11) NOT NULL auto_increment,
  `user_id` int(11) NOT NULL,
  `status` text NOT NULL,
  `short_url` varchar(200) default NULL,
  `created` int(11) NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `user_id` (`user_id`,`created`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;


text:
const niv = require('npm-install-version');

const packageName = `webpack@${process.env.WEBPACK_VERSION}`;
niv.install(packageName);

module.exports = niv.require(packageName);


text:
#include "third_party/blink/renderer/modules/webaudio/panner_node.h"

#include "third_party/blink/renderer/bindings/modules/v8/v8_panner_options.h"
#include "third_party/blink/renderer/modules/webaudio/audio_graph_tracer.h"
#include "third_party/blink/renderer/modules/webaudio/audio_listener.h"
#include "third_party/blink/renderer/modules/webaudio/audio_param.h"
#include "third_party/blink/renderer/modules/webaudio/panner_handler.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"

namespace blink {

namespace {

constexpr double kDefaultPositionXValue = 0.0;
constexpr double kDefaultPositionYValue = 0.0;
constexpr double kDefaultPositionZValue = 0.0;
constexpr double kDefaultOrientationXValue = 1.0;
constexpr double kDefaultOrientationYValue = 0.0;
constexpr double kDefaultOrientationZValue = 0.0;

}  // namespace

PannerNode::PannerNode(BaseAudioContext& context)
    : AudioNode(context),
      position_x_(
          AudioParam::Create(context,
                             Uuid(),
                             AudioParamHandler::kParamTypePannerPositionX,
                             kDefaultPositionXValue,
                             AudioParamHandler::AutomationRate::kAudio,
                             AudioParamHandler::AutomationRateMode::kVariable)),
      position_y_(
          AudioParam::Create(context,
                             Uuid(),
                             AudioParamHandler::kParamTypePannerPositionY,
                             kDefaultPositionYValue,
                             AudioParamHandler::AutomationRate::kAudio,
                             AudioParamHandler::AutomationRateMode::kVariable)),
      position_z_(
          AudioParam::Create(context,
                             Uuid(),
                             AudioParamHandler::kParamTypePannerPositionZ,
                             kDefaultPositionZValue,
                             AudioParamHandler::AutomationRate::kAudio,
                             AudioParamHandler::AutomationRateMode::kVariable)),
      orientation_x_(
          AudioParam::Create(context,
                             Uuid(),
                             AudioParamHandler::kParamTypePannerOrientationX,
                             kDefaultOrientationXValue,
                             AudioParamHandler::AutomationRate::kAudio,
                             AudioParamHandler::AutomationRateMode::kVariable)),
      orientation_y_(
          AudioParam::Create(context,
                             Uuid(),
                             AudioParamHandler::kParamTypePannerOrientationY,
                             kDefaultOrientationYValue,
                             AudioParamHandler::AutomationRate::kAudio,
                             AudioParamHandler::AutomationRateMode::kVariable)),
      orientation_z_(
          AudioParam::Create(context,
                             Uuid(),
                             AudioParamHandler::kParamTypePannerOrientationZ,
                             kDefaultOrientationZValue,
                             AudioParamHandler::AutomationRate::kAudio,
                             AudioParamHandler::AutomationRateMode::kVariable)),
      listener_(context.listener()) {
  SetHandler(PannerHandler::Create(
      *this, context.sampleRate(), position_x_->Handler(),
      position_y_->Handler(), position_z_->Handler(), orientation_x_->Handler(),
      orientation_y_->Handler(), orientation_z_->Handler()));
}

PannerNode* PannerNode::Create(BaseAudioContext& context,
                               ExceptionState& exception_state) {
  DCHECK(IsMainThread());

  return MakeGarbageCollected<PannerNode>(context);
}

PannerNode* PannerNode::Create(BaseAudioContext* context,
                               const PannerOptions* options,
                               ExceptionState& exception_state) {
  PannerNode* node = Create(*context, exception_state);

  if (!node) {
    return nullptr;
  }

  node->HandleChannelOptions(options, exception_state);

  node->setPanningModel(options->panningModel());
  node->setDistanceModel(options->distanceModel());

  node->positionX()->setValue(options->positionX());
  node->positionY()->setValue(options->positionY());
  node->positionZ()->setValue(options->positionZ());

  node->orientationX()->setValue(options->orientationX());
  node->orientationY()->setValue(options->orientationY());
  node->orientationZ()->setValue(options->orientationZ());

  node->setRefDistance(options->refDistance(), exception_state);
  node->setMaxDistance(options->maxDistance(), exception_state);
  node->setRolloffFactor(options->rolloffFactor(), exception_state);
  node->setConeInnerAngle(options->coneInnerAngle());
  node->setConeOuterAngle(options->coneOuterAngle());
  node->setConeOuterGain(options->coneOuterGain(), exception_state);

  return node;
}

PannerHandler& PannerNode::GetPannerHandler() const {
  return static_cast<PannerHandler&>(Handler());
}

String PannerNode::panningModel() const {
  return GetPannerHandler().PanningModel();
}

void PannerNode::setPanningModel(const String& model) {
  GetPannerHandler().SetPanningModel(model);
}

void PannerNode::setPosition(float x,
                             float y,
                             float z,
                             ExceptionState& exceptionState) {
  GetPannerHandler().SetPosition(x, y, z, exceptionState);
}

void PannerNode::setOrientation(float x,
                                float y,
                                float z,
                                ExceptionState& exceptionState) {
  GetPannerHandler().SetOrientation(x, y, z, exceptionState);
}

String PannerNode::distanceModel() const {
  return GetPannerHandler().DistanceModel();
}

void PannerNode::setDistanceModel(const String& model) {
  GetPannerHandler().SetDistanceModel(model);
}

double PannerNode::refDistance() const {
  return GetPannerHandler().RefDistance();
}

void PannerNode::setRefDistance(double distance,
                                ExceptionState& exception_state) {
  if (distance < 0) {
    exception_state.ThrowRangeError(
        ExceptionMessages::IndexExceedsMinimumBound<double>("refDistance",
                                                            distance, 0));
    return;
  }

  GetPannerHandler().SetRefDistance(distance);
}

double PannerNode::maxDistance() const {
  return GetPannerHandler().MaxDistance();
}

void PannerNode::setMaxDistance(double distance,
                                ExceptionState& exception_state) {
  if (distance <= 0) {
    exception_state.ThrowRangeError(
        ExceptionMessages::IndexExceedsMinimumBound<double>("maxDistance",
                                                            distance, 0));
    return;
  }

  GetPannerHandler().SetMaxDistance(distance);
}

double PannerNode::rolloffFactor() const {
  return GetPannerHandler().RolloffFactor();
}

void PannerNode::setRolloffFactor(double factor,
                                  ExceptionState& exception_state) {
  if (factor < 0) {
    exception_state.ThrowRangeError(
        ExceptionMessages::IndexExceedsMinimumBound<double>("rolloffFactor",
                                                            factor, 0));
    return;
  }

  GetPannerHandler().SetRolloffFactor(factor);
}

double PannerNode::coneInnerAngle() const {
  return GetPannerHandler().ConeInnerAngle();
}

void PannerNode::setConeInnerAngle(double angle) {
  GetPannerHandler().SetConeInnerAngle(angle);
}

double PannerNode::coneOuterAngle() const {
  return GetPannerHandler().ConeOuterAngle();
}

void PannerNode::setConeOuterAngle(double angle) {
  GetPannerHandler().SetConeOuterAngle(angle);
}

double PannerNode::coneOuterGain() const {
  return GetPannerHandler().ConeOuterGain();
}

void PannerNode::setConeOuterGain(double gain,
                                  ExceptionState& exception_state) {
  if (gain < 0 || gain > 1) {
    exception_state.ThrowDOMException(
        DOMExceptionCode::kInvalidStateError,
        ExceptionMessages::IndexOutsideRange<double>(
            "coneOuterGain", gain, 0, ExceptionMessages::kInclusiveBound, 1,
            ExceptionMessages::kInclusiveBound));
    return;
  }

  GetPannerHandler().SetConeOuterGain(gain);
}

void PannerNode::Trace(Visitor* visitor) const {
  visitor->Trace(position_x_);
  visitor->Trace(position_y_);
  visitor->Trace(position_z_);
  visitor->Trace(orientation_x_);
  visitor->Trace(orientation_y_);
  visitor->Trace(orientation_z_);
  visitor->Trace(listener_);
  AudioNode::Trace(visitor);
}

void PannerNode::ReportDidCreate() {
  GraphTracer().DidCreateAudioNode(this);
  GraphTracer().DidCreateAudioParam(position_x_);
  GraphTracer().DidCreateAudioParam(position_y_);
  GraphTracer().DidCreateAudioParam(position_z_);
  GraphTracer().DidCreateAudioParam(orientation_x_);
  GraphTracer().DidCreateAudioParam(orientation_y_);
  GraphTracer().DidCreateAudioParam(orientation_z_);
}

void PannerNode::ReportWillBeDestroyed() {
  GraphTracer().WillDestroyAudioParam(position_x_);
  GraphTracer().WillDestroyAudioParam(position_y_);
  GraphTracer().WillDestroyAudioParam(position_z_);
  GraphTracer().WillDestroyAudioParam(orientation_x_);
  GraphTracer().WillDestroyAudioParam(orientation_y_);
  GraphTracer().WillDestroyAudioParam(orientation_z_);
  GraphTracer().WillDestroyAudioNode(this);
}

}  // namespace blink


text:
typedef MYTYPE mytype_t;

inline MYTYPE myfun() { return 0; }

inline int intfun() {
  MYTYPE localVar = sizeof(MYTYPE);
  return localVar;
}

extern MYTYPE myvar;

// This creates a separate variable named `intvar` for each file that includes
// this header. That's definitely bad practice.
static int intvar = sizeof(MYTYPE);


text:
namespace ash {

class COMPONENT_EXPORT(UI_BASE_IME_ASH) MockIMEEngineHandler
    : public ui::TextInputMethod {
 public:
  MockIMEEngineHandler();
  ~MockIMEEngineHandler() override;

  // ui::TextInputMethod:
  void FocusIn(const InputContext& input_context) override;
  void OnTouch(ui::EventPointerType pointerType) override;
  void FocusOut() override;
  void Enable(const std::string& component_id) override;
  void Disable() override;
  void Reset() override;
  void ProcessKeyEvent(const ui::KeyEvent& key_event,
                       KeyEventDoneCallback callback) override;
  void SetCompositionBounds(const std::vector<gfx::Rect>& bounds) override;
  void SetCaretBounds(const gfx::Rect& caret_bounds) override;
  ui::VirtualKeyboardController* GetVirtualKeyboardController() const override;
  void PropertyActivate(const std::string& property_name) override;
  void CandidateClicked(uint32_t index) override;
  void SetSurroundingText(const std::u16string& text,
                          uint32_t cursor_pos,
                          uint32_t anchor_pos,
                          uint32_t offset_pos) override;
  void SetMirroringEnabled(bool mirroring_enabled) override;
  void SetCastingEnabled(bool casting_enabled) override;
  bool IsReadyForTesting() override;

  const std::string& GetActiveComponentId() const;

  int focus_in_call_count() const { return focus_in_call_count_; }
  int focus_out_call_count() const { return focus_out_call_count_; }
  int reset_call_count() const { return reset_call_count_; }
  int set_surrounding_text_call_count() const {
    return set_surrounding_text_call_count_;
  }
  int process_key_event_call_count() const {
    return process_key_event_call_count_;
  }

  const InputContext& last_text_input_context() const {
    return last_text_input_context_;
  }

  std::string last_activated_property() const {
    return last_activated_property_;
  }

  std::u16string last_set_surrounding_text() const {
    return last_set_surrounding_text_;
  }

  uint32_t last_set_surrounding_cursor_pos() const {
    return last_set_surrounding_cursor_pos_;
  }

  uint32_t last_set_surrounding_anchor_pos() const {
    return last_set_surrounding_anchor_pos_;
  }

  const ui::KeyEvent* last_processed_key_event() const {
    return last_processed_key_event_.get();
  }

  KeyEventDoneCallback last_passed_callback() {
    return std::move(last_passed_callback_);
  }

 private:
  int focus_in_call_count_;
  int focus_out_call_count_;
  int set_surrounding_text_call_count_;
  int process_key_event_call_count_;
  int reset_call_count_;
  InputContext last_text_input_context_;
  std::string last_activated_property_;
  std::u16string last_set_surrounding_text_;
  uint32_t last_set_surrounding_cursor_pos_;
  uint32_t last_set_surrounding_anchor_pos_;
  std::unique_ptr<ui::KeyEvent> last_processed_key_event_;
  KeyEventDoneCallback last_passed_callback_;
  std::string active_component_id_;
};

}  // namespace ash

#endif  // UI_BASE_IME_ASH_MOCK_IME_ENGINE_HANDLER_H_


text:
var propagate = require('../../../../lib/factory-granny/prototypes/propagate')

describe('FactoryGranny#propagate', function () {
  var FactoryGranny, FactoryGrannyStatic, subject

  beforeEach(function () {
    FactoryGranny = Factories.FactoryGranny.build()
    FactoryGrannyStatic = Factories.FactoryGranny.traits.static.build()

    propagate(FactoryGranny)

    subject = FactoryGranny.prototype.propagate
  })

  it('returns a constructor for the object with static properties',
  function () {
    subject.call(FactoryGrannyStatic)

    var target = FactoryGrannyStatic.traits.name

    expect(target.sequences).to.eql({
      a: 1,
      aa: 1
    })

    expect(target.opts).to.eql({
      b: 2
    })

    expect(target.attrs).to.eql({
      c: 3
    })

    expect(target._static).to.have.key('attr1')
  })
})


text:
import {Column, Entity, PrimaryGeneratedColumn} from "../../../../src";

@Entity("Foo")
export class FooEntity {

    @PrimaryGeneratedColumn()
    id: number;

    @Column("datetime2", { precision: 0 })
    date: Date;
}


text:
package mesh

import (
	"fmt"
	"math"

	"github.com/DexterLB/traytor/maths"
	"github.com/DexterLB/traytor/ray"
)

// BoundingBox represents a cuboid which surrounds a part of the mesh.
// The points in the cuboid are those (x, y, z), for which is true:
// MinVolume[0] < x < MaxVolume[0]
// MinVolume[1] < y < MaxVolume[1]
// MinVolume[2] < z , MaxVolume[2]
type BoundingBox struct {
	MaxVolume, MinVolume [3]float64
}

// NewBoundingBox creates a bounding box with no volume (min > max)
func NewBoundingBox() *BoundingBox {
	return &BoundingBox{
		MinVolume: [3]float64{maths.Inf, maths.Inf, maths.Inf},
		MaxVolume: [3]float64{-maths.Inf, -maths.Inf, -maths.Inf},
	}
}

// AddPoint expands the volume of the box, if the point isn't already in the box
func (b *BoundingBox) AddPoint(point *maths.Vec3) {
	b.MinVolume[0] = math.Min(b.MinVolume[0], point.X)
	b.MinVolume[1] = math.Min(b.MinVolume[1], point.Y)
	b.MinVolume[2] = math.Min(b.MinVolume[2], point.Z)

	b.MaxVolume[0] = math.Max(b.MaxVolume[0], point.X)
	b.MaxVolume[1] = math.Max(b.MaxVolume[1], point.Y)
	b.MaxVolume[2] = math.Max(b.MaxVolume[2], point.Z)
}

// Inside checks if a point is inside the box
func (b *BoundingBox) Inside(point *maths.Vec3) bool {
	return (maths.Between(b.MinVolume[0], b.MaxVolume[0], point.X) &&
		maths.Between(b.MinVolume[1], b.MaxVolume[1], point.Y) &&
		maths.Between(b.MinVolume[2], b.MaxVolume[2], point.Z))
}

// otherAxes returns the two other axis of the given and we can get (0, 1, 2), (1, 0, 2), (2, 0, 1)
// if axis is the first of the tree, otherAxis1 is the second, and otherAxis2 the third
func otherAxes(axis int) (int, int) {
	var otherAxis1, otherAxis2 int
	if axis == 0 {
		otherAxis1 = 1
	} else {
		otherAxis1 = 0
	}
	if axis == 2 {
		otherAxis2 = 1
	} else {
		otherAxis2 = 2
	}
	return otherAxis1, otherAxis2
}

// IntersectAxis checks whether there's interaction between the ray and the box.
func (b *BoundingBox) IntersectAxis(ray *ray.Ray, axis int) bool {
	directions := [3]float64{ray.Direction.X, ray.Direction.Y, ray.Direction.Z}
	start := [3]float64{ray.Start.X, ray.Start.Y, ray.Start.Z}

	// if the ray isn't pointing at the box there wouldn't be an intersection
	if (directions[axis] > 0 && start[axis] > b.MaxVolume[axis]) ||
		(directions[axis] < 0 && start[axis] < b.MinVolume[axis]) {
		return false
	}
	// or if the ray isn't moving in this direction at all
	if math.Abs(directions[axis]) < maths.Epsilon {
		return false
	}
	// we take the other two axes
	otherAxis1, otherAxis2 := otherAxes(axis)

	multiplier := ray.Inverse[axis]
	var intersectionX, intersectionY float64

	distance := (b.MinVolume[axis] - start[axis]) * multiplier
	if distance < 0 {
		return false
	}

	intersectionX = start[otherAxis1] + directions[otherAxis1]*distance
	if maths.Between(b.MinVolume[otherAxis1], b.MaxVolume[otherAxis1], intersectionX) {
		intersectionY = start[otherAxis2] + directions[otherAxis2]*distance
		if maths.Between(b.MinVolume[otherAxis2], b.MaxVolume[otherAxis2], intersectionY) {
			return true
		}
	}

	distance = (b.MaxVolume[axis] - start[axis]) * multiplier
	if distance < 0 {
		return false
	}
	intersectionX = start[otherAxis1] + directions[otherAxis1]*distance
	if maths.Between(b.MinVolume[otherAxis1], b.MaxVolume[otherAxis1], intersectionX) {
		intersectionY = start[otherAxis2] + directions[otherAxis2]*distance
		if maths.Between(b.MinVolume[otherAxis2], b.MaxVolume[otherAxis2], intersectionY) {
			return true
		}
	}
	return false
}

// Intersect check if a ray intersects the bounding box
func (b *BoundingBox) Intersect(ray *ray.Ray) bool {
	if b.Inside(&ray.Start) {
		return true
	}
	return (b.IntersectAxis(ray, maths.Ox) || b.IntersectAxis(ray, maths.Oy) || b.IntersectAxis(ray, maths.Oz))
}

// IntersectTriangle checks if the bounding box intersects with a triangle
// 1) To have a vertex in the box
// 2) The edge of the triangle intersects with the box
// 3) The middle of the triangle to be inside the box, while the vertices aren't
func (b *BoundingBox) IntersectTriangle(A, B, C *maths.Vec3) bool {
	if b.Inside(A) || b.Inside(B) || b.Inside(C) {
		return true
	}
	// we construct the ray from A->B, A->C, etc and check whether it intersects with the box
	triangle := [3]*maths.Vec3{A, B, C}
	ray := &ray.Ray{}
	for rayStart := 0; rayStart < 3; rayStart++ {
		for rayEnd := rayStart + 1; rayEnd < 3; rayEnd++ {
			ray.Start = *(triangle[rayStart])
			ray.Direction = *maths.MinusVectors(triangle[rayEnd], triangle[rayStart])
			ray.Init()
			// Check if there's intersection between AB and the box (example)
			if b.Intersect(ray) {
				// we check whether there's intersection between BA and the Box too
				// to be sure the edge isn't outside the box
				//    _____
				//    |    | <----AB there is intersection, but BA----->
				//    |____|
				ray.Start = *triangle[rayEnd]
				ray.Direction = *maths.MinusVectors(triangle[rayStart], triangle[rayEnd])
				ray.Init()
				if b.Intersect(ray) {
					return true
				}
			}
		}
	}
	// we have to check if the inside of the triangle intersects with the box
	AB := maths.MinusVectors(B, A)
	AC := maths.MinusVectors(C, A)
	ABxAC := maths.CrossProduct(AB, AC)
	distance := maths.DotProduct(A, ABxAC)
	rayEnd := &maths.Vec3{}

	for edgeMask := 0; edgeMask < 7; edgeMask++ {
		for axis := uint(0); axis < 3; axis++ {
			if edgeMask&(1<<axis) != 0 {
				continue
			}

			if edgeMask&1 != 0 {
				ray.Start.X = b.MaxVolume[0]
			} else {
				ray.Start.X = b.MinVolume[0]
			}

			if edgeMask&2 != 0 {
				ray.Start.Y = b.MaxVolume[1]
			} else {
				ray.Start.Y = b.MinVolume[1]
			}

			if edgeMask&4 != 0 {
				ray.Start.Z = b.MaxVolume[2]
			} else {
				ray.Start.Z = b.MinVolume[2]
			}

			*rayEnd = ray.Start
			rayEnd.SetDimension(int(axis), b.MaxVolume[axis])

			if (maths.DotProduct(&ray.Start, ABxAC)-distance)*(maths.DotProduct(rayEnd, ABxAC)-distance) <= 0 {
				ray.Direction = *maths.MinusVectors(rayEnd, &ray.Start)
				ray.Init()
				intersected, distance := IntersectTriangle(ray, A, B, C)
				if intersected && distance < 1.0000001 {
					return true
				}
			}
		}
	}

	return false
}

// Split returns two new bounding boxes which are the result of spliting the original on the given axis and median
func (b *BoundingBox) Split(axis int, median float64) (*BoundingBox, *BoundingBox) {
	left := &BoundingBox{}
	*left = *b
	right := &BoundingBox{}
	*right = *b
	left.MaxVolume[axis] = median
	right.MinVolume[axis] = median
	return left, right
}

// IntersectWall checks if a ray intersects a wall inside the bounding box
// (the wall is defined by the axis and median, as with Split)
func (b *BoundingBox) IntersectWall(axis int, median float64, ray *ray.Ray) bool {
	directions := [3]float64{ray.Direction.X, ray.Direction.Y, ray.Direction.Z}
	start := [3]float64{ray.Start.X, ray.Start.Y, ray.Start.Z}
	if math.Abs(directions[axis]) < maths.Epsilon {
		return (math.Abs(start[axis]-median) < maths.Epsilon)
	}

	otherAxis1, otherAxis2 := otherAxes(axis)
	distance := median - start[axis]
	directionInAxis := ray.Inverse[axis]

	if (distance * directionInAxis) < 0 {
		return false
	}

	fac := distance * directionInAxis
	distanceOnAxis1 := start[otherAxis1] +
		directions[otherAxis1]*fac
	if b.MinVolume[otherAxis1] <= distanceOnAxis1 &&
		distanceOnAxis1 <= b.MaxVolume[otherAxis1] {

		distanceOnAxis2 := start[otherAxis2] +
			directions[otherAxis2]*fac
		return b.MinVolume[otherAxis2] <= distanceOnAxis2 &&
			distanceOnAxis2 <= b.MaxVolume[otherAxis2]
	}
	return false
}

// String returns the string representation of the boundingBox in the form of bbox[min: _, max: _]
func (b *BoundingBox) String() string {
	return fmt.Sprintf("bbox[min: %s, max: %s]", maths.NewVec3Array(b.MinVolume), maths.NewVec3Array(b.MaxVolume))
}


text:
/* eslint-env mocha */
import { expect } from 'chai';
import getStyles from '../../src/checkbox-group/get-styles';
import styles from '../../src/checkbox-group/styles';

describe('CheckboxGroup.getStyles', () => {
  describe('buttons', () => {
    it('should get styles', () => {
      const style = getStyles.buttons();

      expect(style).to.deep.equal(styles.buttons);
    });

    it('should combine styles', () => {
      const style = getStyles.buttons({ color: 'red' });

      expect(style).to.have.property('color', 'red');
    });
  });

  describe('label', () => {
    it('should get styles', () => {
      const style = getStyles.label();

      expect(style).to.deep.equal(styles.label);
    });

    it('should combine styles', () => {
      const style = getStyles.label({ color: 'red' });

      expect(style).to.have.property('color', 'red');
    });
  });

  describe('error', () => {
    it('should get styles', () => {
      const style = getStyles.error();

      expect(style).to.deep.equal(styles.error);
    });

    it('should combine styles', () => {
      const style = getStyles.error({ color: 'red' });

      expect(style).to.have.property('color', 'red');
    });
  });
});


text:
namespace Stripe
{
    using System;
    using Newtonsoft.Json;
    using Stripe.Infrastructure;

    public class AccountCompanyOwnershipDeclaration : StripeEntity<AccountCompanyOwnershipDeclaration>
    {
        /// <summary>
        /// The Unix timestamp marking when the beneficial owner attestation was made.
        /// </summary>
        [JsonProperty("date")]
        [JsonConverter(typeof(UnixDateTimeConverter))]
        public DateTime? Date { get; set; }

        /// <summary>
        /// The IP address from which the beneficial owner attestation was made.
        /// </summary>
        [JsonProperty("ip")]
        public string Ip { get; set; }

        /// <summary>
        /// The user-agent string from the browser where the beneficial owner attestation was made.
        /// </summary>
        [JsonProperty("user_agent")]
        public string UserAgent { get; set; }
    }
}