text:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ATTENTION: THIS CLASS IS VERY BAD WRITTEN
 */
@SuppressWarnings("Duplicates")
public class Cities {
    private static final String MAIL_ADRESS = "metinkale38@gmail.com";
    private static AtomicInteger id = new AtomicInteger();
    private static Map<String, Geocoder> mGeocodings = new ConcurrentHashMap<>();
    private static Map<Integer, Entry> mEntries = Collections.synchronizedNavigableMap(new TreeMap<>());
    private static AtomicInteger mTaskCounter = new AtomicInteger();
    //only increase poolsize if you want to speedup network requests, but use 1 for final version to keep ids consistent
    private static Executor mWorker = new ThreadPoolExecutor(1, 1,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>()) {
        @Override
        public void execute(Runnable command) {
            if (getMaximumPoolSize() == 1) {
                command.run();
                return;
            }
            mTaskCounter.incrementAndGet();
            super.execute(() -> {
                command.run();
                mTaskCounter.decrementAndGet();
            });
        }
    };

    private static class Entry {
        int id;
        int parent;
        double lat;
        double lng;
        String key;
        String name;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        Locale.setDefault(Locale.ENGLISH);

        byte[] encoded;
        try {
            encoded = Files.readAllBytes(Paths.get("geocodings.geo"));
            mGeocodings = new Gson().fromJson(new String(encoded, StandardCharsets.UTF_8), new TypeToken<ConcurrentHashMap<String, Geocoder>>() {
            }.getType());
        } catch (IOException e) {
            // e.printStackTrace();
            mGeocodings = new ConcurrentHashMap<>();
        }

        while (mTaskCounter.get() > 0) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        long time = System.currentTimeMillis();
        System.out.println("Start geocode()");
        geocode();
        System.out.println("geocode() - finished in " + (System.currentTimeMillis() - time) + " ms");

        time = System.currentTimeMillis();
        System.out.println("Start export()");
        export();

        System.out.println("export() - finished in " + (System.currentTimeMillis() - time) + " ms");
        if (mTaskCounter.get() == 0) System.exit(0);
    }

