text:
namespace tera {
namespace io {

class TabletWriter;

class TabletIO {
public:
    enum TabletStatus {
        kNotInit = kTabletNotInit,
        kReady = kTabletReady,
        kOnLoad = kTabletOnLoad,
        kOnSplit = kTabletOnSplit,
        kSplited = kTabletSplited,
        kUnLoading = kTabletUnLoading,
        kUnLoading2 = kTabletUnLoading2
    };
    typedef std::map< std::string, std::set<std::string> > ColumnFamilyMap;
    struct ScanOptions {
        uint32_t max_versions;
        uint32_t version_num; // restore version_num for stream scan
        uint32_t max_size;
        int64_t ts_start;
        int64_t ts_end;
        uint64_t snapshot_id;
        FilterList filter_list;
        ColumnFamilyMap column_family_list;
        std::set<std::string> iter_cf_set;
        int64_t timeout;

        ScanOptions()
            : max_versions(UINT32_MAX), version_num(0), max_size(UINT32_MAX),
              ts_start(kOldestTs), ts_end(kLatestTs), snapshot_id(0), timeout(INT64_MAX / 2)
        {}
    };

    struct StatCounter {
        tera::Counter low_read_cell;
        tera::Counter scan_rows;
        tera::Counter scan_kvs;
        tera::Counter scan_size;
        tera::Counter read_rows;
        tera::Counter read_kvs;
        tera::Counter read_size;
        tera::Counter write_rows;
        tera::Counter write_kvs;
        tera::Counter write_size;
    };

public:
    TabletIO(const std::string& key_start, const std::string& key_end);
    virtual ~TabletIO();

    std::string GetTableName() const;
    std::string GetTablePath() const;
    std::string GetStartKey() const;
    std::string GetEndKey() const;
    virtual CompactStatus GetCompactStatus() const;
    virtual const TableSchema& GetSchema() const;
    bool KvOnly() const { return m_kv_only; }
    StatCounter& GetCounter();
    // tablet
    virtual bool Load(const TableSchema& schema,
                      const std::string& path,
                      const std::vector<uint64_t>& parent_tablets,
                      std::map<uint64_t, uint64_t> snapshots,
                      std::map<uint64_t, uint64_t> rollbacks,
                      leveldb::Logger* logger = NULL,
                      leveldb::Cache* block_cache = NULL,
                      leveldb::TableCache* table_cache = NULL,
                      StatusCode* status = NULL);
    virtual bool Unload(StatusCode* status = NULL);
    virtual bool Split(std::string* split_key, StatusCode* status = NULL);
    virtual bool Compact(int lg_no = -1, StatusCode* status = NULL);
    bool CompactMinor(StatusCode* status = NULL);
    bool Destroy(StatusCode* status = NULL);
    virtual bool GetDataSize(uint64_t* size, std::vector<uint64_t>* lgsize = NULL,
                             StatusCode* status = NULL);
    virtual bool AddInheritedLiveFiles(std::vector<std::set<uint64_t> >* live);

    bool IsBusy();
    bool Workload(double* write_workload);

    bool SnapshotIDToSeq(uint64_t snapshot_id, uint64_t* snapshot_sequence);

    virtual bool Read(const leveldb::Slice& key, std::string* value,
                      uint64_t snapshot_id = 0, StatusCode* status = NULL);

    // read a row
    virtual bool ReadCells(const RowReaderInfo& row_reader, RowResult* value_list,
                           uint64_t snapshot_id = 0, StatusCode* status = NULL);
    /// scan from leveldb return ture means complete flase means not complete
    bool LowLevelScan(const std::string& start_tera_key,
                      const std::string& end_row_key,
                      const ScanOptions& scan_options,
                      RowResult* value_list,
                      KeyValuePair* next_start_point,
                      uint32_t* read_row_count,
                      uint32_t* read_bytes,
                      bool* is_complete,
                      StatusCode* status = NULL);

    bool LowLevelSeek(const std::string& row_key, const ScanOptions& scan_options,
                      RowResult* value_list, StatusCode* status = NULL);

    bool WriteOne(const std::string& key, const std::string& value,
                  bool sync = true, StatusCode* status = NULL);
    bool WriteBatch(leveldb::WriteBatch* batch, bool disable_wal = false, bool sync = true,
                    StatusCode* status = NULL);
    virtual bool Write(const WriteTabletRequest* request,
                       WriteTabletResponse* response,
                       google::protobuf::Closure* done,
                       const std::vector<int32_t>* index_list,
                       Counter* done_counter, WriteRpcTimer* timer = NULL,
                       StatusCode* status = NULL);

    virtual bool Scan(const ScanOption& option, KeyValueList* kv_list,
                      bool* complete, StatusCode* status = NULL);

    virtual bool ScanRows(const ScanTabletRequest* request,
                          ScanTabletResponse* response,
                          google::protobuf::Closure* done);

    uint64_t GetSnapshot(uint64_t id, uint64_t snapshot_sequence,
                         StatusCode* status = NULL);
    bool ReleaseSnapshot(uint64_t snapshot_id,  StatusCode* status = NULL);
    void ListSnapshot(std::vector<uint64_t>* snapshot_id);

    uint64_t Rollback(uint64_t snapshot_id, StatusCode* status);

    uint32_t GetLGidByCFName(const std::string& cfname);

    const leveldb::RawKeyOperator* GetRawKeyOperator();

    void SetStatus(TabletStatus status);
    TabletStatus GetStatus();

    void GetAndClearCounter(TabletCounter* counter);

    int32_t AddRef();
    int32_t DecRef();
    int32_t GetRef() const;

    static bool FindAverageKey(const std::string& start, const std::string& end,
                               std::string* res);

private:
    friend class TabletWriter;
    bool WriteWithoutLock(const std::string& key, const std::string& value,
                          bool sync = false, StatusCode* status = NULL);
//     int64_t GetDataSizeWithoutLock(StatusCode* status = NULL);

    void SetupOptionsForLG();
    void TearDownOptionsForLG();
    void IndexingCfToLG();

    void SetupIteratorOptions(const ScanOptions& scan_options,
                              leveldb::ReadOptions* leveldb_opts);
    void TearDownIteratorOptions(leveldb::ReadOptions* opts);

    void ProcessRowBuffer(std::list<KeyValuePair>& row_buf,
                          const ScanOptions& scan_options,
                          RowResult* value_list,
                          uint32_t* buffer_size);

    StatusCode InitedScanInterator(const std::string& start_tera_key,
                                   const ScanOptions& scan_options,
                                   leveldb::Iterator** scan_it);

    bool ScanRowsRestricted(const ScanTabletRequest* request,
                            ScanTabletResponse* response,
                            google::protobuf::Closure* done);
    bool ScanRowsStreaming(const ScanTabletRequest* request,
                           ScanTabletResponse* response,
                           google::protobuf::Closure* done);

    void SetupScanInternalTeraKey(const ScanTabletRequest* request,
                                  std::string* start_tera_key,
                                  std::string* end_row_key);
    void SetupScanRowOptions(const ScanTabletRequest* request,
                             ScanOptions* scan_options);

    bool LowLevelScan(const std::string& start_tera_key,
                      const std::string& end_row_key,
                      const ScanOptions& scan_options,
                      leveldb::Iterator* it,
                      RowResult* value_list,
                      KeyValuePair* next_start_point,
                      uint32_t* read_row_count,
                      uint32_t* read_bytes,
                      bool* is_complete,
                      StatusCode* status);

    void MakeKvPair(leveldb::Slice key, leveldb::Slice col, leveldb::Slice qual,
                    int64_t ts, leveldb::Slice value, KeyValuePair* kv);

    bool ParseRowKey(const std::string& tera_key, std::string* row_key);

private:
    mutable Mutex m_mutex;
    TabletWriter* m_async_writer;

    std::string m_tablet_path;
    const std::string m_start_key;
    const std::string m_end_key;
    std::string m_raw_start_key;
    std::string m_raw_end_key;
    CompactStatus m_compact_status;

    TabletStatus m_status;
    volatile int32_t m_ref_count;
    volatile int32_t m_db_ref_count;
    leveldb::Options m_ldb_options;
    leveldb::DB* m_db;
    bool m_mem_store_activated;
    TableSchema m_table_schema;
    bool m_kv_only;
    std::map<uint64_t, uint64_t> id_to_snapshot_num_;
    std::map<uint64_t, uint64_t> rollbacks_;

    const leveldb::RawKeyOperator* m_key_operator;

    std::map<std::string, uint32_t> m_cf_lg_map;
    std::map<std::string, uint32_t> m_lg_id_map;
    StreamScanManager m_stream_scan;
    StatCounter m_counter;
};

} // namespace io
} // namespace tera

#endif // TERA_IO_TABLET_IO_H_


text:
<?php

declare(strict_types=1);

namespace Inowas\Common\Boundaries;

use Inowas\Common\DateTime\DateTime;

class WellDateTimeValue extends DateTimeValue
{

    public const TYPE = 'wel';

    /** @var float */
    private $pumpingRate;

    public static function fromParams(DateTime $dateTime, float $pumpingRate): WellDateTimeValue
    {
        return new self($dateTime, $pumpingRate);
    }

    /**
     * @param array $arr
     * @return WellDateTimeValue
     * @throws \Exception
     */
    public static function fromArray(array $arr): WellDateTimeValue
    {
        return new self(DateTime::fromAtom($arr['date_time']), $arr['values'][0]);
    }

    /**
     * @param array $arr
     * @return WellDateTimeValue
     * @throws \Exception
     */
    public static function fromArrayValues(array $arr): WellDateTimeValue
    {
        return new self(DateTime::fromAtom($arr[0]), $arr[1]);
    }

    private function __construct(DateTime $dateTime, float $pumpingRate) {
        $this->dateTime = $dateTime;
        $this->pumpingRate = $pumpingRate;
    }

    public function type(): string
    {
        return self::TYPE;
    }

    public function dateTime(): DateTime
    {
        return $this->dateTime;
    }

    public function pumpingRate(): float
    {
        return $this->pumpingRate;
    }

    public function toArray(): array
    {
        return array(
            'date_time' => $this->dateTime->toAtom(),
            'values' => [$this->pumpingRate]
        );
    }