    private static void export() throws UnsupportedEncodingException {

        new File("out.tsv").delete();
        try (PrintWriter out = new PrintWriter("out.tsv", "utf-8")) {
            for (Entry e : mEntries.values()) {
                out.print(e.id);
                out.print('\t');
                out.print(e.parent);
                out.print('\t');
                if (e.lat != 0) out.print(e.lat);
                out.print('\t');
                if (e.lng != 0) out.print(e.lng);
                out.print('\t');
                if (e.key != null) out.print(e.key);
                out.print('\t');
                out.print(e.name.trim().replace("  ", " ").replace("( ", "(").replace(" )", ")"));
                out.println();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        try (PrintWriter out = new PrintWriter("geocodings.geo")) {
            out.write(new Gson().toJson(mGeocodings));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void fetchIGMG() {
        String data = HTTP.get("https://live.igmgapp.org:8091/api/Calendar/GetPrayerTimesCities?prefLocale=DE");

        class City {
            private String name;
            private int id;
            double lat;
            double lng;
        }

        String[] cities = data.replace("\"list\":", "").split("},");
        HashMap<String, List<City>> map = new HashMap<>();
        for (String city : cities) {
            String[] fields = city.split(",");
            City entity = new City();
            for (String field : fields) {
                String value = field.substring(field.indexOf(":") + 1).replace("\"", "").split("}")[0].trim();
                if (field.contains("\"id\""))
                    entity.id = Integer.parseInt(value);
                else if (field.contains("\"name\""))
                    entity.name = value;
                else if (field.contains("\"latitude\""))
                    entity.lat = Double.parseDouble(value);
                else if (field.contains("\"longitude\""))
                    entity.lng = Double.parseDouble(value);
            }

            String country = entity.name.substring(entity.name.lastIndexOf("(") + 1);
            country = country.substring(0, 2);
            entity.name = entity.name.substring(0, entity.name.lastIndexOf(" "));

            if (!map.containsKey(country)) {
                map.put(country, new ArrayList<>());
            }
            map.get(country).add(entity);

        }

        for (String country : map.keySet()) {

            Entry parent = new Entry();
            parent.id = Cities.id.incrementAndGet();
            parent.parent = 0;
            parent.name = country;
            parent.key = null;
            parent.lat = 0;
            parent.lng = 0;
            mEntries.put(parent.id, parent);

            switch (parent.name) {
                case "BA":
                    parent.name = "Bosnien";
                    break;
                case "NL":
                    parent.name = "Niederlande";
                    break;
                case "DE":
                    parent.name = "Deutschland";
                    break;
                case "AT":
                    parent.name = "\u00d6sterreich";
                    break;
                case "AU":
                    parent.name = "Australien";
                    break;
                case "BE":
                    parent.name = "Belgien";
                    break;
                case "CA":
                    parent.name = "Kanada";
                    break;
                case "CH":
                    parent.name = "Schweiz";
                    break;
                case "DK":
                    parent.name = "D\u00e4nemark";
                    break;
                case "FR":
                    parent.name = "Frankreich";
                    break;
                case "GB":
                    parent.name = "Vereinigtes K\u00f6nigreich";
                    break;
                case "IT":
                    parent.name = "Italien";
                    break;
                case "LI":
                    parent.name = "Liechtenstein";
                    break;
                case "MK":
                    parent.name = "Mazedonien";
                    break;
                case "NO":
                    parent.name = "Norwegen";
                    break;
                case "SE":
                    parent.name = "Schweden";
                    break;
                case "US":
                    parent.name = "Vereinigte Staaten von Amerika";
                case "SG":
                    parent.name = "Singapur";
                case "TR":
                    parent.name = "Türkei";
                    break;
                case "JP":
                    parent.name = "Japan";
                    break;
                case "EN":
                    parent.name = "England";
                    break;
                case "MY":
                    parent.name = "Malaysia";
                    break;
                case "NZ":
                    parent.name = "Neuseeland";
                    break;
                default:
                    System.err.println("Unknown Country Code " + parent.name);
            }

            List<City> splits = map.get(country);
            for (City c : splits) {
                Entry e = new Entry();
                e.id = Cities.id.incrementAndGet();
                e.parent = parent.id;
                e.name = c.name;
                e.key = "" + c.id;
                e.lat = c.lat;
                e.lng = c.lng;
                mEntries.put(e.id, e);

            }

        }
    }

    private static void fetchNVCCountries() {
        String data = HTTP.get("http://namazvakti.com/CountryList.php");
        Entry nvc = new Entry();
        nvc.id = Cities.id.incrementAndGet();
        nvc.parent = 0;
        nvc.name = "NamazVakti.com";
        nvc.key = null;
        nvc.lat = 0;
        nvc.lng = 0;
        mEntries.put(nvc.id, nvc);

        for (data = data.substring(data.indexOf("StateList.php?"));
             data.contains("StateList.php?");
             data = data.substring(i(data.indexOf("StateList.php?")))) {
            data = data.substring(1);
            String _id = data.substring(data.indexOf("=") + 1);
            _id = _id.substring(0, _id.indexOf("\""));
            int id = Integer.parseInt(_id);
            String name = data.substring(data.indexOf("<b>") + 3);
            name = name.substring(0, name.indexOf("<"));
            name = name.replace(" ", " ").trim();

            Entry e = new Entry();
            e.id = Cities.id.incrementAndGet();
            e.parent = nvc.id;
            e.name = name;
            e.key = null;
            e.lat = 0;
            e.lng = 0;
            mEntries.put(e.id, e);

            fetchNVCStates(id, e);
        }

    }

    private static void fetchNVCStates(int parentId, Entry parent) {
        String data = HTTP.get("http://namazvakti.com/StateList.php?countryID=" + parentId);
        for (data = data.substring(data.indexOf("CityList.php?"));
             data.contains("CityList.php?");
             data = data.substring(i(data.indexOf("CityList.php?")))) {
            data = data.substring(1);
            String _id = data.substring(data.indexOf("=") + 1);
            String state = _id.substring(_id.indexOf("state=") + 6);
            state = state.substring(0, state.indexOf("\""));
            _id = _id.substring(0, _id.indexOf("&"));
            int id = Integer.parseInt(_id);
            String name = data.substring(data.indexOf("<b>") + 3);
            name = name.substring(0, name.indexOf("<"));
            name = name.replace(" ", " ").trim();

            Entry e = new Entry();
            e.id = Cities.id.incrementAndGet();
            e.parent = parent.id;
            e.name = name;
            e.key = null;
            e.lat = 0;
            e.lng = 0;
            mEntries.put(e.id, e);

            fetchNVCCitites(id, state, e);
        }
    }

    private static void fetchNVCCitites(int country, String state, Entry parent) {
        String data = HTTP.get("http://namazvakti.com/CityList.php?countryID=" + country + "&state=" + URLEncoder.encode(state));
        data = data.substring(data.indexOf("stateTitle"));
        for (data = data.substring(data.indexOf("Main.php?cityID"));
             data.contains("Main.php?cityID");
             data = data.substring(i(data.indexOf("Main.php?cityID")))) {
            data = data.substring(1);
            String _id = data.substring(data.indexOf("=") + 1);
            _id = _id.substring(0, _id.indexOf("\""));
            int id = Integer.parseInt(_id);
            String name = data.substring(data.indexOf("<b>") + 3);
            name = name.substring(0, name.indexOf("<"));
            name = name.replace(" ", " ").trim();

            Entry e = new Entry();
            e.id = Cities.id.incrementAndGet();
            e.parent = parent.id;
            e.name = name;
            e.key = "N_" + id;
            e.lat = 0;
            e.lng = 0;
            mEntries.put(e.id, e);
        }
    }

    private static void fetchSemerkand() {
        try {
            String Url = "http://semerkandtakvimi.semerkandmobile.com/locations";
            String data = HTTP.get(Url);
            List<Semerkand> semerkand = new Gson().fromJson(data,
                    new TypeToken<List<Semerkand>>() {
                    }.getType());

            Entry sem = new Entry();
            sem.id = Cities.id.incrementAndGet();
            sem.parent = 0;
            sem.name = "Semerkandtakvimi.com";
            sem.key = null;
            sem.lat = 0;
            sem.lng = 0;
            mEntries.put(sem.id, sem);

            for (Semerkand country : semerkand) {
                Entry parent = new Entry();
                parent.id = Cities.id.incrementAndGet();
                parent.parent = sem.id;
                parent.name = country.Name;
                parent.key = null;
                parent.lat = 0;
                parent.lng = 0;
                mEntries.put(parent.id, parent);

                for (Semerkand city : country.Cities) {
                    if (city.Districts.length != 0) {
                        Entry parent2 = new Entry();
                        parent2.id = Cities.id.incrementAndGet();
                        parent2.parent = parent.id;
                        parent2.name = city.Name;
                        parent2.key = null;
                        parent2.lat = 0;
                        parent2.lng = 0;
                        mEntries.put(parent2.id, parent2);
                        for (Semerkand county : city.Districts) {
                            Entry e = new Entry();
                            e.id = Cities.id.incrementAndGet();
                            e.parent = parent2.id;
                            e.name = county.Name;
                            e.key = "S_" + 'd' + county.Id;
                            e.lat = 0;
                            e.lng = 0;
                            mEntries.put(e.id, e);
                        }
                    } else {
                        Entry e = new Entry();
                        e.id = Cities.id.incrementAndGet();
                        e.parent = parent.id;
                        e.name = city.Name;
                        e.key = "S_" + 'c' + city.Id;
                        e.lat = 0;
                        e.lng = 0;
                        mEntries.put(e.id, e);

                    }
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    static class Semerkand {
        int Id;
        String Name;
        Semerkand[] Cities = new Semerkand[0];
        Semerkand[] Districts = new Semerkand[0];
    }

    private static void geocode(Entry e, boolean onlyCache) {
        String name = e.name;

/*        while ((parent = mEntries.get(parent.parent)) != null && parent.parent != 0) {
            name = parent.name + ", " + name;
        }
*/
        if (mGeocodings.containsKey(name)) {
            Geocoder gc = mGeocodings.get(name);
            e.lat = gc.lat;
            e.lng = gc.lon;
            return;
        }

        String url = "https://nominatim.openstreetmap.org/search?q="
                + URLEncoder.encode(name.replace("+", " ")
                .replace("ABD,", "USA,"))
                + "&format=json&limit=1&email=" + MAIL_ADRESS + "&namedetails=1";
        String data = HTTP.get(url);

        List<Geocoder> result = null;
        try {
            result = new Gson().fromJson(data, new TypeToken<List<Geocoder>>() {
            }.getType());
        } catch (Exception ignored) {
        }
        if (result != null && result.size() != 0) {
            Geocoder gc = result.get(0);
            e.lat = gc.lat;
            e.lng = gc.lon;
            mGeocodings.put(name, gc);
        }
    }

    private static String extract(String data, String s) {
        data = data.substring(data.indexOf(s));
        data = data.substring(data.indexOf("=") + 2);
        data = data.substring(0, data.indexOf("\""));
        return data;
    }

    private static void geocodeNVC(Entry entry) {
        String name = entry.name;
        Entry parent = entry;
        while ((parent = mEntries.get(parent.parent)) != null && parent.parent != 0) {
            name = parent.name + ", " + name;
        }

        if (mGeocodings.containsKey(name)) {
            Geocoder gc = mGeocodings.get(name);
            entry.lat = gc.lat;
            entry.lng = gc.lon;
            return;
        }

        try {
            String data = HTTP.get("http://namazvakti.com/XML.php?cityID=" + entry.key.substring(2));
            String arzDer = extract(data, "arzDer");
            String arzDak = extract(data, "arzDak");
            String arzYon = extract(data, "arzYon");
            String tulDer = extract(data, "tulDer");
            String tulDak = extract(data, "tulDak");
            String tulYon = extract(data, "tulYon");

            double lat = (arzYon.endsWith("N") ? 1 : -1) * (Double.parseDouble(arzDer) + Double.parseDouble(arzDak) / 60.0);
            double lng = (tulYon.endsWith("E") ? 1 : -1) * (Double.parseDouble(tulDer) + Double.parseDouble(tulDak) / 60.0);
            entry.lat = lat;
            entry.lng = lng;

            Geocoder gc = new Geocoder();
            gc.lat = lat;
            gc.lon = lng;
            mGeocodings.put(name, gc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void geocode() {
        int size = mEntries.values().size();
        AtomicInteger count = new AtomicInteger();
        for (Entry e : mEntries.values()) {
            if ((e.lat != 0 && e.lng != 0) || e.key == null) {
                count.incrementAndGet();
                continue;
            }

            if (e.key.startsWith("N_")) {
                mWorker.execute(() -> {
                    geocode(e, true);
                    if (e.lat == 0 && e.lng == 0)
                        geocodeNVC(e);
                });
            } else {
                mWorker.execute(() -> {
                    geocode(e, false);
                    System.out.println(count.incrementAndGet() + "/" + size);
                });

            }
        }

        while (mTaskCounter.get() != 0) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static class Ilce {
        List<Sehir> ilceler = new ArrayList<>();
    }

    private static class Sehirler {
        List<Sehir> sehirler = new ArrayList<>();
    }

    private static class Sehir {
        String adi;
        int id;
    }

    private static class Geocoder {
        double lat;
        double lon;
    }

    public static int i(int i) {
        return Math.max(i, 0);
    }
}


text:
<?php
// DO NOT EDIT! Generated by Protobuf-PHP protoc plugin @package_version@// Source: riak.proto
//   Date: 2015-01-16 03:40:25

namespace Riak\Client\ProtoBuf {

    class RpbYokozunaSchemaGetReq extends \DrSlump\Protobuf\Message
    {
        /** @var \DrSlump\Protobuf\Descriptor */
        protected static $__descriptor;
        /** @var \Closure[] */
        protected static $__extensions = array();

        public static function descriptor()
        {
            $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, '.RpbYokozunaSchemaGetReq');

            // required bytes name = 1
            $f = new \DrSlump\Protobuf\Field();
            $f->number = 1;
            $f->name   = "name";
            $f->rule   = \DrSlump\Protobuf\Protobuf::RULE_REQUIRED;
            $f->type   = \DrSlump\Protobuf\Protobuf::TYPE_BYTES;

            $descriptor->addField($f);

            foreach (self::$__extensions as $cb) {
                $descriptor->addField($cb(), true);
            }

            return $descriptor;
        }

        /**
         * Check if "name" has a value
         *
         * @return boolean
         */
        public function hasName()
        {
            return isset($this->name);
        }

        /**
         * Clear "name" value
         */
        public function clearName()
        {
            unset($this->name);
        }

        /**
         * Get "name" value
         * @return string                  *
         *
         */
        public function getName()
        {
            return $this->name;
        }

        /**
         * Set "name" value
         *
         * @param string $value
         */
        public function setName($value)
        {
            return $this->name = $value;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from openstack_dashboard.test.test_data import utils

def load_test_data(load_onto=None):
    from manila_ui.test.test_data import keystone_data as manila_keystone_data
    from openstack_dashboard.test.test_data import ceilometer_data
    from openstack_dashboard.test.test_data import cinder_data
    from openstack_dashboard.test.test_data import exceptions
    from openstack_dashboard.test.test_data import glance_data
    from openstack_dashboard.test.test_data import heat_data
    from openstack_dashboard.test.test_data import keystone_data
    from openstack_dashboard.test.test_data import neutron_data
    from openstack_dashboard.test.test_data import nova_data
    from openstack_dashboard.test.test_data import sahara_data
    from openstack_dashboard.test.test_data import swift_data
    from openstack_dashboard.test.test_data import trove_data

    # The order of these loaders matters, some depend on others.
    loaders = (
        exceptions.data,
        keystone_data.data,
        glance_data.data,
        nova_data.data,
        cinder_data.data,
        neutron_data.data,
        swift_data.data,
        heat_data.data,
        ceilometer_data.data,
        trove_data.data,
        sahara_data.data,
        manila_keystone_data.data,
    )
    if load_onto:
        for data_func in loaders:
            data_func(load_onto)
        return load_onto
    else:
        return utils.TestData(*loaders)


text:
@implementation ComGoodowRealtimeStoreImplCollaborativeStringImpl (Adapter)
- (id<GDCRegistration>)onTextDeleted:(void (^)(id <GDSTextDeletedEvent>))handler {
  return (id<GDCRegistration>)[self onTextDeletedWithComGoodowRealtimeCoreHandler:handler];
}

- (id<GDCRegistration>)onTextInserted:(void (^)(id <GDSTextInsertedEvent>))handler {
  return (id<GDCRegistration>)[self onTextInsertedWithComGoodowRealtimeCoreHandler:handler];
}

- (void)append:(NSString *)text {
  [self appendWithNSString:text];
}

- (void)insertString:(int)index text:(NSString *)text {
  [self insertStringWithInt:index withNSString:text];
}

- (id <GDSIndexReference>)registerReference:(int)index canBeDeleted:(BOOL)canBeDeleted {
  return (id <GDSIndexReference>)[self registerReferenceWithInt:index withBoolean:canBeDeleted];
}

- (void)removeRange:(int)startIndex endIndex:(int)endIndex {
  [self removeRangeWithInt:startIndex withInt:endIndex];
}

- (void)setText:(NSString *)text {
  [self setTextWithNSString:text];
}

@end


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="co.navdeep.toptensongs.app.SearchFieldFragment">

        <EditText
            android:id="@+id/search_box"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Search (min. 3 char)"
            android:singleLine="true"
            />

</FrameLayout>


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class TimetableListItem extends Component {
    constructor(props) {
        super(props);
    }

    renderItem() {
        let id = 0;
        return (

                {this.props.list.map(item => {
                    id++;
                    return (
                    <li key={`i${id}`} className="list_item">

                             {item.time.from} - {item.time.to}

                            {item.title}

                            {item.location}

                            {item.teacher}

                            {item.group.replace(/[;,]/g, ', ')}

                    )
                })}

        )
    }

    render() {
        return (
            this.renderItem()
        );
    }
}

export default TimetableListItem;


text:
SYNONYM

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

#### Published in
Can. J. Bot. 52: 1684 (1974)

#### Original name
Ceratocystis minima Olchow. & J. Reid, 1974

### Remarks
null


text:
title: Las Vegas Strip Buffets
author: Alexis Jackson
header:
  image: /assets/images/cover/vegas.jpg
  caption: "Mirage Hotel"
categories:
  - Reviews
tags:
  - Buffets
  - Las-Vegas
  - Le Village Buffet
  - Wicked Spoon
  - Cravings
  - The Buffet at Monte Carlo
  - Beach Cafe
---

Whilst in Vegas, we decided to try a variety of buffets. One buffet on this list we visited when we were here this last June, but the experience was memorable enough that I've decided to note it here as well.

### Le Village Buffet at Paris Casino

Paris was easily number two for us, with a charming, quiet atmosphere and great food. The layout is not the typical wide open room of other Vegas Strip buffets, and feels somewhat more like a restaurant. Everything we sampled was delicious, from the chicken breast and prime rib, to the sushi, and everything in between. We went for a brunch, around 11AM on a weekday, and there was no line. The only negative we experienced was that our waitress rarely came by the table to make sure we had enough to drink (once every 25 - 30 minutes).

### Cravings at the Mirage Casino

This buffet was more in the middle of quality - not bad, not great. The food was all good, but nothing stood out as fantastic. Nor was anything terrible. Our waitress was excellent! She came by every 5 to 10 minutes to clear plates and see if we needed anything, and was very upbeat and positive. Drinks here are self serve which (would have come in handy at Paris), and your meal includes free tap beer and select wines.

### Wicked Spoon at Cosmopolitan

Wicked Spoon takes the cake for us on food quality out of the buffets we've visited thus far. We decided to go for a Sunday Brunch as we'd read that was the best time to go, and we were not disappointed. Many of the dishes were excellent, and the pumpkin pancakes and french toast stand out above any I've had before. The only downside was that it looked like they make artificial lines. We arrived at 10AM and waited roughly 45 minutes to be sat, even though half of the tables were open and clean. Being a Sunday morning brunch, I would be surprised if being understaffed was the reason for keeping so many tables open. If you decide to try a weekend brunch here, try to arrive at least by 10AM. When we left around 11:30AM, both lines (line to pay and line to be seated) were twice as long as when we arrived. I wouldn't normally agree to wait 45 minutes in line for a buffet, but I'd make an exception for Wicked Spoon.

### The Buffet at Monte Carlo

We visited this buffet while in Vegas in June, on a whim after playing BlackJack in the casino. There was no line and the dining area was pretty empty - which should have told us something considering it was dinner time. We sampled a fairly wide variety of dishes looking for something decent or worth eating. The prime rib was more like rubber than meat. The crab legs were all over cooked, and a lot of the meat was wasted. Gravies were bland and some of the food was even cold. Monte Carlo's buffet unfortunately is not one we'll be visiting again, nor would we recommend it.

### Beach Cafe at Tropicana

Beach Cafe got the best of us, in that it is only a buffet for breakfast (and a tiny one at that). We wondered over for dinner figuring it was worth a shot since it was within walking distance of our hotel, and found out that lunch and dinner are a la carte. This one wasn't terrible, and none of the food was bad, but I don't believe we'll go back. The chicken soup recommended to us was comparable to Campbell's, and the french dip sandwich was bland and depended too heavily on bland, watery gravy. They had a french toast item that was decent, but a little over the top for my taste (plus side was that it came with plenty of fresh berries!).

### General Tips

- Rather than tipping at the register, tip cash at the table. We had some servers that deserved more than the typical 18% gratuity at the register, and some that barely earned the 18%.
- If going for a weekend brunch, try to beat the hangover and get there before 10AM. You still may have a decent wait, but it won't be two hours. No one wants to wait that long when they're hung over.


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

<faces-config
	version="2.2"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_2.xsd">

	<application>
		<locale-config>
			<default-locale>en</default-locale>
			<supported-locale>bg</supported-locale>
			<supported-locale>de</supported-locale>
			<supported-locale>en</supported-locale>
			<supported-locale>fr</supported-locale>
			<supported-locale>tr</supported-locale>
		</locale-config>

		<!--
			In JSF, you can't depend on the standard ServletContextListeners
			to capture postConstruct and preDestroy at the correct times.
		 -->
		<system-event-listener>
			<!-- Perform custom postConstruct after application has started -->
			<system-event-class>javax.faces.event.PostConstructApplicationEvent</system-event-class>
			<system-event-listener-class>nam.ui.event.PostConstructEventListener</system-event-listener-class>
		</system-event-listener>

		<system-event-listener>
			<!-- Perform custom preDestroy before application is brought down -->
			<system-event-class>javax.faces.event.PreDestroyApplicationEvent</system-event-class>
			<system-event-listener-class>nam.ui.event.PreDestroyEventListener</system-event-listener-class>
		</system-event-listener>

		<!--
		<view-handler>nam.ui.CustomViewHandler</view-handler>
		-->

		<!--
		<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
		<el-resolver>org.jboss.seam.el.SeamELResolver</el-resolver>
		<navigation-handler>org.jboss.seam.jsf.SeamNavigationHandler</navigation-handler>
		<message-bundle>org.jboss.seam.core.SeamResourceBundle</message-bundle>
		-->
	</application>

	<!--
	<managed-bean>
		<managed-bean-name>admin.permissionListSorter</managed-bean-name>
		<managed-bean-class>nam.ui.permission.PermissionListSorter</managed-bean-class>
		<managed-bean-scope>view</managed-bean-scope>
	</managed-bean>
	-->

	<lifecycle>
		<!--
		<phase-listener>org.jboss.seam.jsf.SeamPhaseListener</phase-listener>
		<phase-listener>org.jboss.seam.document.DocumentStorePhaseListener</phase-listener>
		-->
		<phase-listener>nam.ui.TracingListener</phase-listener>
		<phase-listener>nam.ui.TreePrinter</phase-listener>
	</lifecycle>

	<!--
	<render-kit>
		<render-kit-id>Aries</render-kit-id>
		<renderer>
			<description>@author Tom Fisher</description>
			<component-family>org.aries.Panel</component-family>
			<renderer-type>org.richfaces.StatusRenderer</renderer-type>
			<renderer-class>org.aries.ui.MyPanelGridRenderer</renderer-class>
			<renderer-extension>
				<cdk:renders-children>false</cdk:renders-children>
			</renderer-extension>
		</renderer>
	</render-kit>
	-->

	<!--
	<component>
		<component-type>org.aries.Panel</component-type>
		<component-class>org.aries.ui.MyPanelGridRenderer</component-class>
		<attribute>
			<attribute-name>backgroundColor</attribute-name>
			<attribute-class>java.lang.String</attribute-class>
		</attribute>
	</component>
	-->

		<!--
		<property>
			<display-name>Component Identifier</display-name>
			<icon />
			<property-name>id</property-name>
			<property-class>java.lang.String</property-class>
			<property-extension>
				<cdk:generate>false</cdk:generate>
				<cdk:hidden>false</cdk:hidden>
				<cdk:literal>false</cdk:literal>
				<cdk:pass-through>false</cdk:pass-through>
				<cdk:read-only>false</cdk:read-only>
				<cdk:required>false</cdk:required>
			</property-extension>
		</property>
		-->

</faces-config>


text:
package photoeffect.effect.otherblur;

import jadex.bridge.IInternalAccess;
import jadex.bridge.service.annotation.Service;
import jadex.bridge.service.annotation.ServiceComponent;

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;

import measure.generic.AbstractGenericProfiler;

@Service
public class EffectOtherBlurService extends AbstractGenericProfiler<BufferedImage> implements IEffectOtherBlur
{

    @ServiceComponent
    protected IInternalAccess agent;

    @Override
    protected BufferedImage internalModifyObject(BufferedImage image)
    {
        if (System.getProperty("loop") != null)
            for (long i = 0; i < 10000000000L; i++)
            {
                // approx 5secs
            }

        BufferedImage blurredImage = image.getSubimage(0, 0, image.getWidth(), image.getHeight());

        if (image != null)
        {
            float[] matrix = { 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, 0.111f, };

            BufferedImageOp op = new ConvolveOp(new Kernel(3, 3, matrix));
            op.filter(image, blurredImage);
        }

        if (System.getProperty("loop") != null)
            for (long i = 0; i < 10000000000L; i++)
            {
                // approx 5secs
            }

        return blurredImage;
    }

}


text:
var jobAutoSaveIntervalId = -1;

function onGarmentCostUpdate(costField, newCost, editable, estimate, total){
	var oldCost = $(costField).val() * 1;
	var garmentCount = getGarmentCount(estimate);
	var oldEstimate = $(estimate).val() * 1;
	var newEstimate = oldEstimate + 1 * newCost - oldCost;
	var editVal = $(editable).val() * 1;
	if(oldCost != newCost){
		if(oldEstimate == editVal){
			editVal = newEstimate;
			$(editable).val(editVal);
		}
		refreshEstimate(editVal, newEstimate, $(estimate).parent());
		$(costField).val(newCost);
		$(total).val(editVal * garmentCount).change();
	}
}

function updateLineTotal(sender, calculatorUrl, editable, estimate, total, cost){
	var editVal = $(editable).val() * 1;
	var costVal = $(cost).val() * 1;
	var totalVal = 0;
	var garmentCount = getGarmentCount(estimate);
	var estimateVal = 0;
	calculateTotalCore(calculatorUrl, garmentCount, getFrontPasses(), getBackPasses(), getSleevePasses(), function(data){
		var oldEstimate = $(estimate).children('.hidden-price').val() * 1;
		if(oldEstimate == editVal){
			editVal = 1 * data.result / garmentCount + costVal;
			$(editable).val(editVal);
		}
		refreshEstimate(editVal, 1 * data.result / garmentCount + costVal, estimate);
		var sizeSurChargeSum =getSizeSurChargeSum(sender);
		$(total).val((editVal * garmentCount)+ sizeSurChargeSum).change();
	});
	$(sender).closest('*[name="sizes"]').children('*[name="product-quantity"]:first').val(garmentCount);
}

function chooseEstimatePrice(element, event){
	event.preventDefault();
	$(element).parents('.price-select-container')
		.find('.unit_price')
			.val($(element).children('.hidden-price').val())
			.keyup();
	$(element).hide();

	return false;
}

var getTaxRate = function(){
	var taxRate = 0;
	if($('#jobIsTaxed').prop('checked')){
		taxRate = parseInt($('#tax_rate').val(), 10);
		taxRate = (typeof taxRate  === "number" && !isNaN(taxRate)) ? taxRate : 0;
	}
	return taxRate;
}

var calculateSalesTax = function(subTotal){
	return parseFloat((getTaxRate()/100 * subTotal).toFixed(2));
}

var setGrandTotal = function(subTotal){
	var gTotal = subTotal + calculateSalesTax(subTotal);
	$('#jobTotal').val(gTotal.toFixed(2)).change();
}

var setCostOfGoodsSoldPercentage = function(costOfGoods){
	var totalBeforeTax = parseFloat($("#jobTotal" ).val());
	totalBeforeTax = (typeof totalBeforeTax  === "number" && !isNaN(totalBeforeTax)) ? totalBeforeTax : 0;
	//remove tax if necessary
	if($('#jobIsTaxed').prop('checked')){
		totalBeforeTax = totalBeforeTax / (getTaxRate()/100 + 1);
	}
	$('#jobCogPercentage').val(totalBeforeTax > 0 ?
		Math.round(parseFloat(((costOfGoods / totalBeforeTax).toFixed(2)) * 100)) : '');
}

var calculateJobTotal = function(){
	var jobTotal = 0;
	$('.auto_quote .part').each(function(index){
		var lineItemPrice = parseFloat($(this).val());
		lineItemPrice = (typeof lineItemPrice  === "number" && !isNaN(lineItemPrice)) ? lineItemPrice : 0;
		jobTotal += lineItemPrice;
	});
	$('#lines div[name="price-group"] .garment_part').each(function(index){ jobTotal += parseFloat($(this).val()); });
	setGrandTotal(jobTotal);
}

function addJobLine(sender, namePrefix, newJobLineUrl, productOptionsUrl, productFindUrl){
	var btn = $(sender);
	btn.button('loading');
	var count = $(sender).parents('.row').prev('#lines').children('.jobLines')
							.children('div[name="sizes"]').children('.jobLine').children('.part').size();
	$.ajax({
		url: newJobLineUrl,
		type: 'POST',
		data: {
			namePrefix: namePrefix,
			count: count,
		},
		success: function(data){
			var productsContainer = $(sender).parents('.gus-form').children('fieldset').find('#lines');
			$(data).appendTo(productsContainer);
			var div_id = $(data).find('.line_delete').parent().attr('id');
			$('#' + div_id).find('.item-select').autocomplete({
				'select': function(event, ui){
					$.getJSON( productOptionsUrl,{
							itemID: ui.item.id,
							namePrefix: namePrefix,
							count: count,
						},
						function(data){
							var colors = data.colors;
							var sizes = data.sizes;
							var cost = data.productCost;
							var selectElement = $('#' + div_id + ' .row div[name="color-group"]').find('.color-select:first-child');
							selectElement.empty();
							for(var color in colors){
								selectElement.append($('<option></option>').val(colors[color].ID).html(colors[color].TEXT));
							}
							selectElement.removeAttr('disabled');
							var jobSizeLine = $('#' + div_id + ' .row').children('.jobLine');
							jobSizeLine.addClass('hidden-size').removeClass('col-md-2')
										.children('.score_part').attr('disabled', true).val(0);
							jobSizeLine.children('.hidden_cost').val(cost);
							onGarmentCostUpdate($('#' + div_id).find('.product-cost')
								, cost, $('#' + div_id).find('.editable-price')
								, $('#' + div_id).find('.hidden-price')
								, $('#' + div_id).find('.garment_part')
							);
							for(var size in sizes){
								$('#' + div_id + ' .row').children('.' + div_id + sizes[size].ID)
								.removeClass('hidden-size')
								.addClass('col-md-2')
								.children('.score_part').removeAttr('disabled');
							}
							$('#' + div_id +' .row div[name="style-group"]').find('.hidden-style').val(ui.item.id);
						}
					);
				},
				'source': productFindUrl
			});
		},
	}).always(function(){ btn.button('reset'); });
}

function iconToPendingSave(submitInputGroup){
	return submitInputGroup.find('.glyphicon').removeClass('glyphicon-ok text-success text-danger text-faint')
    		.addClass('glyphicon-repeat glyphicon-spin').remove();
}

function btnToPendingSave(submitInputGroup, submitIcon){
	return submitInputGroup.find('button[type="submit"]').empty().append(submitIcon).append(' Saving...');
}

//bonus points: add in progress data
//only do this if document.valid  (auto handled by yii if ajax validation enabled?)
var ajaxSubmit = function(form){
	var data=$("#job-form-update").serialize();
	var submitInputGroup = $('.gus-input-group-submit');
	var submitIcon = iconToPendingSave(submitInputGroup);
	var submitBtn = btnToPendingSave(submitInputGroup, submitIcon);

    $.ajax(form.attr('action'), {
        type: 'POST',
        dataType: 'json',
        data: data,
        success: function(response){
        	submitBtn.empty();
   			submitBtn.append(submitIcon.addClass('text-success'));
        },
        error: function (xhr, ajaxOptions, thrownError) {
        	console.log('auto save error!');
            console.log(xhr.status);
            console.log(xhr.responseJSON);
            submitBtn.empty();
   			submitBtn.append(submitIcon.addClass('text-danger'));
        },
        failure: function(response){
            console.log('auto save failure!');
            submitBtn.empty();
   			submitBtn.append(submitIcon.addClass('text-danger'));
        },
    }).always(function(){submitIcon.removeClass('glyphicon-repeat glyphicon-spin').addClass('glyphicon-ok');});
}

var setupAutoSave = function(form){
    if(form.first().val() === undefined) return;
    var submitInputGroup = $('.gus-input-group-submit');
    var submitIcon = submitInputGroup.find('.glyphicon').removeClass('text-success').remove();
    var submitBtn = submitInputGroup.find('button[type="submit"]');
    submitBtn.empty();
   	submitBtn.append(submitIcon.addClass('text-faint')).append(' Save');

    //TODO: should we make this so its always 30 seconds from last save - regardless of whether last save was auto or not?
    clearTimeout( jobAutoSaveIntervalId );
    jobAutoSaveIntervalId = setTimeout(function(){
        ajaxSubmit(form);
    }, 15000);
}

var calculateCostOfGoodsPercentage = function(){
	var costOfGoods = 0;
	var jobProducts = $('.jobLines')
	$.each(jobProducts, function(idx, jobProduct){
									costOfGoods += $(jobProduct).find('*[name="product-cost"]').val()
										* $(jobProduct).find('*[name="product-quantity"]').val();
								});
	setCostOfGoodsSoldPercentage(costOfGoods);
}

var addAutoTotalListeners = function(){
	//any fee input change
	$( ".auto_quote .part" ).on( "change keyup", function() {
	  	calculateJobTotal();
	});
	//is taxed checkbox change
	$( "#jobIsTaxed" ).on( "click", function() {
	  	calculateJobTotal();
	});
	//job line total change
	$( ".garment_part" ).on( "change", function() {
	  	calculateJobTotal();
	});
}

var addCostOfGoodsPercentageListeners = function(){
	$( "#jobTotal" ).on( "change", function() {
	  	calculateCostOfGoodsPercentage();
	});
}

$( document ).ready(function() {
	$('#jobStatusDropdown .dropdown-toggle').attr('href', '#jobStatusDropdown');
	$("#jobStatusDropdown .dropdown-menu li a").click(function(){
	  var group = $(this).parents(".input-group");
	  group.find('.selection').text($(this).text()).change();
	  var listItem = $(this).parent();
	  var statusId = listItem.data('status-id');
	  listItem.siblings().removeClass('active');
	  listItem.addClass('active');
	  group.children('*[type="hidden"]').val(statusId);
	});
	addAutoTotalListeners();
	addCostOfGoodsPercentageListeners();
	setGrandTotal(parseFloat($('#jobTotal').val().replace(/,/g, '')));

	$( "#job-form-update" ).on( "change", function(event) {
		if(!$(this)[0].checkValidity || !$(this)[0].checkValidity()) return;
		console.log('job form change detected');
	  	setupAutoSave($(this));
	});
	$( ".gus-input-group-submit button[type='submit']" ).on( "click", function(event) {
		var form = $('.gus-form');
		if(!form[0].checkValidity || !form[0].checkValidity()) return;
		console.log('job form submitted');
	  	var submitInputGroup = $('.gus-input-group-submit');
		var submitIcon = iconToPendingSave(submitInputGroup);
		btnToPendingSave(submitInputGroup, submitIcon);

	});
});


text:
<?php declare(strict_types=1);

namespace IceHawk\IceHawk\Tests\Unit\Defaults;

use IceHawk\IceHawk\Defaults\FinalReadResponder;
use IceHawk\IceHawk\Defaults\FinalWriteResponder;
use IceHawk\IceHawk\Defaults\IceHawkConfig;
use IceHawk\IceHawk\Defaults\RequestInfo;
use PHPUnit\Framework\TestCase;

class IceHawkConfigTest extends TestCase
{
	public function testDefaults()
	{
		$config = new IceHawkConfig();

		$this->assertEquals( [], $config->getEventSubscribers() );
		$this->assertEquals( RequestInfo::fromEnv(), $config->getRequestInfo() );
		$this->assertEquals( new FinalReadResponder(), $config->getFinalReadResponder() );
		$this->assertEquals( new FinalWriteResponder(), $config->getFinalWriteResponder() );
		$this->assertEquals( [], $config->getWriteRoutes() );
		$this->assertEquals( [], $config->getReadRoutes() );
	}
}


text:
require 'spec_helper'

describe SeemsRateable::Models::ActiveRecordExtension do
  describe "#seems_rateable" do
    subject { DummyModel.seems_rateable.new }

    context "without any dimension" do
      it { should have_many(:_rates).class_name(SeemsRateable::Rate) }
      it { should have_many(:_raters).through(:_rates).dependent(:destroy) }
    end

    context "with dimensions" do
      dimensions = [:speed, :quality]
      let(:dimensions) { dimensions }

      subject { DummyModel.seems_rateable(*dimensions).new }

      dimensions.each do |dimension|
        it { should have_many(:"#{dimension}_rates").conditions(dimension: dimension) }
        it { should have_many(:"#{dimension}_raters").through(:"#{dimension}_rates") }
      end
    end

    it { should be_a(SeemsRateable::Models::ActiveRecordExtension::Rateable) }
  end

  describe "#seems_rateable_rater" do
    subject { DummyModel.seems_rateable_rater.new }

    it { should have_many(:rates_given).class_name(SeemsRateable::Rate) }
    it { should be_a(SeemsRateable::Models::ActiveRecordExtension::Rater) }
  end

  describe SeemsRateable::Models::ActiveRecordExtension::Rateable do
    subject do
      Class.new.send(:include, SeemsRateable::Models::ActiveRecordExtension::Rateable).new
    end

    %w[rates raters].each do |method|
      describe "##{method}" do
        context "valid dimension" do
          context "no dimension" do
            it "sends _#{method}" do
              subject.should_receive(:"_#{method}")
              subject.send method
            end
          end

          context "existent dimension" do
            let(:dimension) { 'quality' }

            before do
              subject.stub(dimension + '_' + method).and_return(true)
            end

            it "sends quality_rates" do
              subject.should_receive(:"#{dimension}_#{method}")
              subject.send method, dimension
            end
          end

          context "non-existent dimension" do
            it "raises NonExistentDimension error" do
              expect { subject.send method, "foo" }.to raise_error
            end
          end
        end
      end
    end

    describe "#rating" do
      let(:rates) { SeemsRateable::Rate.all }

      before do
        subject.stub(:rates).and_return(rates)
      end

      it "initializes a SeemsRateable::Rating instance with its rates" do
        subject.rating.should be_a(SeemsRateable::Rating)
        subject.rating.rates.should == rates
      end
    end

    describe "#rated_by" do
      context "when passed rater is nil" do
        it "returns does not query the database and returns nil" do
          subject.rated_by?(nil).should be_nil
        end
      end

      context "when passed rater is not nil" do
        before do
          subject.stub(:raters).and_return([])
        end

        let(:rater) { "a random guy" }

        it "checks wheter its raters includes the rater" do
          subject.raters.should_receive(:include?).with(rater)
          subject.rated_by?(rater)
        end
      end
    end
  end
end


text:
/* { dg-options "-std=gnu89 -fms-extensions" } */
/* Enabling Microsoft mode makes all of the tests equivalent.  Checked vs
   Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 12.00.8168 for 80x86
 */

struct A { char a; };

struct B {
  struct A;
  char b;
};
char testB[sizeof(struct B) == 2 * sizeof(struct A) ? 1 : -1];

struct C {
  struct D { char d; };
  char c;
};
char testC[sizeof(struct C) == 2 * sizeof(struct A) ? 1 : -1];
char testD[sizeof(struct D) == sizeof(struct A) ? 1 : -1];

struct E {
  struct { char z; };
  char e;
};
char testE[sizeof(struct E) == 2 * sizeof(struct A) ? 1 : -1];

typedef struct A typedef_A;
struct F {
  typedef_A;
  char f;
};
char testF[sizeof(struct F) == 2 * sizeof(struct A) ? 1 : -1];


text:
from typing import Callable, Optional, TypeVar

from reactivex import Observable, compose
from reactivex import operators as ops
from reactivex.typing import Predicate

_T = TypeVar("_T")

def single_(
    predicate: Optional[Predicate[_T]] = None,
) -> Callable[[Observable[_T]], Observable[_T]]:
    """Returns the only element of an observable sequence that satisfies the
    condition in the optional predicate, and reports an exception if there
    is not exactly one element in the observable sequence.

    Example:
        >>> res = single()
        >>> res = single(lambda x: x == 42)

    Args:
        predicate -- [Optional] A predicate function to evaluate for
            elements in the source sequence.

    Returns:
        An observable sequence containing the single element in the
        observable sequence that satisfies the condition in the predicate.
    """

    if predicate:
        return compose(ops.filter(predicate), ops.single())
    else:
        return ops.single_or_default_async(False)

__all__ = ["single_"]


text:
package com.urqa.Collector;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

import com.urqa.common.CallStackData;
import com.urqa.common.StateData;
import com.urqa.common.JsonObj.ErrorSendData;
import com.urqa.eventpath.EventPathManager;
import com.urqa.rank.ErrorRank;

public class ErrorReportFactory {

	public static ErrorReport CreateErrorReport(Throwable e,String tag,ErrorRank rank ,Context context)
	{
		ErrorReport report = new ErrorReport();
		report.ErrorData = CreateSendData(e,tag,rank,context);
		report.LogData	 = LogCollector.getLog(context);

		return report;
	}

	public static ErrorReport CreateNativeErrorReport(Context context)
	{
		ErrorReport report = new ErrorReport();
		report.ErrorData = CreateNativeSendData(context);
		report.LogData	 = LogCollector.getLog(context);

		return report;
	}

	private static ErrorSendData CreateNativeSendData(Context context)
	{
		ErrorSendData senddata = new ErrorSendData();

		PackageManager packagemanager = context.getPackageManager();
		PackageInfo packageinfo = null;
		try {
			packageinfo = packagemanager.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		}

		senddata.apikey 		= StateData.APIKEY;
		senddata.datetime 		= DateCollector.GetDateYYMMDDHHMMSS(context);
		senddata.device			= android.os.Build.MODEL;
		senddata.country		= DeviceCollector.GetNational(context);
		senddata.appversion		= packageinfo.versionName;
		senddata.osversion		= android.os.Build.VERSION.RELEASE;
		senddata.gpson			= (DeviceCollector.GetGps(context)) ? 1 : 0;
		senddata.wifion			= (DeviceCollector.GetWiFiNetwork(context)) ? 1 : 0;
		senddata.mobileon		= (DeviceCollector.GetMobileNetwork(context)) ? 1 : 0;
		senddata.scrwidth		= DeviceCollector.GetWidthScreenSize(context);
		senddata.scrheight		= DeviceCollector.GetHeightScreenSize(context);
		senddata.batterylevel	= DeviceCollector.GetBatteryLevel(context);
		senddata.availsdcard	= DeviceCollector.BytetoMegaByte(DeviceCollector.getAvailableExternalMemorySize());
		senddata.rooted			= (DeviceCollector.CheckRoot()) ? 1 : 0;
		senddata.appmemtotal	= DeviceCollector.BytetoMegaByte(DeviceCollector.GetTotalMemory());
		senddata.appmemfree		= DeviceCollector.BytetoMegaByte(DeviceCollector.GetFreeMemory());
		senddata.appmemmax		= DeviceCollector.BytetoMegaByte(DeviceCollector.GetMaxMemory());
		senddata.kernelversion	= DeviceCollector.GetLinuxKernelVersion();
		senddata.xdpi			= DeviceCollector.GetXDPI(context);
		senddata.ydpi			= DeviceCollector.GetYDPI(context);
		senddata.scrorientation = DeviceCollector.GetOrientation(context);
		senddata.sysmemlow		= (DeviceCollector.GetSystemLowMemory()) ? 1 : 0;
		senddata.eventpaths		= EventPathManager.GetErrorEventPath();
		senddata.locale			= DeviceCollector.GetLocale(context);
		senddata.rank			= ErrorRank.Native.value();

		return senddata;
	}

	private static ErrorSendData CreateSendData(Throwable e,String tag,ErrorRank rank ,Context context)
	{
		ErrorSendData senddata = new ErrorSendData();

		String CallStack = CallStackCollector.GetCallStack(e);
		CallStackData data = CallStackCollector.ParseStackTrace(e, CallStack);

		PackageManager packagemanager = context.getPackageManager();
		PackageInfo packageinfo = null;
		try {
			packageinfo = packagemanager.getPackageInfo(context.getPackageName(), 0);
		} catch (NameNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return null;
		}

		senddata.apikey 		= StateData.APIKEY;
		senddata.datetime 		= DateCollector.GetDateYYMMDDHHMMSS(context);
		senddata.device			= android.os.Build.MODEL;
		senddata.country		= DeviceCollector.GetNational(context);
		senddata.errorname		= data.ErrorName;
		senddata.errorclassname	= data.ClassName;
		senddata.linenum		= data.Line;
		senddata.lastactivity	= data.ActivityName;
		senddata.callstack		= CallStack;
		senddata.appversion		= packageinfo.versionName;
		senddata.osversion		= android.os.Build.VERSION.RELEASE;
		senddata.gpson			= (DeviceCollector.GetGps(context)) ? 1 : 0;
		senddata.wifion			= (DeviceCollector.GetWiFiNetwork(context)) ? 1 : 0;
		senddata.mobileon		= (DeviceCollector.GetMobileNetwork(context)) ? 1 : 0;
		senddata.scrwidth		= DeviceCollector.GetWidthScreenSize(context);
		senddata.scrheight		= DeviceCollector.GetHeightScreenSize(context);
		senddata.batterylevel	= DeviceCollector.GetBatteryLevel(context);
		senddata.availsdcard	= DeviceCollector.BytetoMegaByte(DeviceCollector.getAvailableExternalMemorySize());
		senddata.rooted			= (DeviceCollector.CheckRoot()) ? 1 : 0;
		senddata.appmemtotal	= DeviceCollector.BytetoMegaByte(DeviceCollector.GetTotalMemory());
		senddata.appmemfree		= DeviceCollector.BytetoMegaByte(DeviceCollector.GetFreeMemory());
		senddata.appmemmax		= DeviceCollector.BytetoMegaByte(DeviceCollector.GetMaxMemory());
		senddata.kernelversion	= DeviceCollector.GetLinuxKernelVersion();
		senddata.xdpi			= DeviceCollector.GetXDPI(context);
		senddata.ydpi			= DeviceCollector.GetYDPI(context);
		senddata.scrorientation = DeviceCollector.GetOrientation(context);
		senddata.sysmemlow		= (DeviceCollector.GetSystemLowMemory()) ? 1 : 0;
		senddata.tag			= tag;
		senddata.rank			= rank.value();
		senddata.eventpaths		= EventPathManager.GetErrorEventPath();
		senddata.locale			= DeviceCollector.GetLocale(context);

		return senddata;
	}
}


text:
from matplotlib import pyplot as plt
from multiprocessing import Pool
from multiprocessing import cpu_count
import numpy as np
import os
from scipy.misc import imread, imsave
import scipy.sparse
import sklearn.linear_model as lm
import scipy.ndimage
import sys

import plotting
import utils

def sampling_mask(shape, rate=0.5):
    """ Creates sampling mask

    :param shape: (int, int)
        shape of mask
    :param rate: float
        ratio of True pixels
    :return: 2d bool array
        mask
    """
    assert 0 <= rate < 1.

    np.random.seed(42)
    size = int(np.product(shape))
    mask = np.zeros(size, dtype=np.bool)
    mask[np.random.choice(size, int(size*rate), replace=False)] = True
    return mask.reshape(shape)

def recovery_single(img, mask, basis="dct", wvt_level=3, alpha=None):
    """ Recovers image

    :param img: 2d array
        corrupted image
    :param mask: 2d bool array
        mask
    :param basis: str
        either 'wvt', 'dct'
    :param wvt_level: int
        level of wavelet transform
    :param alpha: float or None
        regularization parameter
        if None: alpha is first found with CV (takes long)
    :return: 2d array
        recovered image
    """
    print "img shape: ", img.shape
    img_f = img.flatten()
    A = np.eye(len(img_f), dtype=np.bool)
    print("Build sensing matrix")
    mask_f = mask.flatten()
    for i_px in range(len(img_f)):
        if mask_f[i_px]:
            A[i_px, i_px] = False

    print("Measurement")
    b = np.array([np.dot(A[i], img_f) for i in range(len(img_f))])

    if basis == "wvt":
        print("Wavelets")
        trans_A = [utils.dwt2(A[i].reshape(img.shape), level=wvt_level).
                     astype(np.float16).flatten() for i in range(len(img_f))]
    elif basis == "dct":
        print("DCT")
        trans_A = [utils.dct2(A[i].reshape(img.shape)).
                       astype(np.float16).flatten() for i in range(len(img_f))]
    else:
        raise Exception("Unknown basis")

    A = None

    if alpha:
        lasso = lm.Lasso(alpha=alpha, max_iter=100000, normalize=True)
        print("Fit")
        lasso.fit(trans_A, b)
    else:
        lasso_cv = lm.LassoCV(n_jobs=cpu_count(), max_iter=100000,
                              normalize=True)
        print("Fit")
        lasso_cv.fit(trans_A, b)
        print("Alpha: %.6f" % lasso_cv.alpha_)
        lasso = lm.Lasso(alpha=lasso_cv.alpha_, max_iter=100000,
                         normalize=True)
        print("Fit")
        lasso.fit(trans_A, b)

    if basis == "wvt":
        return utils.idwt2(lasso.coef_.reshape(img.shape), level=wvt_level)
    elif basis == "dct":
        return utils.idct2(lasso.coef_.reshape(img.shape))
    else:
        raise Exception("Unknown basis")

def _recovery_thread(args):
    rec = recovery_single(args[1], args[2], wvt_level=args[3], alpha=args[4])
    return args[0], rec

def recover_blocks(img, mask, blocksize=32, wvt_level=3, alpha=None,
                   n_processes=None):
    """ Recovers image parallel with blocking

    :param img: 2d array
        image
    :param mask: 2d bool array
        mask
    :param blocksize: int
        defines edgelength of blocking squares
    :param wvt_level: int
        level of wavelet transform
    :param alpha: float or None
        regularization parameter
        if None: alpha is first found with CV (takes long)
    :param n_processes: int or None
        number of processes to be used
        if None: all cores are used
    :return: 2d array
        recovered image
    """
    if not n_processes:
        n_processes = cpu_count()

    my_img = np.pad(img, [[blocksize/2, blocksize/2],
                          [blocksize/2, blocksize/2]], mode="reflect")
    my_mask = np.pad(mask, [[blocksize/2, blocksize/2],
                            [blocksize/2, blocksize/2]], mode="reflect")

    params = []

    for x_pos in range(0, my_img.shape[0]-blocksize/2, blocksize/2):
        for y_pos in range(0, my_img.shape[1]-blocksize/2, blocksize/2):
            params.append([[x_pos, y_pos],
                           my_img[x_pos: x_pos + blocksize,
                                  y_pos: y_pos + blocksize],
                           my_mask[x_pos: x_pos + blocksize,
                                   y_pos: y_pos + blocksize],
                           wvt_level, alpha, blocksize])

    print("N jobs: %d" % (len(params)))
    if n_processes > 1:
        pool = Pool(n_processes)
        results = pool.map(_recovery_thread, params)
        pool.close()
        pool.join()
    else:
        results = map(_recovery_thread, params)

    r_img = np.zeros(my_img.shape, dtype=np.float32)
    normalization = np.zeros(my_img.shape, dtype=np.float16)
    for result in results:
        r_img[result[0][0] + blocksize/4: result[0][0] + blocksize*3/4,
              result[0][1] + blocksize/4: result[0][1] + blocksize*3/4] += \
            result[1][blocksize/4: blocksize*3/4, blocksize/4:blocksize*3/4]
        normalization[result[0][0] + blocksize/4:
                                            result[0][0] + blocksize*3/4,
                      result[0][1] + blocksize/4:
                                            result[0][1] + blocksize*3/4] += 1

    r_img /= normalization
    return r_img[blocksize/2: -blocksize/2, blocksize/2: -blocksize/2]

def recover_main(img_path, zoom_rate=1., corruption_rate=.1, alpha=None,
                 wvt_level=3, save_path=None, blocksize=32, n_processes=None):
    """ Recoveres an image and performs assisting work

    :param img_path: str
        path to true image
    :param zoom_rate: float
        image rescaling factor
    :param corruption_rate: float
        corruptin rate (0-1)
    :param alpha: float or None
        regularization parameter
        if None: alpha is first found with CV (takes long)
    :param wvt_level: int
        level of wavelet transform
    :param save_path: str
        path to folder to which images will be exported
        if ends with .png: only recovered image and cropped image are stored
        if None: images will be shown
    :param blocksize: int
        defines edgelength of blocking squares
    :param n_processes:int or None
        number of processes to be used
        if None: all cores are used
    """

    assert os.path.exists(img_path)
    img = imread(img_path)

    if len(img.shape) > 2:
        print("Only grayscale supported...")
        img = np.mean(img, axis=-1)
        print("... RGB converted to grayscale")

    if zoom_rate != 1:
        img = scipy.ndimage.zoom(img, zoom=zoom_rate, order=3)

    off = [(img.shape[0] % 2 ** wvt_level) / 2.,
           (img.shape[1] % 2 ** wvt_level) / 2.]

    img = img[int(np.floor(off[0])): img.shape[0] - int(np.ceil(off[0])),
              int(np.floor(off[1])): img.shape[1] - int(np.ceil(off[1]))]

    if (3 + wvt_level)**2 > blocksize:
        print "Blocksize is too small for chosen wavelet level..."
        wvt_level = int(np.log2(blocksize)) - 3
        print "... chose %d as wavelet level instead." % wvt_level

    print("Cropped image to: ", img.shape)

    mask = sampling_mask(img.shape, rate=corruption_rate)

    img = img.astype(np.float16) / np.max(img)

    d_img = img.copy()
    d_img[mask] = 0

    r_img = recover_blocks(d_img.copy(), mask.copy(), alpha=alpha,
                           blocksize=blocksize, n_processes=n_processes,
                           wvt_level=wvt_level)
    r_img[r_img < 0] = 0
    neg_mask = np.invert(mask)

    print("rmse %.3f" % (utils.compute_rmse(img, r_img)))
    print("Corruption rate: %.3f, number of pixel: %d" % (corruption_rate,
          int(np.sum(neg_mask))))

    if save_path:
        if save_path.endswith(".png"):
            imsave(save_path, r_img)
            imsave(save_path[:-4] + "_true.png", d_img)
        else:
            if not os.path.exists(save_path + "/cr_%d/" % (corruption_rate * 1000)):
                os.makedirs(save_path + "/cr_%d/" % (corruption_rate * 1000))
            alpha_s = int(alpha * 1e9)
            imsave(save_path + "/cr_%d/img_%d_%d.png" %
                   (corruption_rate * 1000, blocksize, alpha_s), img)
            imsave(save_path + "/cr_%d/corrupt_img_%d_%d.png" %
                   (corruption_rate * 1000, blocksize, alpha_s), d_img)
            imsave(save_path + "/cr_%d/rec_%d_%d.png" %
                   (corruption_rate * 1000, blocksize, alpha_s), r_img)
            imsave(save_path + "/cr_%d/rec_diff_%d_%d.png" %
                   (corruption_rate * 1000, blocksize, alpha_s),
                   np.abs(img-r_img))
            imsave(save_path + "/cr_%d/rec_diff_%d_%d_gray.png" %
                   (corruption_rate * 1000, blocksize, alpha_s), img-r_img)
            plotting.plot_img(img-r_img,
                              save_path + "/cr_%d/rec_diff_%d_%d.png" %
                              (corruption_rate * 1000, blocksize, alpha_s))
    else:
        plt.clf()
        fig, axarr = plt.subplots(2, 2)

        axarr[0, 0].imshow(img, cmap="gray")
        axarr[0, 1].imshow(d_img, cmap="gray")
        axarr[1, 0].imshow(r_img, cmap="gray")
        axarr[1, 1].imshow(np.abs(r_img-img), cmap="gray")

        plt.show()

if __name__ == "__main__":
    if len(sys.argv) not in [3, 4]:
        print("Usage for parameter swiping: python2 recovery.py <path_to_img> "
              "<path_to_save_folder> [<blocksize>]")
    else:
        assert os.path.exists(sys.argv[1])
        img_path = sys.argv[1]

        assert os.path.exists(sys.argv[2])
        save_path = sys.argv[2]

        if len(sys.argv) == 4:
            blocksizes = [int(sys.argv[3])]
        else:
            blocksizes = [16, 32, 64]

        alphas = list(np.logspace(-7, 1, num=20))
        corruption_rates = [i / 10. for i in range(1, 10)] + [.95, .99]

        for cr in corruption_rates:
            for b in blocksizes:
                for a in alphas:
                    recover_main(img_path=img_path, corruption_rate=cr, alpha=a,
                                 blocksize=b, save_path=save_path)

            utils.compute_rmse_folder(save_path + "/cr_%d/" % cr)


text:
using System;
using System.Collections.Generic;

namespace Jcq.IcqProtocol.DataTypes
{
    public class Snac0118 : Snac
    {
        public Snac0118() : base(0x1, 0x18)
        {
        }

        public List<FamilyVersionPair> FamilyNameVersionPairs { get; } = new List<FamilyVersionPair>();

        public override List<byte> Serialize()
        {
            throw new NotImplementedException();
        }

        public override void Deserialize(List<byte> data)
        {
            base.Deserialize(data);

            int index = SizeFixPart;

            while (index + 4 <= data.Count)
            {
                int number = ByteConverter.ToUInt16(data.GetRange(index, 2));
                index += 2;
                int version = ByteConverter.ToUInt16(data.GetRange(index, 2));
                index += 2;

                FamilyNameVersionPairs.Add(new FamilyVersionPair(number, version));
            }

            TotalSize = index;
        }

        public override int CalculateDataSize()
        {
            return FamilyNameVersionPairs.Count * 4;
        }
    }
}


text:
class AddBlockNumToDisplays < ActiveRecord::Migration
  def change
    add_column :displays, :block_num, :integer
  end
end


text:
"""
This module provides the Stress class used to create, manipulate, and
calculate relevant properties of the stress tensor.
"""

from pymatgen.core.tensors import SquareTensor
import math
import numpy as np
import warnings

__author__ = "Joseph Montoya"
__copyright__ = "Copyright 2012, The Materials Project"
__credits__ = "Maarten de Jong, Mark Asta, Anubhav Jain"
__version__ = "1.0"
__maintainer__ = "Joseph Montoya"
__email__ = "montoyjh@lbl.gov"
__status__ = "Production"
__date__ = "July 24, 2018"

class Stress(SquareTensor):
    """
    This class extends SquareTensor as a representation of the
    stress
    """
    symbol = "s"

    def __new__(cls, stress_matrix):
        """
        Create a Stress object.  Note that the constructor uses __new__
        rather than __init__ according to the standard method of
        subclassing numpy ndarrays.

        Args:
            stress_matrix (3x3 array-like): the 3x3 array-like
                representing the stress
        """
        obj = super(Stress, cls).__new__(cls, stress_matrix)
        return obj.view(cls)

    @property
    def dev_principal_invariants(self):
        """
        returns the principal invariants of the deviatoric stress tensor,
        which is calculated by finding the coefficients of the characteristic
        polynomial of the stress tensor minus the identity times the mean
        stress
        """
        return self.deviator_stress.principal_invariants*np.array([1, -1, 1])

    @property
    def von_mises(self):
        """
        returns the von mises stress
        """
        if not self.is_symmetric():
            raise ValueError("The stress tensor is not symmetric, Von Mises "
                             "stress is based on a symmetric stress tensor.")
        return math.sqrt(3*self.dev_principal_invariants[1])

    @property
    def mean_stress(self):
        """
        returns the mean stress
        """
        return 1./3.*self.trace()

    @property
    def deviator_stress(self):
        """
        returns the deviatoric component of the stress
        """
        if not self.is_symmetric:
            raise warnings.warn("The stress tensor is not symmetric, "
                                "so deviator stress will not be either")
        return self - self.mean_stress*np.eye(3)

    def piola_kirchoff_1(self, def_grad):
        """
        calculates the first Piola-Kirchoff stress

        Args:
            def_grad (3x3 array-like): deformation gradient tensor
        """
        if not self.is_symmetric:
            raise ValueError("The stress tensor is not symmetric, \
                             PK stress is based on a symmetric stress tensor.")
        def_grad = SquareTensor(def_grad)
        return def_grad.det*np.dot(self, def_grad.inv.trans)

    def piola_kirchoff_2(self, def_grad):
        """
        calculates the second Piola-Kirchoff stress

        Args:
            def_grad (3x3 array-like): rate of deformation tensor
        """

        def_grad = SquareTensor(def_grad)
        if not self.is_symmetric:
            raise ValueError("The stress tensor is not symmetric, \
                             PK stress is based on a symmetric stress tensor.")
        return def_grad.det*np.dot(np.dot(def_grad.inv, self),
                                   def_grad.inv.trans)


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->string('email')->unique();
            $table->string('avatar');//保存用户头像
            $table->string('confirm_code',64);//邮箱确认激活code
            $table->smallInteger('is_confirmed')->default(0);//判断用户呢是否已经激活他的邮箱
            $table->string('password');
            $table->integer('followers_count')->default(0);
            $table->integer('followings_count')->default(0);
            $table->rememberToken()->nullable();
            $table->string('api_token',64)->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}


text:
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Counter from '../components/Counter';
import * as ItemActions from '../actions/items';

function mapStateToProps(state) {
  return {
    counter: state.counter
  };
}

export default connect(mapStateToProps)(Counter);


text:
#ifndef mitkIPropertyPersistence_h
#define mitkIPropertyPersistence_h

#include <mitkPropertyPersistenceInfo.h>
#include <mitkServiceInterface.h>

namespace mitk
{
  /** \ingroup MicroServices_Interfaces
    * \brief Interface of property persistence service
    *
    * This service allows you to manage persistence info for base data properties.
    * Persistent properties will be saved if the file format supports custom key value pairs like the .nrrd file
   * format.\n
    * \remark The service supports the use of regular expressions (regex; ECMAscript syntax)
    * for property names and persistance keys to specifiy persistence rules in a generic way. The getter of the
   * interface
    * (GetInfo and GetInfoByKey) will always ensure that the return containes no regex, thus name and key in the results
    * can directly be used. For details on how the result names and keys are determined, please @TODO
    *
    */
  class MITKCORE_EXPORT IPropertyPersistence
  {
  public:
    virtual ~IPropertyPersistence();

    using InfoResultType = std::list<PropertyPersistenceInfo::ConstPointer>;
    using MimeTypeNameType = PropertyPersistenceInfo::MimeTypeNameType;

    /** \brief Add persistence info for a specific base data property.
      * If there is already a property info instance for the passed
      * property name and the same info, it won't be added. Info instances
      * are regarded equal, if the mime types are equal.
      * You may enforce to overwrite the old equal info for a property name
      * by the overwrite parameter.
      *
      * \param[in] propertyName Name of the property.
      * \param[in] info Persistence info of the property.
      * \param[in] overwrite Overwrite already existing persistence info.
      * \return True if persistence info was added successfully.
      */
    virtual bool AddInfo(const PropertyPersistenceInfo *info, bool overwrite = false) = 0;

    /** \brief Get the persistence info for a specific base data property.
      * \param[in] propertyName Name of the property.
      * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked.
      * \return Property persistence info or null pointer if no persistence info is available.
      */
    virtual InfoResultType GetInfo(const std::string &propertyName, bool allowNameRegEx = true) const = 0;

    /** \brief Get the persistence info for a specific base data property and mime type.
    *
    * \param[in] propertyName Name of the property.
    * \param[in] mime Name of the mime type the info is specified for.
    * \param[in] allowMimeWildCard Indicates if wildcard is allowed. If it is allowed, the method will first try to find
    * the specified info.
    * If no info was found but an info exists with the mime type name PropertyPersistenceInfo::ANY_MIMETYPE_NAME(), the
    * later info will be
    * returned as fall back option.
    * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked.
    * \return Property persistence info or null pointer if no persistence info is available.
    */
    virtual InfoResultType GetInfo(const std::string &propertyName,
                                   const MimeTypeNameType &mime,
                                   bool allowMimeWildCard = false,
                                   bool allowNameRegEx = true) const = 0;

    /** \brief Get the persistence info that will use the specified key.
    *
    * \param[in] propertyName Name of the property.
    * \param[in] allowKeyRegEx Indicates if also added info instances with regexs for the key are being checked.
    * \return Property persistence info or null pointer if no persistence info is available.
    */
    virtual InfoResultType GetInfoByKey(const std::string &persistenceKey, bool allowKeyRegEx = true) const = 0;

    /** \brief Check if a specific base data property has persistence info.
      *
      * \param[in] propertyName Name of the property.
      * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked.
      * \return True if the property has persistence info, false otherwise.
      */
    virtual bool HasInfo(const std::string &propertyName, bool allowNameRegEx = true) const = 0;

    /** \brief Remove all persistence info.
      */
    virtual void RemoveAllInfo() = 0;

    /** \brief Remove persistence info instances of a specific property name/regex.
      *
      * \param[in] propertyName Registered name or regex that should be removed.
      */
    virtual void RemoveInfo(const std::string &propertyName) = 0;

    /** \brief Remove persistence info instances of a specific property name/regex and mime type.
    *
    * \param[in] propertyName Registered name or regex that should be removed.
    * \param[in] mime Name of the mime type.
    */
    virtual void RemoveInfo(const std::string &propertyName, const MimeTypeNameType &mime) = 0;
  };
}

MITK_DECLARE_SERVICE_INTERFACE(mitk::IPropertyPersistence, "org.mitk.IPropertyPersistence")

#endif


text:
namespace extensions {

namespace {

const char kNoTabIdError[] = "targetTab doesn't have id field set.";
const char kNoUrlError[] = "targetTab doesn't have URL field set.";
const char kInvalidOriginError[] = "targetTab.url is not a valid URL.";
const char kInvalidTabIdError[] = "Invalid tab specified.";
const char kTabUrlNotSecure[] =
    "URL scheme for the specified tab is not secure.";
}  // namespace

DesktopCaptureChooseDesktopMediaFunction::
    DesktopCaptureChooseDesktopMediaFunction() {
}

DesktopCaptureChooseDesktopMediaFunction::
    ~DesktopCaptureChooseDesktopMediaFunction() {
}

bool DesktopCaptureChooseDesktopMediaFunction::RunAsync() {
  EXTENSION_FUNCTION_VALIDATE(args_->GetSize() > 0);

  EXTENSION_FUNCTION_VALIDATE(args_->GetInteger(0, &request_id_));
  DesktopCaptureRequestsRegistry::GetInstance()->AddRequest(
      render_frame_host()->GetProcess()->GetID(), request_id_, this);

  args_->Remove(0, NULL);

  scoped_ptr<api::desktop_capture::ChooseDesktopMedia::Params> params =
      api::desktop_capture::ChooseDesktopMedia::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params.get());

  // |web_contents| is the WebContents for which the stream is created, and will
  // also be used to determine where to show the picker's UI.
  content::WebContents* web_contents = NULL;
  base::string16 target_name;
  GURL origin;
  if (params->target_tab) {
    if (!params->target_tab->url) {
      error_ = kNoUrlError;
      return false;
    }
    origin = GURL(*(params->target_tab->url)).GetOrigin();

    if (!origin.is_valid()) {
      error_ = kInvalidOriginError;
      return false;
    }

    if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
            switches::kAllowHttpScreenCapture) &&
        !content::IsOriginSecure(origin)) {
      error_ = kTabUrlNotSecure;
      return false;
    }
    target_name = base::UTF8ToUTF16(content::IsOriginSecure(origin) ?
        net::GetHostAndOptionalPort(origin) : origin.spec());

    if (!params->target_tab->id ||
        *params->target_tab->id == api::tabs::TAB_ID_NONE) {
      error_ = kNoTabIdError;
      return false;
    }

    if (!ExtensionTabUtil::GetTabById(*(params->target_tab->id), GetProfile(),
                                      true, NULL, NULL, &web_contents, NULL)) {
      error_ = kInvalidTabIdError;
      return false;
    }
    DCHECK(web_contents);
  } else {
    origin = extension()->url();
    target_name = base::UTF8ToUTF16(extension()->name());
    web_contents = GetSenderWebContents();
    DCHECK(web_contents);
  }

  return Execute(params->sources, web_contents, origin, target_name);
}

DesktopCaptureCancelChooseDesktopMediaFunction::
    DesktopCaptureCancelChooseDesktopMediaFunction() {}

DesktopCaptureCancelChooseDesktopMediaFunction::
    ~DesktopCaptureCancelChooseDesktopMediaFunction() {}

}  // namespace extensions


text:
"""File containing a Windows Registry plugin to parse the USBStor key."""

import logging

from plaso.containers import windows_events
from plaso.parsers import winreg
from plaso.parsers.winreg_plugins import interface

__author__ = 'David Nides (david.nides@gmail.com)'

class USBStorPlugin(interface.WindowsRegistryPlugin):
  """USBStor key plugin."""

  NAME = u'windows_usbstor_devices'
  DESCRIPTION = u'Parser for USB Plug And Play Manager USBStor Registry Key.'

  FILTERS = frozenset([
      interface.WindowsRegistryKeyPathFilter(
          u'HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Enum\\USBSTOR')])

  URLS = [u'http://www.forensicswiki.org/wiki/USB_History_Viewing']

  _SOURCE_APPEND = u': USBStor Entries'

  def GetEntries(self, parser_mediator, registry_key, **kwargs):
    """Collect Values under USBStor and return an event object for each one.

    Args:
      parser_mediator: A parser mediator object (instance of ParserMediator).
      registry_key: A Windows Registry key (instance of
                    dfwinreg.WinRegistryKey).
    """
    for subkey in registry_key.GetSubkeys():
      values_dict = {}
      values_dict[u'subkey_name'] = subkey.name

      # Time last USB device of this class was first inserted.
      event_object = windows_events.WindowsRegistryEvent(
          subkey.last_written_time, registry_key.path, values_dict,
          offset=registry_key.offset, source_append=self._SOURCE_APPEND)
      parser_mediator.ProduceEvent(event_object)

      name_values = subkey.name.split(u'&')
      number_of_name_values = len(name_values)

      # Normally we expect 4 fields here however that is not always the case.
      if number_of_name_values != 4:
        logging.warning(
            u'Expected 4 &-separated values in: {0:s}'.format(subkey.name))

      if number_of_name_values >= 1:
        values_dict[u'device_type'] = name_values[0]
      if number_of_name_values >= 2:
        values_dict[u'vendor'] = name_values[1]
      if number_of_name_values >= 3:
        values_dict[u'product'] = name_values[2]
      if number_of_name_values >= 4:
        values_dict[u'revision'] = name_values[3]

      for device_key in subkey.GetSubkeys():
        values_dict[u'serial'] = device_key.name

        friendly_name_value = device_key.GetValueByName(u'FriendlyName')
        if friendly_name_value:
          values_dict[u'friendly_name'] = friendly_name_value.GetDataAsObject()
        else:
          values_dict.pop(u'friendly_name', None)

        # ParentIdPrefix applies to Windows XP Only.
        parent_id_prefix_value = device_key.GetValueByName(u'ParentIdPrefix')
        if parent_id_prefix_value:
          values_dict[u'parent_id_prefix'] = (
              parent_id_prefix_value.GetDataAsObject())
        else:
          values_dict.pop(u'parent_id_prefix', None)

        # Win7 - Last Connection.
        # Vista/XP - Time of an insert.
        event_object = windows_events.WindowsRegistryEvent(
            device_key.last_written_time, registry_key.path, values_dict,
            offset=registry_key.offset, source_append=self._SOURCE_APPEND)
        parser_mediator.ProduceEvent(event_object)

        device_parameter_key = device_key.GetSubkeyByName(u'Device Parameters')
        if device_parameter_key:
          event_object = windows_events.WindowsRegistryEvent(
              device_parameter_key.last_written_time, registry_key.path,
              values_dict, offset=registry_key.offset,
              source_append=self._SOURCE_APPEND)
          parser_mediator.ProduceEvent(event_object)

        log_configuration_key = device_key.GetSubkeyByName(u'LogConf')
        if log_configuration_key:
          event_object = windows_events.WindowsRegistryEvent(
              log_configuration_key.last_written_time, registry_key.path,
              values_dict, offset=registry_key.offset,
              source_append=self._SOURCE_APPEND)
          parser_mediator.ProduceEvent(event_object)

        properties_key = device_key.GetSubkeyByName(u'Properties')
        if properties_key:
          event_object = windows_events.WindowsRegistryEvent(
              properties_key.last_written_time, registry_key.path,
              values_dict, offset=registry_key.offset,
              source_append=self._SOURCE_APPEND)
          parser_mediator.ProduceEvent(event_object)

winreg.WinRegistryParser.RegisterPlugin(USBStorPlugin)


text:
'use strict';

var uuid = require('node-uuid');
var Q = require('q');

var Queue = function (amiConnection, config) {

    var CommandQueueStatus = function (ami) {
        var defer = Q.defer();

        setTimeout(function() {
            defer.reject(new Error('timeout for get queue status'))
        }, 3000);

        var events = {
            params: [],
            members: [],
            entries: []
        };

        var actionid = uuid.v4();

        var catcher = function (evt) {

            if (evt.actionid == actionid) {
                if (evt['event'] == 'QueueParams') events.params.push(evt);
                if (evt['event'] == 'QueueMember') events.members.push(evt);
                if (evt['event'] == 'QueueEntry') events.entries.push(evt);
                if (evt['event'] == 'QueueStatusComplete') {
                    ami.removeListener('managerevent', catcher);
                    defer.resolve(events);
                }
            };
        };

        ami.on('managerevent', catcher);
        ami.action({
          'action': 'queuestatus',
          'actionid': actionid
        }, function (err, res) {
            if (err) defer.reject(err);
            //console.log('action', err, res);
        });
        return defer.promise;
    };

    var cacheData;
    var isCacheDataActual = false;
    var cacheTimeout = config.cacheTimeout || 3000;

    var CachedCommandQueueStatus = function () {

        if (isCacheDataActual) {
            console.log('get cached data')
            return Q.resolve(cacheData);
        } else {
            return CommandQueueStatus(amiConnection)
                .then(function (data) {
                    cacheData = data;
                    isCacheDataActual = true;
                    setTimeout(function () {
                        isCacheDataActual = false;
                    }, cacheTimeout);
                    return Q.resolve(data);
                });
        }
    };

    var queueMembers = function (object) {
        var memberEvents;
        return CachedCommandQueueStatus(amiConnection)
            .then(function (data) {
                console.log('object', object);

                if (object && object.queue) {
                    var queue = object.queue;
                    memberEvents = data.members.filter(function (item) {
                        return (item.queue == queue);
                    });
                } else {
                    memberEvents = data.members;
                }
                console.log('memberEvents', memberEvents);
                return Q.resolve(memberEvents);
            });
    };

    var queueList = function () {
        return CachedCommandQueueStatus(amiConnection)
            .then(function (data) {
                return Q.resolve(data.params);
            });
    };

    return {
        queueList: queueList,
        queueMembers: queueMembers
    };

};

module.exports = Queue;


text:
class AddMissingIndexes < ActiveRecord::Migration
  def self.up

    # These indexes were found by searching for AR::Base finds on your application
    # It is strongly recommanded that you will consult a professional DBA about your infrastucture and implemntation before
    # changing your database in that matter.
    # There is a possibility that some of the indexes offered below is not required and can be removed and not added, if you require
    # further assistance with your rails application, database infrastructure or any other problem, visit:
    #
    # http://www.railsmentors.org
    # http://www.railstutor.org
    # http://guides.rubyonrails.org

    add_index :posts, :permalink
    add_index :comments, :post_id
    add_index :posts, [:id, :type]
  end

  def self.down
    # remove_index :posts, :permalink
    remove_index :comments, :post_id
    remove_index :posts, :column => [:id, :type]
  end
end


text:
namespace arangodb {
namespace basics {
class LocalTaskQueue;
}

class LogicalCollection;
class ManagedDocumentResult;
class StringRef;

namespace velocypack {
class Builder;
class Slice;
}

namespace aql {
struct AstNode;
class SortCondition;
struct Variable;
}

namespace transaction {
class Methods;
};
}

namespace arangodb {
class IndexIterator;

class Index {
 public:
  Index() = delete;
  Index(Index const&) = delete;
  Index& operator=(Index const&) = delete;

  Index(TRI_idx_iid_t, LogicalCollection*,
        std::vector<std::vector<arangodb::basics::AttributeName>> const&,
        bool unique, bool sparse);

  Index(TRI_idx_iid_t, LogicalCollection*, arangodb::velocypack::Slice const&);

  explicit Index(arangodb::velocypack::Slice const&);

  virtual ~Index();

 public:
  /// @brief index types
  enum IndexType {
    TRI_IDX_TYPE_UNKNOWN = 0,
    TRI_IDX_TYPE_PRIMARY_INDEX,
    TRI_IDX_TYPE_GEO1_INDEX,
    TRI_IDX_TYPE_GEO2_INDEX,
    TRI_IDX_TYPE_HASH_INDEX,
    TRI_IDX_TYPE_EDGE_INDEX,
    TRI_IDX_TYPE_FULLTEXT_INDEX,
    TRI_IDX_TYPE_SKIPLIST_INDEX,
    TRI_IDX_TYPE_PERSISTENT_INDEX
  };

 public:
  /// @brief return the index id
  inline TRI_idx_iid_t id() const { return _iid; }

  /// @brief return the index fields
  inline std::vector<std::vector<arangodb::basics::AttributeName>> const&
  fields() const {
    return _fields;
  }

  /// @brief return the index fields names
  inline std::vector<std::vector<std::string>> fieldNames() const {
    std::vector<std::vector<std::string>> result;

    for (auto const& it : _fields) {
      std::vector<std::string> parts;
      parts.reserve(it.size());
      for (auto const& it2 : it) {
        parts.emplace_back(it2.name);
      }
      result.emplace_back(std::move(parts));
    }
    return result;
  }

  /// @brief whether or not the ith attribute is expanded (somewhere)
  inline bool isAttributeExpanded(size_t i) const {
    if (i >= _fields.size()) {
      return false;
    }
    return TRI_AttributeNamesHaveExpansion(_fields[i]);
  }

  /// @brief whether or not any attribute is expanded
  inline bool isAttributeExpanded(
      std::vector<arangodb::basics::AttributeName> const& attribute) const {
    for (auto const& it : _fields) {
      if (!arangodb::basics::AttributeName::namesMatch(attribute, it)) {
        continue;
      }
      return TRI_AttributeNamesHaveExpansion(it);
    }
    return false;
  }

  /// @brief whether or not any attribute is expanded
  inline bool attributeMatches(
      std::vector<arangodb::basics::AttributeName> const& attribute) const {
    for (auto const& it : _fields) {
      if (arangodb::basics::AttributeName::isIdentical(attribute, it, true)) {
        return true;
      }
    }
    return false;
  }

  /// @brief whether or not any attribute is expanded
  inline bool hasExpansion() const {
    for (auto const& it : _fields) {
      for (auto const& it2 : it) {
        if (it2.shouldExpand) {
          return true;
        }
      }
    }
    return false;
  }

  /// @brief return the underlying collection
  inline LogicalCollection* collection() const { return _collection; }

  /// @brief return a contextual string for logging
  std::string context() const;

  /// @brief whether or not the index is sparse
  inline bool sparse() const { return _sparse; }

  /// @brief whether or not the index is unique
  inline bool unique() const { return _unique; }

  /// @brief validate fields from slice
  static void validateFields(VPackSlice const& slice);

  /// @brief return the name of the index
  char const* oldtypeName() const { return oldtypeName(type()); }

  /// @brief return the index type based on a type name
  static IndexType type(char const* type);

  static IndexType type(std::string const& type);

  virtual char const* typeName() const = 0;

  virtual bool allowExpansion() const = 0;

  static bool allowExpansion(IndexType type) {
    return (type == TRI_IDX_TYPE_HASH_INDEX ||
            type == TRI_IDX_TYPE_SKIPLIST_INDEX ||
            type == TRI_IDX_TYPE_PERSISTENT_INDEX);
  }

  virtual IndexType type() const = 0;

  /// @brief return the name of an index type
  static char const* oldtypeName(IndexType);

  /// @brief validate an index id
  static bool validateId(char const*);

  /// @brief validate an index handle (collection name + / + index id)
  static bool validateHandle(char const*, size_t*);

  /// @brief generate a new index id
  static TRI_idx_iid_t generateId();

  /// @brief index comparator, used by the coordinator to detect if two index
  /// contents are the same
  static bool Compare(VPackSlice const& lhs, VPackSlice const& rhs);

  virtual bool isPersistent() const { return false; }
  virtual bool canBeDropped() const = 0;

  /// @brief Checks if this index is identical to the given definition
  virtual bool matchesDefinition(arangodb::velocypack::Slice const&) const;

  /// @brief whether or not the index is sorted
  virtual bool isSorted() const = 0;

  /// @brief whether or not the index has a selectivity estimate
  virtual bool hasSelectivityEstimate() const = 0;

  /// @brief return the selectivity estimate of the index
  /// must only be called if hasSelectivityEstimate() returns true
  ///
  /// The extra StringRef is only used in the edge index as direction
  /// attribute attribute, a Slice would be more flexible.
  double selectivityEstimate(
      arangodb::StringRef const* extra = nullptr) const;

  virtual double selectivityEstimateLocal(
      arangodb::StringRef const* extra) const;

  /// @brief whether or not the index is implicitly unique
  /// this can be the case if the index is not declared as unique,
  /// but contains a unique attribute such as _key
  virtual bool implicitlyUnique() const;

  virtual size_t memory() const = 0;

  virtual void toVelocyPack(arangodb::velocypack::Builder&, bool withFigures, bool forPersistence) const;
  std::shared_ptr<arangodb::velocypack::Builder> toVelocyPack(bool withFigures, bool forPersistence) const;

  virtual void toVelocyPackFigures(arangodb::velocypack::Builder&) const;
  std::shared_ptr<arangodb::velocypack::Builder> toVelocyPackFigures() const;

  virtual Result insert(transaction::Methods*, TRI_voc_rid_t revisionId,
                     arangodb::velocypack::Slice const&, bool isRollback) = 0;
  virtual Result remove(transaction::Methods*, TRI_voc_rid_t revisionId,
                     arangodb::velocypack::Slice const&, bool isRollback) = 0;

  virtual void batchInsert(
      transaction::Methods*,
      std::vector<std::pair<TRI_voc_rid_t, arangodb::velocypack::Slice>> const&,
      std::shared_ptr<arangodb::basics::LocalTaskQueue> queue);

  virtual void load() = 0;
  virtual void unload() = 0;

  // called when the index is dropped
  virtual int drop();

  // give index a hint about the expected size
  virtual int sizeHint(transaction::Methods*, size_t);

  virtual bool hasBatchInsert() const;

  virtual bool supportsFilterCondition(arangodb::aql::AstNode const*,
                                       arangodb::aql::Variable const*, size_t,
                                       size_t&, double&) const;

  virtual bool supportsSortCondition(arangodb::aql::SortCondition const*,
                                     arangodb::aql::Variable const*, size_t,
                                     double&, size_t&) const;

  virtual IndexIterator* iteratorForCondition(transaction::Methods*,
                                              ManagedDocumentResult*,
                                              arangodb::aql::AstNode const*,
                                              arangodb::aql::Variable const*,
                                              bool);

  virtual arangodb::aql::AstNode* specializeCondition(
      arangodb::aql::AstNode*, arangodb::aql::Variable const*) const;

  bool canUseConditionPart(arangodb::aql::AstNode const* access,
                           arangodb::aql::AstNode const* other,
                           arangodb::aql::AstNode const* op,
                           arangodb::aql::Variable const* reference,
                           std::unordered_set<std::string>& nonNullAttributes,
                           bool) const;

  /// @brief Transform the list of search slices to search values.
  ///        This will multiply all IN entries and simply return all other
  ///        entries.
  virtual void expandInSearchValues(arangodb::velocypack::Slice const,
                                    arangodb::velocypack::Builder&) const;

  virtual void warmup(arangodb::transaction::Methods* trx);

  // needs to be called when the _colllection is guaranteed to be valid!
  // unfortunatly access the logical collection on the coordinator is not always safe!
  std::pair<bool,double> updateClusterEstimate(double defaultValue = 0.1);

 protected:
  static size_t sortWeight(arangodb::aql::AstNode const* node);

  //returns estimate for index in cluster - the bool is true if the index was found

 private:
  /// @brief set fields from slice
  void setFields(VPackSlice const& slice, bool allowExpansion);

 protected:
  TRI_idx_iid_t const _iid;

  LogicalCollection* _collection;

  std::vector<std::vector<arangodb::basics::AttributeName>> _fields;

  mutable bool _unique;

  mutable bool _sparse;

  double _clusterSelectivity;
};
}

std::ostream& operator<<(std::ostream&, arangodb::Index const*);
std::ostream& operator<<(std::ostream&, arangodb::Index const&);

#endif


text:
using NGin.Core.Configuration;
using NGin.Core.Logging;
using NGin.Core.Systems;
using System;

namespace NGin.Core.Test.Integration
{
    [System( typeof( TestSystem ), null )]
    public class TestSystem : NGinSystem
    {
        public TestSystem( ILogManager logManager )
            : base( TimeSpan.FromSeconds( 1 / 5.0f ), logManager )
        { }

        public override string Name
        {
            get { return "TestSystem"; }
        }

        public override void Update()
        {
            this.LogManager.Trace( Namespace.LoggerName, LogLevel.Debugging, this.GetType().FullName + ": Performing task...Time since last: {0} MaximumRate: {1}", this.TimeSinceLastTask.TotalMilliseconds, this.MaximumRate.TotalMilliseconds );
        }
    }
}


text:
    <masthead masthead-image="{{mastheadImage[0].url}}"
              masthead-title="{{heroPost[0].title}}"
              illustration-slug="{{heroPost[0].slug}}">
    </masthead>

<jsonld data-json="hc.jsonLd"></jsonld>

{{'home.featured_posts.heading' | translate }}

                {{::featuredPost.title}}

                {{::post.content}}

{{::post.date_updated | date: "dd MMMM, yyyy"}}

{{::post.title}}

                    {{::post.date_created | date: "dd MMMM, yyyy" }}