    public function values(): array
    {
        return array(
            'pumping_rate' => $this->pumpingRate
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace media {

// 2MB: approximately 1 minute of 256Kbps content.
// 30MB: approximately 1 minute of 4Mbps content.
const size_t kSourceBufferAudioMemoryLimit = 2 * 1024 * 1024;
const size_t kSourceBufferVideoMemoryLimit = 30 * 1024 * 1024;

}  // namespace media


text:
<?php

namespace Models\Publication;

use Application\Cache\Keys;
use Application\Mvc\Model\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness as UniquenessValidator;

class Publication extends Model
{

    public function getSource()
    {
        return "publication";
    }

    public function initialize()
    {
        $this->hasMany('id', $this->translateModel, 'foreign_id'); // translate

        $this->belongsTo('type_id', 'Models\Publication\Type', 'id', [
            'alias' => 'type'
        ]);
    }

    private $id;
    private $type_id;
    private $slug;
    private $created_at;
    private $updated_at;
    private $date;
    private $preview_src;
    private $preview_inner;

    protected $title;
    protected $text;
    protected $meta_title;
    protected $meta_description;
    protected $meta_keywords;

    protected $translateModel = 'Models\Publication\Translate\PublicationTranslate'; // translate
    protected $translateFields = [
        'title',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'text'
    ];

    public function beforeCreate()
    {
        $this->created_at = date("Y-m-d H:i:s");
    }

    public function beforeUpdate()
    {
        $this->updated_at = date("Y-m-d H:i:s");
    }

    public function afterUpdate()
    {
        parent::afterUpdate();

        $cache = $this->getDi()->get('cache');

        $cache->delete(self::cacheSlugKey($this->getSlug()));

        $this->getDi()->get('cacheManager')->delete([
            Keys::PAGE,
            $this->slug,
            self::$lang
        ]);
    }

    public function validation()
    {
        $validator = new Validation();
        $validator->add('slug', new UniquenessValidator(
            [
                "model"   => $this,
                "message" => $this->getDi()->get('helper')->translate("Publishcation with slug is already exists")
            ]
        ));
        return $this->validate($validator);
    }

    public function afterValidation()
    {
        if (!$this->date) {
            $this->date = date("Y-m-d H:i:s");
        }
    }

    public function updateFields($data)
    {
        if (!$this->getSlug()) {
            $this->setSlug($data['title']);
        }
        if (!$this->getMetaTitle()) {
            $this->setMetaTitle($data['title']);
        }
        $this->setPreviewInner(isset($data['preview_inner']) ? 1 : 0);
    }

    public static function findCachedBySlug($slug)
    {
        $publication = self::findFirst(["slug = '$slug'",
            'cache' => [
                'key'      => self::cacheSlugKey($slug),
                'lifetime' => 60]
        ]);
        return $publication;
    }

    public static function cacheSlugKey($slug)
    {
        $key = HOST_HASH . md5('Models\Publication\Publication; slug = ' . $slug);
        return $key;
    }

    public function setCreatedAt($created_at)
    {
        $this->created_at = $created_at;
        return $this;
    }

    public function getCreatedAt()
    {
        return $this->created_at;
    }

    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setMetaDescription($meta_description)
    {
        $this->setMLVariable('meta_description', $meta_description);
        return $this;
    }

    public function getMetaDescription()
    {
        return $this->getMLVariable('meta_description');
    }

    public function setMetaKeywords($meta_keywords)
    {
        $this->setMLVariable('meta_keywords', $meta_keywords);
        return $this;
    }

    public function getMetaKeywords()
    {
        return $this->getMLVariable('meta_keywords');
    }

    public function setMetaTitle($meta_title)
    {
        $this->setMLVariable('meta_title', $meta_title);
        return $this;
    }

    public function getMetaTitle()
    {
        return $this->getMLVariable('meta_title');
    }

    public function setSlug($slug)
    {
        $this->slug = $slug;
        return $this;
    }

    public function getSlug()
    {
        return $this->slug;
    }

    public function setText($text)
    {
        $this->setMLVariable('text', $text);
        return $this;
    }

    public function getText()
    {
        return $this->getMLVariable('text');
    }

    public function setTitle($title)
    {
        $this->setMLVariable('title', $title);
        return $this;
    }

    public function getTitle()
    {
        return $this->getMLVariable('title');
    }

    public function setUpdatedAt($updated_at)
    {
        $this->updated_at = $updated_at;
        return $this;
    }

    public function getUpdatedAt()
    {
        return $this->updated_at;
    }

    public function setDate($date)
    {
        $this->date = $date;
        return $this;
    }

    public function getDate($format = 'Y-m-d H:i:s')
    {
        if ($format) {
            if ($this->date) {
                return date($format, strtotime($this->date));
            }
        } else {
            return $this->date;
        }
    }

    public function setTypeId($type_id)
    {
        $this->type_id = $type_id;
        return $this;
    }

    public function getTypeId()
    {
        return $this->type_id;
    }

    public function getTypeTitle()
    {
        if ($this->type_id) {
            $types = Type::cachedListArray(['key' => 'id']);
            if (array_key_exists($this->type_id, $types)) {
                return $types[$this->type_id];
            }
        }
    }

    public function getTypeSlug()
    {
        if ($this->type_id) {
            $types = Type::cachedListArray(['key' => 'id', 'value' => 'slug']);
            if (array_key_exists($this->type_id, $types)) {
                return $types[$this->type_id];
            }
        }
    }

    public function getTypeDisplayDate()
    {
        if ($this->type_id) {
            $types = Type::cachedListArray(['key' => 'id', 'value' => 'display_date']);
            if (array_key_exists($this->type_id, $types)) {
                return $types[$this->type_id];
            }
        }
    }

    public function setPreviewInner($preview_inner)
    {
        $this->preview_inner = $preview_inner;
        return $this;
    }

    public function getPreviewInner()
    {
        return $this->preview_inner;
    }

    public function getPreviewSrc()
    {
        return $this->preview_src;
    }

    public function setPreviewSrc($preview_src)
    {
        $this->preview_src = $preview_src;
        return $this;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>GogoTech</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/stylish-portfolio.css" rel="stylesheet">

		<link href="fonts/font-awesome/css/font-awesome.css" rel="stylesheet">

		<link href="css/animations.css" rel="stylesheet">

		<link href="css/style.css" rel="stylesheet">

		<link href="css/custom.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic" rel="stylesheet" type="text/css">

Tidligere prosjekter

All

Nettside

Booking

Nettbutikk


text:
@interface DPHueSettingViewController4 () {
    int lightCount;
    int retryCount;
}
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *lightSearchingIndicator;
@property (weak, nonatomic) IBOutlet UIView *indicator;

@property (weak, nonatomic) IBOutlet UITableView *foundLightListView;
@property (strong, nonatomic) NSString *serial;
@property (weak, nonatomic) UIAlertAction *okAction;

- (IBAction)searchAutomatic:(id)sender;
- (IBAction)searchManual:(id)sender;

@end

@implementation DPHueSettingViewController4

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _foundLightListView.delegate = self;
    _foundLightListView.dataSource = self;
    [_foundLightListView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellLight"];
    [_foundLightListView reloadData];
    if ([_foundLightListView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_foundLightListView setSeparatorInset:UIEdgeInsetsZero];
    }
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    return [[DPHueManager sharedManager] getLightStatus].count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 選択状態の解除
}

// セルの生成と設定
- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Storyboard で設定したidentifier
    static NSString *CellIdentifier = @"cellLight";
    UITableViewCell *cell =
    [tableView dequeueReusableCellWithIdentifier:CellIdentifier
                                    forIndexPath:indexPath];
    cell.exclusiveTouch = YES;
    cell.accessoryView.exclusiveTouch = YES;
    NSString * path = [_bundle pathForResource:@"hue_small_icon" ofType:@"png"];
    cell.imageView.image = [UIImage imageWithContentsOfFile:path];
    NSDictionary* dic = [[DPHueManager sharedManager] getLightStatus];
    int i = 0;
    for (PHLight *light in dic.allValues) {
        if (indexPath.row == i) {

            cell.textLabel.text = light.name;
            break;
        }
        i++;
    }
    return cell;
}

-(void)startIndicator
{
    [_lightSearchingIndicator startAnimating];
    _lightSearchingIndicator.hidden = NO;
}

-(void)stopIndicator
{
    [_lightSearchingIndicator stopAnimating];
    _lightSearchingIndicator.hidden = YES;
}

- (IBAction)searchAutomatic:(id)sender {
    _indicator.hidden = NO;
    retryCount = 2;
    [self startIndicator];
    [manager searchLightWithCompletion:^(NSArray *errors) {
        dispatch_async(dispatch_get_main_queue(), ^{
            lightCount = (int) [[DPHueManager sharedManager] getLightStatus].allValues.count;
            [self reloadHue];
        });
    }];
}

- (IBAction)searchManual:(id)sender {
    float osVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (osVersion > 8.0) {
        UIAlertController *serialAlert = [UIAlertController alertControllerWithTitle:DPHueLocalizedString(_bundle, @"HueSerialNoTitle")
                                                                             message:DPHueLocalizedString(_bundle, @"HueSerialNoDesc")
                                                                      preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:nil];
        [serialAlert addAction:cancelAction];
        _okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            _indicator.hidden = NO;
            [self startIndicator];
            NSArray *serials = @[_serial];
            [manager registerLightForSerialNo:serials completion:^(NSArray *errors) {
                retryCount = 2;
                lightCount = (int) [[DPHueManager sharedManager] getLightStatus].allValues.count;
                [self  reloadHue];
            }];
        }];
        _okAction.enabled = NO;
        [serialAlert addAction:_okAction];

        [serialAlert addTextFieldWithConfigurationHandler:^(UITextField *textField) {

            textField.placeholder = DPHueLocalizedString(_bundle, @"HueSerialNoHint");
            textField.delegate = self;
            textField.keyboardType = UIKeyboardTypeAlphabet;
        }];
        [self presentViewController:serialAlert animated:YES completion:nil];
    } else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:DPHueLocalizedString(_bundle, @"HueSerialNoTitle")
                                                        message:DPHueLocalizedString(_bundle, @"HueSerialNoDesc")
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"OK", nil];
        alert.delegate       = self;
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alert textFieldAtIndex:0].placeholder = DPHueLocalizedString(_bundle, @"HueSerialNoHint");
        [alert textFieldAtIndex:0].delegate = self;
        [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeAlphabet;
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if( buttonIndex == alertView.cancelButtonIndex ) { return; }

    NSString* textValue = [[alertView textFieldAtIndex:0] text];
    if( [textValue length] >= 6 )
    {
        _indicator.hidden = NO;
        [self startIndicator];
        NSArray *serials = @[textValue];
        [manager registerLightForSerialNo:serials completion:^(NSArray *errors) {
            retryCount = 2;
            lightCount = (int) [[DPHueManager sharedManager] getLightStatus].allValues.count;
            [self  reloadHue];
        }];
    }
}

- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSMutableString *text = [textField.text mutableCopy];
    [text replaceCharactersInRange:range withString:string];
    if ([text length] >= 6) {
        _okAction.enabled = YES;
        _serial = text;
    }
    return ([text length] <= 6);
}

- (void)reloadHue
{

    DPHueItemBridge *item = [self getSelectedItemBridge];
    [[DPHueManager sharedManager] initHue];
    [[DPHueManager sharedManager] startAuthenticateBridgeWithIpAddress:item.ipAddress
                                                            macAddress:item.macAddress
                                                              receiver:self
                                        localConnectionSuccessSelector:@selector(didBridgeSuccess)
                                                     noLocalConnection:@selector(didBridgeFailed)
                                                      notAuthenticated:@selector(didBridgeFailed)];
}

- (void)didBridgeSuccess
{
    [[DPHueManager sharedManager] deallocPHNotificationManagerWithReceiver:self];
    [[DPHueManager sharedManager] deallocHueSDK];
    dispatch_queue_t updateQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(updateQueue, ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (retryCount < 0 || lightCount < [[DPHueManager sharedManager] getLightStatus].allValues.count) {
                [_foundLightListView reloadData];
                _indicator.hidden = YES;
                [self stopIndicator];
                if (lightCount < [[DPHueManager sharedManager] getLightStatus].allValues.count) {
                    NSString *successMessage = [DPHueLocalizedString(_bundle, @"HueSearchLight")
                                                stringByAppendingFormat:DPHueLocalizedString(_bundle, @"HueSearchHitLight"),
                                                [[DPHueManager sharedManager] getLightStatus].allValues.count - lightCount];
                    [self showAleart:successMessage];
                } else {
                    [self showAleart:DPHueLocalizedString(_bundle, @"HueSearchLightOld")];
                }
            } else {
                retryCount--;
                [self reloadHue];
            }
        });
    });
}

- (void)didBridgeFailed
{
    [[DPHueManager sharedManager] deallocPHNotificationManagerWithReceiver:self];
    [[DPHueManager sharedManager] deallocHueSDK];
    dispatch_queue_t updateQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(updateQueue, ^{
        dispatch_sync(dispatch_get_main_queue(), ^{
            [[DPHueManager sharedManager] deallocPHNotificationManagerWithReceiver:self];
            [[DPHueManager sharedManager] deallocHueSDK];
            [_foundLightListView reloadData];
            _indicator.hidden = YES;
            [self stopIndicator];
            [self showAleart:DPHueLocalizedString(_bundle, @"HueSearchLightError")];
        });
    });
}

@end


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0016_userprofile_mathjax_url'),
    ]

    operations = [
        migrations.AlterField(
            model_name='userprofile',
            name='personal_project',
            field=models.ForeignKey(to='editor.Project', related_name='personal_project_of', on_delete=django.db.models.deletion.SET_NULL, null=True),
        ),
    ]


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syll. fung. (Abellini) 4: 246 (1886)

#### Original name
Fusidium patellatum Bonord.

### Remarks
null


text:
@interface LSRefreshNativeHeader : LSRefreshComponent

+ (instancetype)nativeHeaderWithActionBlock:(LSRefreshActionBlock)actionBlock;

@end


text:
all: test

test: spec/node.js
	@node spec/node.js

benchmark:
	@node benchmarks/large.js

.PHONY: test benchmark


text:
#include "Collider.h"

#include <cmath>

namespace PolandBall {

namespace Game {

Collider::CollideSide Collider::collides(const std::unique_ptr<Collider>& another) const {
    if (this == another.get()) {
        return SIDE_NONE;
    }

    auto ourBox = this->getCollideBox();
    auto anotherBox = another->getCollideBox();
    float width = 0, height = 0;

    // Their top is inside us
    if ((anotherBox[0].get(Math::Vec3::Y) <= ourBox[0].get(Math::Vec3::Y)) &&
            (anotherBox[0].get(Math::Vec3::Y) >= ourBox[3].get(Math::Vec3::Y)) &&
            !((anotherBox[3].get(Math::Vec3::Y) <= ourBox[0].get(Math::Vec3::Y)) &&
            (anotherBox[3].get(Math::Vec3::Y) >= ourBox[3].get(Math::Vec3::Y)))) {

        bool topRightInside = this->vertexInsideBox(anotherBox[0], ourBox);
        bool topLeftInside = this->vertexInsideBox(anotherBox[1], ourBox);

        if (topLeftInside && topRightInside) {
            return SIDE_BOTTOM;
        }

        if (topLeftInside) {
            width = ourBox[3].get(Math::Vec3::X) - anotherBox[1].get(Math::Vec3::X);
            height = anotherBox[1].get(Math::Vec3::Y) - ourBox[3].get(Math::Vec3::Y);
            return (width > height) ? SIDE_BOTTOM : SIDE_RIGHT;
        }

        if (topRightInside) {
            width = anotherBox[0].get(Math::Vec3::X) - ourBox[2].get(Math::Vec3::X);
            height = anotherBox[0].get(Math::Vec3::Y) - ourBox[2].get(Math::Vec3::Y);
            return (width > height) ? SIDE_BOTTOM : SIDE_LEFT;
        }

        if (!topLeftInside && !topRightInside &&
                anotherBox[1].get(Math::Vec3::X) <= ourBox[1].get(Math::Vec3::X) &&
                anotherBox[0].get(Math::Vec3::X) >= ourBox[0].get(Math::Vec3::X)) {
            return SIDE_BOTTOM;
        }
    // Their bottom is inside us
    } else if ((anotherBox[3].get(Math::Vec3::Y) <= ourBox[0].get(Math::Vec3::Y)) &&
            (anotherBox[3].get(Math::Vec3::Y) >= ourBox[3].get(Math::Vec3::Y)) &&
            !((anotherBox[0].get(Math::Vec3::Y) <= ourBox[0].get(Math::Vec3::Y)) &&
            (anotherBox[0].get(Math::Vec3::Y) >= ourBox[3].get(Math::Vec3::Y)))) {

        bool bottomRightInside = this->vertexInsideBox(anotherBox[3], ourBox);
        bool bottomLeftInside = this->vertexInsideBox(anotherBox[2], ourBox);

        // Both inside (narrorer) or both outside (wider)
        if (bottomLeftInside && bottomRightInside) {
            return SIDE_TOP;
        }

        if (bottomLeftInside) {
            width = ourBox[0].get(Math::Vec3::X) - anotherBox[2].get(Math::Vec3::X);
            height = ourBox[0].get(Math::Vec3::Y) - anotherBox[2].get(Math::Vec3::Y);
            return (width > height) ? SIDE_TOP : SIDE_RIGHT;
        }

        if (bottomRightInside) {
            width = anotherBox[3].get(Math::Vec3::X) - ourBox[1].get(Math::Vec3::X);
            height = ourBox[1].get(Math::Vec3::Y) - anotherBox[3].get(Math::Vec3::Y);
            return (width > height) ? SIDE_TOP : SIDE_LEFT;
        }

        if (!bottomLeftInside && !bottomRightInside &&
                anotherBox[2].get(Math::Vec3::X) <= ourBox[2].get(Math::Vec3::X) &&
                anotherBox[3].get(Math::Vec3::X) >= ourBox[3].get(Math::Vec3::X)) {
            return SIDE_TOP;
        }
    // Their right is inside us
    } else if ((anotherBox[0].get(Math::Vec3::X) <= ourBox[0].get(Math::Vec3::X)) &&
            (anotherBox[0].get(Math::Vec3::X) >= ourBox[1].get(Math::Vec3::X)) &&
            !((anotherBox[1].get(Math::Vec3::X) <= ourBox[0].get(Math::Vec3::X)) &&
            (anotherBox[1].get(Math::Vec3::X) >= ourBox[1].get(Math::Vec3::X)))) {
        // Partial intersection is already covered in previous clauses
        bool rightTopInside = this->vertexInsideBox(anotherBox[0], ourBox);
        bool rightBottomInside = this->vertexInsideBox(anotherBox[3], ourBox);

        if (rightBottomInside && rightTopInside) {
            return SIDE_LEFT;
        }

        if (!rightBottomInside && !rightTopInside &&
                anotherBox[0].get(Math::Vec3::Y) >= ourBox[1].get(Math::Vec3::Y) &&
                anotherBox[3].get(Math::Vec3::Y) <= ourBox[2].get(Math::Vec3::Y)) {
            return SIDE_LEFT;
        }
    // Their left is inside us
    } else if ((anotherBox[1].get(Math::Vec3::X) <= ourBox[0].get(Math::Vec3::X)) &&
            (anotherBox[1].get(Math::Vec3::X) >= ourBox[1].get(Math::Vec3::X)) &&
            !((anotherBox[0].get(Math::Vec3::X) <= ourBox[0].get(Math::Vec3::X)) &&
            (anotherBox[0].get(Math::Vec3::X) >= ourBox[1].get(Math::Vec3::X)))) {
        // Partial intersection is already covered in previous clauses
        bool leftTopInside = this->vertexInsideBox(anotherBox[1], ourBox);
        bool leftBottomInside = this->vertexInsideBox(anotherBox[2], ourBox);

        // Both inside (narrorer) or both outside (wider)
        if (leftBottomInside && leftTopInside) {
            return SIDE_RIGHT;
        }

        if (!leftBottomInside && !leftTopInside &&
                anotherBox[1].get(Math::Vec3::Y) >= ourBox[0].get(Math::Vec3::Y) &&
                anotherBox[2].get(Math::Vec3::Y) <= ourBox[0].get(Math::Vec3::Y)) {
            return SIDE_RIGHT;
        }
    }

    return SIDE_NONE;
}

}  // namespace Game

}  // namespace PolandBall


text:
package com.novarto.sanedbc.guava;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.novarto.sanedbc.hikari.Hikari;
import com.zaxxer.hikari.HikariDataSource;
import fj.control.db.DB;
import fj.function.Try1;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGet;
import static com.novarto.lang.guava.testutil.FuturesTestUtil.awaitAndGetFailure;
import static com.novarto.sanedbc.hikari.Hikari.gracefulShutdown;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

public class SanityTest
{
    private static GuavaDbInterpreter dbAsync;
    private static HikariDataSource ds;
    private static ListeningExecutorService ex;

    @BeforeClass public static void setupHikari()
    {
        ds = Hikari.createHikari("jdbc:hsqldb:mem:JdbcUtilsTest", "sa", "", new Properties());
        ex = MoreExecutors.listeningDecorator(Hikari.createExecutorFor(ds, false));

        dbAsync = new GuavaDbInterpreter(ds, ex);
    }

    @Test public void sanity()
    {
        ListenableFuture<Integer> success = dbAsync.submit(DB.unit(42));

        SQLException ex = new SQLException("failed i have");
        ListenableFuture<Integer> fail = dbAsync.submit(DB.db((Try1<Connection, Integer, SQLException>) c ->
        {
            assertThat(c, is(notNullValue()));
            throw ex;
        }));

        assertThat(awaitAndGet(success), is(42));

        assertThat(awaitAndGetFailure(fail), is(ex));

    }

    @AfterClass public static void shutdownHikari()
    {
        gracefulShutdown(ex, ds);
    }

}


text:
using System;

namespace QuantConnect.Orders
{
    /// <summary>
    /// Limit order type definition
    /// </summary>
    public class LimitOrder : Order
    {
        /// <summary>
        /// Limit price for this order.
        /// </summary>
        public decimal LimitPrice { get; internal set; }

        /// <summary>
        /// Limit Order Type
        /// </summary>
        public override OrderType Type
        {
            get { return OrderType.Limit; }
        }

        /// <summary>
        /// Added a default constructor for JSON Deserialization:
        /// </summary>
        public LimitOrder()
        {
        }

        /// <summary>
        /// New limit order constructor
        /// </summary>
        /// <param name="symbol">Symbol asset we're seeking to trade</param>
        /// <param name="type">Type of the security order</param>
        /// <param name="quantity">Quantity of the asset we're seeking to trade</param>
        /// <param name="time">Time the order was placed</param>
        /// <param name="limitPrice">Price the order should be filled at if a limit order</param>
        /// <param name="tag">User defined data tag for this order</param>
        public LimitOrder(Symbol symbol, int quantity, decimal limitPrice, DateTime time, string tag = "", SecurityType type = SecurityType.Base)
            : base(symbol, quantity, time, tag, type)
        {
            LimitPrice = limitPrice;

            if (tag == "")
            {
                //Default tag values to display limit price in GUI.
                Tag = "Limit Price: " + limitPrice.ToString("C");
            }
        }

        /// <summary>
        /// Gets the value of this order at the given market price.
        /// </summary>
        /// <param name="currentMarketPrice">The current market price of the security</param>
        /// <returns>The value of this order given the current market price</returns>
        public override decimal GetValue(decimal currentMarketPrice)
        {
            // selling, so higher price will be used
            if (Quantity < 0)
            {
                return Math.Max(LimitPrice, currentMarketPrice);
            }

            // buying, so lower price will be used
            if (Quantity > 0)
            {
                return Math.Min(LimitPrice, currentMarketPrice);
            }

            return 0m;
        }

        /// <summary>
        /// Modifies the state of this order to match the update request
        /// </summary>
        /// <param name="request">The request to update this order object</param>
        public override void ApplyUpdateOrderRequest(UpdateOrderRequest request)
        {
            base.ApplyUpdateOrderRequest(request);
            if (request.LimitPrice.HasValue)
            {
                LimitPrice = request.LimitPrice.Value;
            }
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>
        /// A string that represents the current object.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public override string ToString()
        {
            return string.Format("{0} at limit {1}", base.ToString(), LimitPrice.SmartRounding());
        }

        /// <summary>
        /// Creates a deep-copy clone of this order
        /// </summary>
        /// <returns>A copy of this order</returns>
        public override Order Clone()
        {
            var order = new LimitOrder {LimitPrice = LimitPrice};
            CopyTo(order);
            return order;
        }
    }
}


text:
@*
 * Copyright 2021 HM Revenue & Customs
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *@

@import play.api.i18n._
@import views.html.helper._
@import uk.gov.hmrc.play.mappers.DateFields._

@this(
dateInput: ihtHelpers.standard.date_input
)

@(
    formItem:Form[_],
    fieldName: String,
    label: String,
    childFormName: Option[String],
    args:(Symbol,Any)*
)(implicit messages: Messages)

@childFormField={@if(!childFormName.getOrElse("").isEmpty){@childFormName.getOrElse("").}else{}}
@elements = @{ new FieldElements(formItem(childFormField+fieldName).id, formItem(childFormField+fieldName),null,args.toMap, messages) }

@labelAsHeading = @{ elements.args.get('_legendIsHeading).getOrElse(false).asInstanceOf[Boolean] }

@if(elements.args.get('_legend).isDefined) {
  @if(elements.args.get('_fieldsetId).isDefined) {
    <fieldset id="@elements.args.get('_fieldsetId)">
  } else {
    <fieldset class="date-of-birth">
  }
    <legend class="@if(!labelAsHeading){@elements.args.get('_fieldsetId)__legend bold-small } @elements.args.get('_legendClass)">
        @if(labelAsHeading) {

@elements.args.get('_legend)

        } else {
            @elements.args.get('_legend)
        }
    </legend>
}

    @if(elements.args.get('_extraText).isDefined) {

        @elements.args.get('_extraText)

    }

    @if(elements.args.get('_hintText).isDefined) {

            @elements.args.get('_hintText)

    }

    @defining(elements.field.name){fieldName=>
        @elements.errors.map{error => @Messages(error.toString())}
    }

    @dayElem = @{fieldName + "." + day}
    @dateInput(
    formItem(childFormField+dayElem),
    '_label -> Messages("iht.date.day"),
    '_labelClass -> "label--inlineTextinput",
    '_inputClass -> ("form-control " + (if(elements.errors.size>0) "error-field" else "" )),
    '_autoComplete -> "off",
    '_hint -> elements.args.get('_hintId),
    '_lengthMax -> 2,
    '_type -> "number",
    '_dataAttributes -> (if(elements.args.contains('_inputDataAttributes) ){ elements.args.get('_inputDataAttributes)} else "")
    )

    @monthElem = @{fieldName + "." + month}
    @dateInput(
    formItem(childFormField+monthElem),
    '_label -> Messages("iht.date.month"),
    '_labelClass -> "label--inlineTextinput ",
    '_inputClass -> ("form-control " + (if(elements.errors.size>0) "error-field" else "" )),
    '_autoComplete -> "off",
    '_hint -> elements.args.get('_hintId),
    '_lengthMax -> 2,
    '_type -> "number",
    '_dataAttributes -> (if(elements.args.contains('_inputDataAttributes) ){ elements.args.get('_inputDataAttributes)} else "")
    )

    @yearElem = @{fieldName + "." + year}
    @dateInput(
    formItem(childFormField+yearElem),
    '_label -> Messages("iht.date.year"),
    '_labelClass -> "label--inlineTextinput ",
    '_inputClass -> ("form-control " + (if(elements.errors.size>0) "error-field" else "" )),
    '_autoComplete -> "off",
    '_hint -> elements.args.get('_hintId),
    '_lengthMax -> 4,
    '_type -> "number",
    '_dataAttributes -> (if(elements.args.contains('_inputDataAttributes) ){ elements.args.get('_inputDataAttributes)} else "")
    )

@if(elements.args.get('_legend).isDefined) {
</fieldset>
}


text:
// Copyright 2014 Serilog Contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Serilog.Debugging;
using Serilog.Events;

namespace Serilog.Sinks.Loggly
{
    /// <summary>
    /// Converts <see cref="LogEventProperty"/> values into simple scalars,
    /// that render well in Loggly.
    /// </summary>
    static class LogglyPropertyFormatter
    {
        static readonly HashSet<Type> LogglyScalars = new HashSet<Type>
        {
            typeof(bool),
            typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint),
                typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal),
            typeof(byte[])
        };

        /// <summary>
        /// Simplify the object so as to make handling the serialized
        /// representation easier.
        /// </summary>
        /// <param name="value">The value to simplify (possibly null).</param>
        /// <param name="formatProvider">A formatProvider to format DateTime values if a specific format is required.</param>
        /// <returns>A simplified representation.</returns>
        public static object Simplify(LogEventPropertyValue value, IFormatProvider formatProvider)
        {
            var scalar = value as ScalarValue;
            if (scalar != null)
                return SimplifyScalar(scalar.Value, formatProvider);

            var dict = value as DictionaryValue;
            if (dict != null)
            {
                var result = new Dictionary<object, object>();
                foreach (var element in dict.Elements)
                {
                    var key = SimplifyScalar(element.Key.Value, formatProvider);
                    if (result.ContainsKey(key))
                    {
                        SelfLog.WriteLine("The key {0} is not unique in the provided dictionary after simplification to {1}.", element.Key, key);
                        return dict.Elements.Select(e => new Dictionary<string, object>
                        {
                            { "Key", SimplifyScalar(e.Key.Value, formatProvider) },
                            { "Value", Simplify(e.Value, formatProvider) }
                        })
                        .ToArray();
                    }
                    result.Add(key, Simplify(element.Value, formatProvider));
                }
                return result;
            }

            var seq = value as SequenceValue;
            if (seq != null)
                return seq.Elements.Select(propertyValue => Simplify(propertyValue, formatProvider)).ToArray();

            var str = value as StructureValue;
            if (str != null)
            {
                var props = str.Properties.ToDictionary(p => p.Name, p => Simplify(p.Value, formatProvider));
                if (str.TypeTag != null)
                    props["$typeTag"] = str.TypeTag;
                return props;
            }

            return null;
        }

        static object SimplifyScalar(object value, IFormatProvider formatProvider)
        {
            if (value == null) return null;

            var valueType = value.GetType();
            if (LogglyScalars.Contains(valueType)) return value;

            //handle dateTimes with the format provider
            if (value is DateTime)
                return ((DateTime)value).ToString(formatProvider ?? CultureInfo.InvariantCulture);

            if (value is DateTimeOffset)
                return ((DateTimeOffset)value).ToString(formatProvider ?? CultureInfo.InvariantCulture);

            return value.ToString();
        }
    }
}


text: My logotypes (vector).


text:
pub struct Decimal {
    // implement your type here
}

impl Decimal {
    pub fn try_from(_: &str) -> Option<Decimal> {
        unimplemented!()
    }
}


text:
<!DOCTYPE html>

<title>/r/LeagueOfLegends</title>

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.11.1/themes/ui-darkness/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />

/r/LeagueOfLegends Red Tracker

DescriptionDemoDonate

Description

				Easily identify posts with Rioter comments and then quickly navigate through a post's comment section to find Rioter comments with
				the /r/LeagueOfLegends Red Tracker Chrome extension. All posts with Rioter comments are turned red. Once in the comments
				section, an unobtrusive navigation menu lets you scroll directly to Rioter comments. Finally, /r/LeagueOfLegends Red Tracker
				is compatible with Reddit Enhancement Suite.

					Download

Demo

Donate

Footer

Created by Ryan Roach


text:
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, atomic) NSArray *mContactList;
@property (strong, atomic) NSArray *mSectionTitles;
@property (strong, atomic) NSArray *mFilteredContactList;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

	UIBarButtonItem *addContact = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showAddContact)];
	self.navigationItem.rightBarButtonItem = addContact;

	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:kNotificationAddressBookManagerUpdated object:nil];
	//[[AddressBookManager sharedInstance] refreshContacts]; <- Done on applicationDidBecomeActive
	[self loadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Private methods
- (void) showAddContact{
	[AddressBookManager showAddContactOnViewController:self withPhoneNumber:nil];
}

- (void)loadData{
	NSArray *contacts = [[AddressBookManager sharedInstance] contacts];
	if(!contacts || contacts.count == 0){
		return;
	}

	[self setSectionsFromList:contacts];
	[self.tableView reloadData];

	//Just to test
	NSArray *toSynch = [[ABSynchroManager sharedInstance] addressBookModificationsSinceCheckpoint];
	for(ABContact *contact in toSynch){
		NSLog(@"Contact: %@ - Status: %d", contact.compositeName, contact.status);
	}
	[[ABSynchroManager sharedInstance] saveLastRetrievalAsCheckpoint];
}

-(void) setSectionsFromList:(NSArray *)origin{
	if(!origin) return;

	NSMutableArray *contactList = [[NSMutableArray alloc] init];
	NSMutableArray *sectionTitles = [[NSMutableArray alloc] init];
    //Creating sections
    NSMutableArray * sectionArray = nil;
    NSString* lastSection = nil;
    for(ABContact * contact in origin){
        NSString * text = [contact indexCharacter];
        if([text length] == 0){
            NSLog(@"[Warning] empty complete name here ?!?!");
            //strange situation, just skip contact.
            continue;
        }
        if(lastSection && [lastSection compare:text options:NSDiacriticInsensitiveSearch] == NSOrderedSame){
            [sectionArray addObject: contact];
        }
        else {
			if(sectionArray){
				[contactList addObject:sectionArray];
				sectionArray = nil;
			}
            sectionArray = [[NSMutableArray alloc] initWithObjects:contact, nil];
            lastSection = text;
			[sectionTitles addObject:lastSection];
        }
    }
    if(sectionArray && [sectionArray count] > 0){
        [contactList addObject:sectionArray];
    }
    sectionArray = nil;

	self.mContactList = contactList;
	self.mSectionTitles = sectionTitles;
}

- (UITableViewCell*)createContactsCell:(ABContact*) contact{
	static NSString *cellIdentifier = @"ContactsCell";

	UITableViewCell *cell =[self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
	if (cell == nil) {
		//IB engineer approved
		cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
	}

	if([cell.textLabel respondsToSelector:@selector(attributedText)]){
		//Bold contact on iOS6 or above
		NSRange boldRange;
		if(contact.sortingName && contact.sortingName.length > 0){
			boldRange = [contact.fullName rangeOfString:contact.sortingName options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
		}
		else{
			boldRange = NSMakeRange(0, contact.fullName.length);
		}
		NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:contact.fullName];
		[attrStr addAttribute: NSFontAttributeName value:[UIFont boldSystemFontOfSize:[UIFont labelFontSize]] range:boldRange];

		cell.textLabel.attributedText = attrStr;
	}
	else{
		cell.textLabel.text = contact.fullName;
	}

	return cell;
}

- (ABContact*) contactFromTableView:(UITableView*) tableView andIndexPath: (NSIndexPath*) indexPath{
	NSArray *arrayOfContacts = nil;
	if(tableView == self.tableView){
		if(!self.mContactList) return nil;
		arrayOfContacts = [self.mContactList objectAtIndex:indexPath.section];
	}
	else{
		arrayOfContacts = self.mFilteredContactList;
	}

	if(!arrayOfContacts) return nil;
	ABContact *contact = [arrayOfContacts objectAtIndex:indexPath.row];
	return contact;
}

#pragma mark - ABNewPersonViewControllerDelegate
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person{
	if(person){
		[[AddressBookManager sharedInstance] refreshContacts];
	}
	[newPersonView dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - ABPersonViewControllerDelegate
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
	return YES;
}

#pragma mark - UISearchDisplayDelegate

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{

	self.mFilteredContactList = [[AddressBookManager sharedInstance] contactsWithQuery:searchString];

	return YES;
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
	if(tableView == self.tableView){
		if(!self.mContactList) return 1;
		return self.mContactList.count;
	}
	else{
		return 1;
	}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	if(tableView == self.tableView){
		if(!self.mContactList) return 0;
		NSArray *sectionArray = [self.mContactList objectAtIndex:section];
		if(!sectionArray) return 0;
		return sectionArray.count;
	}
	else{
		return self.mFilteredContactList.count;
	}
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	if(tableView == self.tableView){
		return kHEADER_HEIGHT;
	}
	else{
		return 0.0;
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	ABContact *contact = [self contactFromTableView:tableView andIndexPath:indexPath];
	return [self createContactsCell:contact];
}

//Right selector
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
	if(tableView == self.tableView){
		return self.mSectionTitles;
	}
	return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if(tableView == self.tableView){
		return [self.mSectionTitles objectAtIndex:section];
	}
	return nil;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
	if(tableView == self.tableView){
		return index;
	}
	return 0;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	ABContact *contact = [self contactFromTableView:tableView andIndexPath:indexPath];

	[[AddressBookManager sharedInstance] showContact:contact onViewController:self allowingEdition:NO];
}

@end


text:
namespace DeJong.Utilities.Threading
{
    using Logging;
    using System.Diagnostics;
    using System.Threading;

    /// <summary>
    /// Contains general functions for creating basic threads.
    /// </summary>
#if !DEBUG
    [DebuggerStepThrough]
#endif
    public static class ThreadBuilder
    {
        internal static int ProcessID { get { return Process.GetCurrentProcess().Id; } }
        internal static int ThreadID { get { return Thread.CurrentThread.ManagedThreadId; } }

        /// <summary>
        /// Runs a specified function in a STA thread.
        /// </summary>
        /// <param name="function"> The function for the thread to process. </param>
        public static void RunInSTA(ThreadStart function)
        {
            CreateSTA(function).Start();
        }

        /// <summary>
        /// Creates a background thread with its appartment set to <see cref="ApartmentState.STA"/>.
        /// </summary>
        /// <param name="function"> The function for the thread to process. </param>
        /// <param name="name"> The name of the thread (Optional). </param>
        public static Thread CreateSTA(ThreadStart function, string name = "")
        {
            Thread t = CreateBackground(function, name);
            t.SetApartmentState(ApartmentState.STA);
            return t;
        }

        /// <summary>
        /// Runs a specified function in a background thread.
        /// </summary>
        /// <param name="function"> The function for the thread to process. </param>
        public static void RunInBackground(ThreadStart function)
        {
            CreateBackground(function).Start();
        }

        /// <summary>
        /// Creates a thread with <see cref="Thread.IsBackground"/> set to <see langword="true"/>.
        /// </summary>
        /// <param name="func"> The function for the thread to process. </param>
        /// <param name="name"> The name of the thread (Optional). </param>
        public static Thread CreateBackground(ThreadStart func, string name = "")
        {
            Thread t = new Thread(func) { IsBackground = true };
            if (!string.IsNullOrEmpty(name))
            {
                t.Name = name;
                Log.Info(nameof(ThreadBuilder), $"Created background thread '{t.Name}'({t.ManagedThreadId})");
            }
            else Log.Info(nameof(ThreadBuilder), $"Created background thread({t.ManagedThreadId})");
            return t;
        }
    }
}


text:
package org.apache.lucene.analysis.snowball;

import java.io.IOException;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.tartarus.snowball.SnowballProgram;

/**
 * A filter that stems words using a Snowball-generated stemmer.
 *
 * Available stemmers are listed in {@link org.tartarus.snowball.ext}.
 */
public final class SnowballFilter extends TokenFilter {

  private SnowballProgram stemmer;

  private TermAttribute termAtt;

  public SnowballFilter(TokenStream input, SnowballProgram stemmer) {
    super(input);
    this.stemmer = stemmer;
    termAtt = addAttribute(TermAttribute.class);
  }

  /**
   * Construct the named stemming filter.
   *
   * Available stemmers are listed in {@link org.tartarus.snowball.ext}.
   * The name of a stemmer is the part of the class name before "Stemmer",
   * e.g., the stemmer in {@link org.tartarus.snowball.ext.EnglishStemmer} is named "English".
   *
   * @param in the input tokens to stem
   * @param name the name of a stemmer
   */
  public SnowballFilter(TokenStream in, String name) {
    super(in);
    try {
      Class<?> stemClass = Class.forName("org.tartarus.snowball.ext." + name + "Stemmer");
      stemmer = (SnowballProgram) stemClass.newInstance();
    } catch (Exception e) {
      throw new RuntimeException(e.toString());
    }
    termAtt = addAttribute(TermAttribute.class);
  }

  /** Returns the next input Token, after being stemmed */
  @Override
  public final boolean incrementToken() throws IOException {
    if (input.incrementToken()) {
      String originalTerm = termAtt.term();
      stemmer.setCurrent(originalTerm);
      stemmer.stem();
      String finalTerm = stemmer.getCurrent();
      // Don't bother updating, if it is unchanged.
      if (!originalTerm.equals(finalTerm))
        termAtt.setTermBuffer(finalTerm);
      return true;
    } else {
      return false;
    }
  }
}


text:
JavaScript implementation of Publish/Subscribe pattern.

## Usage

Create a Signal object

```
var signal = new SignalService();
```
You can create many signal service objects to provide isolation.

**Subscribe**

```
signal.subscribe('buy-fruits', function (a, b) {
  console.log('Function 1 : ', a, b);
});

signal.subscribe('buy-fruits', function () {
  console.log('Function 2');
});
```

Subscribe associates message and handler functions to respond to publish later. You can add as many functions to a message. Functions are executed in the subscribed order.

**Publish**

```
signal.publish('buy-fruits', 'apple', 'pineapple');
// Function 1 : apple pineapple
// Function 2
```

Publish calls already subscribed functions with the arguments provided.


text:
namespace CircuitSimulation.UI
{
    partial class FormOptions
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.buttonSetDelay = new System.Windows.Forms.Button();
            this.labelDelay = new System.Windows.Forms.Label();
            this.textBoxDelay = new System.Windows.Forms.TextBox();
            this.okButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // buttonSetDelay
            //
            this.buttonSetDelay.Location = new System.Drawing.Point(247, 69);
            this.buttonSetDelay.Name = "buttonSetDelay";
            this.buttonSetDelay.Size = new System.Drawing.Size(75, 23);
            this.buttonSetDelay.TabIndex = 0;
            this.buttonSetDelay.Text = "Set";
            this.buttonSetDelay.UseVisualStyleBackColor = true;
            //
            // labelDelay
            //
            this.labelDelay.AutoSize = true;
            this.labelDelay.Location = new System.Drawing.Point(36, 75);
            this.labelDelay.Name = "labelDelay";
            this.labelDelay.Size = new System.Drawing.Size(34, 13);
            this.labelDelay.TabIndex = 1;
            this.labelDelay.Text = "Delay";
            //
            // textBoxDelay
            //
            this.textBoxDelay.Location = new System.Drawing.Point(111, 72);
            this.textBoxDelay.Name = "textBoxDelay";
            this.textBoxDelay.Size = new System.Drawing.Size(100, 20);
            this.textBoxDelay.TabIndex = 2;
            //
            // okButton
            //
            this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.okButton.Location = new System.Drawing.Point(340, 189);
            this.okButton.Name = "okButton";
            this.okButton.Size = new System.Drawing.Size(75, 23);
            this.okButton.TabIndex = 25;
            this.okButton.Text = "&OK";
            //
            // FormOptions
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(437, 224);
            this.Controls.Add(this.okButton);
            this.Controls.Add(this.textBoxDelay);
            this.Controls.Add(this.labelDelay);
            this.Controls.Add(this.buttonSetDelay);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MinimizeBox = false;
            this.Name = "FormOptions";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Options";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button buttonSetDelay;
        private System.Windows.Forms.Label labelDelay;
        private System.Windows.Forms.TextBox textBoxDelay;
        private System.Windows.Forms.Button okButton;
    }
}