text:
@interface CollectionViewExampleViewController () <UICollectionViewDelegateFlowLayout>

@end

@implementation CollectionViewExampleViewController {
    NSArray *_items;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    static ExampleCollectionViewCell *prototypeCell;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        prototypeCell = [[ExampleCollectionViewCell alloc] init];
    });
    [prototypeCell setItem:_items[(NSUInteger) indexPath.item]];
    CGSize size = collectionView.bounds.size;
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *) collectionViewLayout;
    if (flowLayout.scrollDirection == UICollectionViewScrollDirectionVertical) {
        size.height = [prototypeCell requiredHeightForWidth:size.width];
    }
    else
    {
        size.width = [prototypeCell requiredWidthForHeight:size.height];
    }

    return size;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _items.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewItem *item = _items[(NSUInteger) indexPath.item];
    ExampleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell setItem:item];
    return cell;
}

#pragma mark - UICollectionViewController

- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)layout {
    self = [super initWithCollectionViewLayout:layout];
    if (self) {
        _items = [CollectionViewItem randomItems];
    }
    return self;
}

#pragma mark - UIViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor lightGrayColor];
    [self.collectionView registerClass:[ExampleCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    if ([self.collectionView.collectionViewLayout respondsToSelector:@selector(setEstimatedItemSize:)]) {
        UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *) self.collectionView.collectionViewLayout;
        //layout.estimatedItemSize = CGSizeMake(100, self.collectionView.bounds.size.width * 0.159f);
    }
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self.collectionView.collectionViewLayout invalidateLayout];
}

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    [self.collectionView.collectionViewLayout invalidateLayout];
    ((UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout).estimatedItemSize = CGSizeMake(size.width, size.width*0.159f);
}

@end


text:
<?php

namespace Oro\Bundle\EntityMergeBundle\Controller;

use Doctrine\ORM\EntityManager;
use Oro\Bundle\DataGridBundle\Extension\MassAction\MassActionDispatcher;
use Oro\Bundle\EntityConfigBundle\Config\ConfigManager;
use Oro\Bundle\EntityMergeBundle\Data\EntityData;
use Oro\Bundle\EntityMergeBundle\Data\EntityDataFactory;
use Oro\Bundle\EntityMergeBundle\Doctrine\DoctrineHelper;
use Oro\Bundle\EntityMergeBundle\Exception\ValidationException;
use Oro\Bundle\EntityMergeBundle\Form\Type\MergeType;
use Oro\Bundle\EntityMergeBundle\Model\EntityMergerInterface;
use Oro\Bundle\SecurityBundle\Annotation\Acl;
use Oro\Bundle\SecurityBundle\Annotation\AclAncestor;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

/**
 * Provides action for simple and multiple merge.
 *
 * @Route("/merge")
 */
class MergeController extends AbstractController
{
    /**
     * @Route("/{gridName}/massAction/{actionName}", name="oro_entity_merge_massaction")
     * @AclAncestor("oro_entity_merge")
     * @Template("OroEntityMergeBundle:Merge:merge.html.twig")
     * @param Request $request
     * @param string $gridName
     * @param string $actionName
     * @return array|RedirectResponse
     */
    public function mergeMassActionAction(Request $request, $gridName, $actionName)
    {
        /** @var MassActionDispatcher $massActionDispatcher */
        $massActionDispatcher = $this->get(MassActionDispatcher::class);

        $response = $massActionDispatcher->dispatchByRequest($gridName, $actionName, $request);

        $entityData = $this->getEntityDataFactory()->createEntityData(
            $response->getOption('entity_name'),
            $response->getOption('entities')
        );

        return $this->mergeAction($request, $entityData);
    }

    /**
     * @Route(name="oro_entity_merge")
     * @Acl(
     *      id="oro_entity_merge",
     *      label="oro.entity_merge.acl.merge",
     *      type="action",
     *      category="entity"
     * )
     * @Template()
     * @param Request $request
     * @param EntityData|null $entityData
     * @return array|RedirectResponse
     */
    public function mergeAction(Request $request, EntityData $entityData = null)
    {
        if (!$entityData) {
            $className = $request->get('className');
            $ids = (array)$request->get('ids');

            $entityData = $this->getEntityDataFactory()->createEntityDataByIds($className, $ids);
        } else {
            $className = $entityData->getClassName();
        }

        $constraintViolations = $this->getValidator()->validate($entityData, null, ['validateCount']);
        if ($constraintViolations->count()) {
            foreach ($constraintViolations as $violation) {
                /* @var ConstraintViolation $violation */
                $this->get('session')->getFlashBag()->add(
                    'error',
                    $violation->getMessage()
                );
            }

            return $this->redirect($this->generateUrl($this->getEntityIndexRoute($entityData->getClassName())));
        }

        $form = $this->createForm(
            MergeType::class,
            $entityData,
            [
                'metadata' => $entityData->getMetadata(),
                'entities' => $entityData->getEntities(),
            ]
        );

        if ($request->isMethod('POST')) {
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $merger = $this->getEntityMerger();

                try {
                    $this->getEntityManager()->transactional(
                        function () use ($merger, $entityData) {
                            $merger->merge($entityData);
                        }
                    );
                } catch (ValidationException $exception) {
                    foreach ($exception->getConstraintViolations() as $violation) {
                        /* @var ConstraintViolation $violation */
                        $this->get('session')->getFlashBag()->add(
                            'error',
                            $violation->getMessage()
                        );
                    }
                }

                $this->get('session')->getFlashBag()->add(
                    'success',
                    $this->get(TranslatorInterface::class)->trans('oro.entity_merge.controller.merged_successful')
                );

                return $this->redirect(
                    $this->generateUrl(
                        $this->getEntityViewRoute($entityData->getClassName()),
                        ['id' => $entityData->getMasterEntity()->getId()]
                    )
                );
            }
        }

        return [
            'formAction' => $this->generateUrl(
                'oro_entity_merge',
                [
                    'className' => $className,
                    'ids' => $this->getDoctineHelper()->getEntityIds($entityData->getEntities()),
                ]
            ),
            'entityLabel' => $entityData->getMetadata()->get('label'),
            'cancelPath' => $this->generateUrl($this->getEntityIndexRoute($className)),
            'form' => $form->createView()
        ];
    }

    /**
     * Get route name for entity view page by class name
     *
     * @param string $className
     * @return string
     */
    protected function getEntityViewRoute($className)
    {
        return $this->getConfigManager()->getEntityMetadata($className)->routeView;
    }

    /**
     * Get route name for entity index page by class name
     *
     * @param string $className
     * @return string
     */
    protected function getEntityIndexRoute($className)
    {
        return $this->getConfigManager()->getEntityMetadata($className)->routeName;
    }

    /**
     * @return ConfigManager
     */
    protected function getConfigManager()
    {
        return $this->get(ConfigManager::class);
    }

    /**
     * @return EntityDataFactory
     */
    protected function getEntityDataFactory()
    {
        return $this->get(EntityDataFactory::class);
    }

    /**
     * @return DoctrineHelper
     */
    protected function getDoctineHelper()
    {
        return $this->get(DoctrineHelper::class);
    }

    /**
     * @return EntityMergerInterface
     */
    protected function getEntityMerger()
    {
        return $this->get(EntityMergerInterface::class);
    }

    /**
     * @return EntityManager
     */
    protected function getEntityManager()
    {
        return $this->get('doctrine')->getManager();
    }

    /**
     * @return ValidatorInterface
     */
    protected function getValidator()
    {
        return $this->get(ValidatorInterface::class);
    }

    /**
     * @return array
     */
    public static function getSubscribedServices()
    {
        return array_merge(
            parent::getSubscribedServices(),
            [
                ConfigManager::class,
                EntityDataFactory::class,
                DoctrineHelper::class,
                EntityMergerInterface::class,
                ValidatorInterface::class,
                MassActionDispatcher::class,
                TranslatorInterface::class,
            ]
        );
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Week 8 Cultural</title>
  <link rel="stylesheet" href="stylesheets/reset.css">
  <link rel="stylesheet" href="stylesheets/blog_post_stylesheet.css">
  <link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'>

CONTACT

ABOUT

PORTFOLIO

BLOG

Week 8 Cultural

Dealing With Conflict

By Steve Ono, Posted on July 27, 2014

Dealing With Conflict

I can recall many conflicts that I've had with my family members over the years. I think these are probably the most common source of conflict in my life. One in particular comes to mind where myself and my father had a disagreement about how to make a business decision. Being business partners, these things come up quite often, and sometimes we dont see eye to eye.

In this case, I knew my stance was the correct one. That isnt always the case, but this time is most definitely was. Due to this fact, I was considerably more confrontational than I normally would have been. This negative energy made the conflict worse, and it resulted in little progress and much wasted time. My actions did not help the situation.

Looking back on this and many other conflicts, I am quick to make my point, regardless of how it comes across to the other person (usually my dad). This is a destructive habit because it alienates people, and usually results in the exact opposite of what you are trying to achieve or debate. I've been slowly and steadily doing things differently when these things come up. I've noticed that I react much better when I give myself a few minutes to cool off before responding. This is actually extremely effective for me.

When these things happen, I learn a little bit more each time about how pointless it is to get upset over small things. Small things shouldn't be ignored, but they should not cause the flare ups that tend to occur, particularly with family members. At the end of the day, its just not worth it and I never look back on it as a positive thing.

RUBY

JAVASCRIPT

HTML5

CSS3

SQL


text:
package com.trevjonez.inject;

/**
 * Base type to enable multi-binding via dagger2.
 *
 * @author TrevJonez
 */
public interface ComponentBuilder<T, C extends PlainComponent<T>> {
    C build();
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>University of Chicago - Network Visualization</title>

    <link href="assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
    <link href="assets/css/font-awesome.min.css" rel="stylesheet" media="screen">
    <link href="assets/css/simple-line-icons.css" rel="stylesheet" media="screen">
    <link href="assets/css/animate.css" rel="stylesheet">

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

        <title>Gephi Seadragon Export</title>

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#custom-collapse">Menu
                        Toggle navigation

                    </button>
                    Joshua Gary Mausolf

About

Knowledge Lab Profile

Contact

University of Chicago Network Visualization

                    Tweet
                    Follow @Joshua_Mausolf

                    Follow @jmausolf

Department Circles
 - 1941-2015 -

Department Circles
- No Edge Labeled -

Department Circles
 - Edges Labeled -

Department Spider
 - No Labels -

Department Spider
 - With Legend -

Department Spider
 - Top Universities -

Time Lapse
 - All Years -

Time Lapse
 - Video Visualization -

ABOUT THESE VISUALIZATIONS

                            These visualizations were created in Gephi by Joshua Mausolf as part of a larger collaboration with scholars Aaron Gerow, Bowen Lou, Eamon Duede, and James Evans of the Knowledge Lab at the University of Chicago.

                            For more information on these projects and others, please visit us at the  Knowledge Lab.

                         © Joshua Gary Mausolf


text:
package com.ibm.watson.app.qaclassifier.services.entities.tracking;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import com.ibm.watson.app.qaclassifier.services.jpa.EntityConstants;
import com.ibm.watson.app.qaclassifier.util.rest.MessageKey;

@NamedQueries({
    @NamedQuery(
            name = EntityConstants.QUERY_CONVERSATION_EVENTS,
            query = "SELECT e from TrackingEventEntity e WHERE e.user = :user ORDER BY e.id ASC"),
    @NamedQuery(
            name = EntityConstants.QUERY_ALL_EVENTS,
            query = "SELECT e from TrackingEventEntity e ORDER BY e.id ASC")
})
@Entity
@Table(name = "TRACKING_EVENTS")
@DiscriminatorColumn(name = "EVENT_TYPE")
public abstract class TrackingEventEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "ID")
    private long id;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "TIMESTAMP", nullable = false)
    private Date timestamp;

    @Column(name = "USER", nullable = false)
    private String user;

    @Column(name = "HOST", nullable = false)
    private String host;

    public TrackingEventEntity() {
    }

    public TrackingEventEntity(Date timestamp, String user, String host) {
        this.timestamp = timestamp;
        this.user = user;
        this.host = host;
    }

    protected void checkRequiredField(String fieldName, Object fieldValue) {
        if (fieldValue == null) {
            throw new IllegalArgumentException(
            		MessageKey.AQWQAC24100E_field_name_required_field_on_object_and_not_null_2.getMessage(fieldName, getClass().getName()).getFormattedMessage()
            		);
        }
    }

    public long getId() {
        return id;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    /**
     * All events have an optional referrer.  Subclasses are left to implement this method
     * since each subclass limits its referral to a specific subclass type.
     * @return The referral for this event, or null if no referral exists
     */
    public abstract TrackingEventEntity getReferral();

    /**
     * Subclasses can't annotate fields as nullable=false because all subclass entities are
     * stored in the same table.  Subclasses should check required fields by calling
     * checkRequiredField(String, Object).
     *
     * @throws IllegalArgumentException if a required field is not set
     */
    @PrePersist
    protected abstract void checkRequiredFields() throws IllegalArgumentException;

    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
                .append("user", this.user)
                .append("host", this.host)
                .append("id", this.id)
                .toString();
    }
}


text:
// Visual Studio Shared Project
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED ON AN  *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.Text.Classification;

namespace TestUtilities {
    public class Classification {
        public readonly int Start, End;
        public readonly string Text;
        public readonly string ClassificationType;

        public Classification(string classificationType, int start, int end, string text) {
            ClassificationType = classificationType;
            Start = start;
            End = end;
            Text = text;
        }

        public static void Verify(IList<ClassificationSpan> spans, params Classification[] expected) {
            bool passed = false;
            try {
                for (int i = 0; i < spans.Count; i++) {
                    if (i >= expected.Length) {
                        Assert.Fail();
                        break;
                    }

                    var curSpan = spans[i];

                    int start = curSpan.Span.Start.Position;
                    int end = curSpan.Span.End.Position;

                    string spanInfo = string.Format("Span #{0}: {1}", i, expected[i].Text);
                    Assert.AreEqual(expected[i].Start, start, spanInfo);
                    Assert.AreEqual(expected[i].End, end, spanInfo);
                    Assert.AreEqual(expected[i].Text, curSpan.Span.GetText(), spanInfo);
                    Assert.IsTrue(curSpan.ClassificationType.IsOfType(expected[i].ClassificationType),
                        "Classifier incorrect for '{0}'.  Expected:{1} Actual:{2}", expected[i].Text, expected[i].ClassificationType, curSpan.ClassificationType);
                }

                passed = true;
            } finally {
                if (!passed) {
                    // Output expected and actual results as Classification objects for easy diffing and copy-pasting.

                    Console.WriteLine("Expected:\r\n" +
                        String.Join(",\r\n",
                            expected.Select(cls =>
                                String.Format("new Classification(\"{0}\", {1}, {2}, \"{3}\")",
                                    cls.ClassificationType,
                                    cls.Start,
                                    cls.End,
                                    FormatString(cls.Text)
                                )
                            )
                        )
                    );

                    Console.WriteLine("Actual:\r\n" +
                        String.Join(",\r\n",
                            spans.Select(curSpan =>
                                String.Format("new Classification(\"{0}\", {1}, {2}, \"{3}\")",
                                    curSpan.ClassificationType.Classification,
                                    curSpan.Span.Start.Position,
                                    curSpan.Span.End.Position,
                                    FormatString(curSpan.Span.GetText())
                                )
                            )
                        )
                    );
                }
            }
        }

        public static string FormatString(string p) {
            StringBuilder res = new StringBuilder();
            for (int i = 0; i < p.Length; i++) {
                switch (p[i]) {
                    case '\\': res.Append("\\\\"); break;
                    case '\n': res.Append("\\n"); break;
                    case '\r': res.Append("\\r"); break;
                    case '\t': res.Append("\\t"); break;
                    case '"': res.Append("\\\""); break;
                    default: res.Append(p[i]); break;
                }
            }
            return res.ToString();
        }

    }

}


text:
import { Wrapper } from '../../../src/ad/wrapper'
import testBase from './_abstract'

describe('Wrapper', () => {
  const createInstance = () => {
    const inst = new Wrapper()
    return inst
  }

  testBase(createInstance)

  describe('#followAdditionalWrappers', () => {
    it('equals to true by default', () => {
      const inst = createInstance()
      expect(inst.followAdditionalWrappers).to.equal(true)
    })
    it('sets followAdditionalWrappers', () => {
      const inst = createInstance()
      const value = false
      inst.followAdditionalWrappers = value
      expect(inst.followAdditionalWrappers).to.equal(value)
    })
  })

  describe('#allowMultipleAds', () => {
    it('equals to false by default', () => {
      const inst = createInstance()
      expect(inst.allowMultipleAds).to.equal(false)
    })
    it('sets allowMultipleAds', () => {
      const inst = createInstance()
      const value = true
      inst.allowMultipleAds = value
      expect(inst.allowMultipleAds).to.equal(value)
    })
  })

  describe('#fallbackOnNoAd', () => {
    it('sets fallbackOnNoAd', () => {
      const inst = createInstance()
      const value = true
      inst.fallbackOnNoAd = value
      expect(inst.fallbackOnNoAd).to.equal(value)
    })
  })

  describe('#vastAdTagURI', () => {
    it('sets vastAdTagURI', () => {
      const inst = createInstance()
      const value = 'https://example.com/tag'
      inst.vastAdTagURI = value
      expect(inst.vastAdTagURI).to.equal(value)
    })
  })

  describe('#$type', () => {
    it('is Wrapper', () => {
      const inst = createInstance()
      expect(inst.$type).to.equal('Wrapper')
    })
  })
})


text:
<!doctype html>
<html class="no-js" lang="en">
<head>
	<meta charset="utf-8">
	<title>An example from http://rwd.education</title>
	<meta name="description" content="An example from the book, 'Responsive Web Design with HTML5 and CSS3' by Ben Frain">
	<meta name="viewport" content="width=device-width">
	<meta name="theme-color" content="#ff9900">
	<link rel="stylesheet" href="styles.css">
</head>
<body>
	<img class="HRH" src="queen@2x-1024x747.png"/>
</body>
</html>


text:
apt-get update && \
apt-get install -y libfontconfig zip npm git apt-transport-https ca-certificates curl openssl && \
npm i -g npm && \
npm cache clean -f && \
npm install -g n && \
n stable && \
node --version && \
npm --version && \
bundle install


text:
import {isPresent, BaseException} from 'changular2/src/facade/lang';
import {ListWrapper, MapWrapper} from 'changular2/src/facade/collection';

export class Locals {
  parent:Locals;
  current:Map;

  constructor(parent:Locals, current:Map) {
    this.parent = parent;
    this.current = current;
  }

  contains(name:string):boolean {
    if (MapWrapper.contains(this.current, name)) {
      return true;
    }

    if (isPresent(this.parent)) {
      return this.parent.contains(name);
    }

    return false;
  }

  get(name:string) {
    if (MapWrapper.contains(this.current, name)) {
      return MapWrapper.get(this.current, name);
    }

    if (isPresent(this.parent)) {
      return this.parent.get(name);
    }

    throw new BaseException(`Cannot find '${name}'`);
  }

  set(name:string, value) {
    // TODO(rado): consider removing this check if we can guarantee this is not
    // exposed to the public API.
    // TODO: vsavkin maybe it should check only the local map
    if (MapWrapper.contains(this.current, name)) {
      MapWrapper.set(this.current, name, value);
    } else {
      throw new BaseException('Setting of new keys post-construction is not supported.');
    }
  }

  clearValues() {
    MapWrapper.clearValues(this.current);
  }
}


text:
exports.isEmpty = function(obj) {
    // null and undefined are "empty"
    if (obj == null || obj == undefined) return true;

    // Assume if it has a length property with a non-zero value
    // that that property is correct.
    if (obj.length > 0)    return false;
    if (obj.length === 0)  return true;

    // Check files
    if (obj.name !== null || obj.name !== undefined) return false;

    // Otherwise, does it have any properties of its own?
    // Note that this doesn't handle
    // toString and valueOf enumeration bugs in IE < 9
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) return true;
    }

    return false;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="first_keyline">24dp</dimen>
    <dimen name="second_keyline">80dp</dimen>
    <dimen name="toolbar_h_padding">12dp</dimen>
</resources>


text:
\section{Jupter Notebook}

\subsection{Change Jupyter Notebook startup folder (Windows)}
Copy the Jupyter Notebook launcher from the menu to the desktop.
Right click on the new launcher and change the Target field, change \verb|%USERPROFILE%| to the full path of the folder which will contain all the notebooks.
Double-click on the Jupyter Notebook desktop launcher (icon shows [IPy]) to start the Jupyter Notebook App. The notebook interface will appear in a new browser window or tab. A secondary terminal window (used only for error logging and for shut down) will be also opened.


text:
@interface AxcQRCodeVC ()

@property(nonatomic, assign)CGFloat QRCodeSideLength;
@property(nonatomic, strong)NSArray *MsgArr;
@property(nonatomic, strong)NSString *QRCodeMsg;
@property(nonatomic, strong)UIColor *QRColor;

@property(nonatomic, strong)UIImageView *qrImageView;

@property(nonatomic, strong)UIButton *ModifyOneBtn;
@property(nonatomic, strong)UIButton *ModifyTwoBtn;
@property(nonatomic, strong)UIButton *ModifyThreeBtn;

@end

@implementation AxcQRCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = YES;

    self.QRCodeSideLength = 200 ;
    self.QRCodeMsg = [self.MsgArr firstObject];
    self.QRColor = [UIColor AxcUI_ArcColor];

    [self autoLayout];
    self.instructionsLabel.text = @"使用类函数入参传值\n只能每次执行一遍该函数才会进行绘制二维码";

}

// 类参传值,只能每次执行来达到动态调整  ************************************************
- (void)click_ModifyOneBtn{
    self.QRColor = [UIColor AxcUI_ArcColor];
    self.qrImageView.image = [UIImage AxcUI_codeImageWithString:self.QRCodeMsg
                                                           size:self.QRCodeSideLength
                                                          color:self.QRColor];
}
- (void)click_ModifyTwoBtn{
    self.QRCodeMsg = [self.MsgArr objectAtIndex:arc4random()%self.MsgArr.count];
    self.qrImageView.image = [UIImage AxcUI_codeImageWithString:self.QRCodeMsg
                                                           size:self.QRCodeSideLength
                                                          color:self.QRColor];
}
- (void)click__ModifyThreeBtn{
    self.qrImageView.image = [UIImage AxcUI_codeImageWithString:self.QRCodeMsg
                                                           size:self.QRCodeSideLength
                                                          color:self.QRColor
                                                           icon:[UIImage imageNamed:@"found_icons_4"]
                                                      iconWidth:30];
}

- (void)autoLayout{
    [self.view addSubview:self.qrImageView];
    [self.qrImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(100);
        make.centerX.mas_equalTo(0);
    }];

    __weak typeof(self) WeakSelf = self;
    [self.ModifyOneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(WeakSelf.qrImageView.mas_bottom).offset(10);
        make.height.mas_equalTo(44);
    }];
    [self.ModifyTwoBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(WeakSelf.ModifyOneBtn.mas_bottom).offset(10);
        make.height.mas_equalTo(44);
    }];
    [self.ModifyThreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(20);
        make.right.mas_equalTo(-20);
        make.top.mas_equalTo(WeakSelf.ModifyTwoBtn.mas_bottom).offset(10);
        make.height.mas_equalTo(44);
    }];
}

#pragma mark - 懒加载
- (UIButton *)ModifyThreeBtn{
    if (!_ModifyThreeBtn) {
        _ModifyThreeBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 250, 30)];
        [_ModifyThreeBtn setTitle:@"点击添加头像/Logo" forState:UIControlStateNormal];
        [_ModifyThreeBtn setTitleColor:[UIColor AxcUI_BelizeHoleColor] forState:UIControlStateNormal];
        _ModifyThreeBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        _ModifyThreeBtn.backgroundColor = [UIColor AxcUI_CloudColor];
        _ModifyThreeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_ModifyThreeBtn addTarget:self action:@selector(click__ModifyThreeBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_ModifyThreeBtn];
    }
    return _ModifyThreeBtn;
}
- (UIButton *)ModifyTwoBtn{
    if (!_ModifyTwoBtn) {
        _ModifyTwoBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 250, 30)];
        [_ModifyTwoBtn setTitle:@"点击修改二维码信息" forState:UIControlStateNormal];
        [_ModifyTwoBtn setTitleColor:[UIColor AxcUI_BelizeHoleColor] forState:UIControlStateNormal];
        _ModifyTwoBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        _ModifyTwoBtn.backgroundColor = [UIColor AxcUI_CloudColor];
        _ModifyTwoBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_ModifyTwoBtn addTarget:self action:@selector(click_ModifyTwoBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_ModifyTwoBtn];
    }
    return _ModifyTwoBtn;
}
- (UIButton *)ModifyOneBtn{
    if (!_ModifyOneBtn) {
        _ModifyOneBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 250, 30)];
        [_ModifyOneBtn setTitle:@"点击修改二维码颜色" forState:UIControlStateNormal];
        [_ModifyOneBtn setTitleColor:[UIColor AxcUI_BelizeHoleColor] forState:UIControlStateNormal];
        _ModifyOneBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        _ModifyOneBtn.backgroundColor = [UIColor AxcUI_CloudColor];
        _ModifyOneBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_ModifyOneBtn addTarget:self action:@selector(click_ModifyOneBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_ModifyOneBtn];
    }
    return _ModifyOneBtn;
}
- (UIImageView *)qrImageView{
    if (!_qrImageView) {
        UIImage *qrCodeImage = [UIImage AxcUI_codeImageWithString:self.QRCodeMsg
                                                             size:self.QRCodeSideLength
                                                            color:[UIColor AxcUI_EmeraldColor]];
        _qrImageView = [[UIImageView alloc]initWithImage:qrCodeImage];
        _qrImageView.center = self.view.center;
        _qrImageView.axcUI_Y = _qrImageView.axcUI_Y - 100;
        _qrImageView.layer.cornerRadius = 5;
        _qrImageView.layer.masksToBounds = YES;
        _qrImageView.layer.borderWidth = 1;
        _qrImageView.layer.borderColor =[ [UIColor grayColor] CGColor];
        _qrImageView.axcUI_Size = CGSizeMake(self.QRCodeSideLength, self.QRCodeSideLength);
    }
    return _qrImageView;
}
- (NSArray *)MsgArr{
    if (!_MsgArr) {
        _MsgArr = @[@"https://github.com/axclogo/AxcUIKit-Sample",
                    @"https://github.com/axclogo/AxcUIKit-Sample/tree/master/AxcUIKit.xcodeproj",
                    @"https://github.com/axclogo/AxcUIKit-Sample/blob/master/README.md",
                    @"https://www.baidu.com/",
                    @"https://www.google.se/?gfe_rd=cr&ei=8RAxWd-FMsH18AeyvreoCw",
                    @"http://app.cnmo.com/android/4090/gonglue_f424056.html",
                    @"http://blog.csdn.net/kaitiren/article/details/38513715"];
    }
    return _MsgArr;
}

@end


text:
html.fp-enabled,
.fp-enabled body {
    margin: 0;
    padding: 0;
    overflow:hidden;

    /*Avoid flicker on slides transitions for mobile phones #336 */
    -webkit-tap-highlight-color: rgba(0,0,0,0);
}
.fp-section {
    position: relative;
    -webkit-box-sizing: border-box; /* Safari<=5 Android<=3 */
    -moz-box-sizing: border-box; /* <=28 */
    box-sizing: border-box;
    height: 100%;
    display: block;
}
.fp-slide {
    float: left;
}
.fp-slide, .fp-slidesContainer {
    height: 100%;
    display: block;
}
.fp-slides {
    z-index:1;
    height: 100%;
    overflow: hidden;
    position: relative;
    -webkit-transition: all 0.3s ease-out; /* Safari<=6 Android<=4.3 */
    transition: all 0.3s ease-out;
}
.fp-table{
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
}
.fp-slidesContainer {
    float: left;
    position: relative;
}
.fp-controlArrow {
    -webkit-user-select: none; /* webkit (safari, chrome) browsers */
    -moz-user-select: none; /* mozilla browsers */
    -khtml-user-select: none; /* webkit (konqueror) browsers */
    -ms-user-select: none; /* IE10+ */
    position: absolute;
    z-index: 4;
    top: 50%;
    cursor: pointer;
    margin-top: -38px;
    -webkit-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
}
.fp-prev{
    left: 15px;
}
.fp-next{
    right: 15px;
}
.fp-arrow{
    width: 0;
    height: 0;
    border-style: solid;
}
.fp-arrow.fp-prev {
    border-width: 38.5px 34px 38.5px 0;
    border-color: transparent #fff transparent transparent;
}
.fp-arrow.fp-next {
    border-width: 38.5px 0 38.5px 34px;
    border-color: transparent transparent transparent #fff;
}
.fp-notransition {
    -webkit-transition: none !important;
    transition: none !important;
}
#fp-nav {
    position: fixed;
    z-index: 100;
    top: 50%;
    opacity: 1;
    transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    -webkit-transform: translate3d(0,-50%,0);
}
#fp-nav.fp-right {
    right: 17px;
}
#fp-nav.fp-left {
    left: 17px;
}
.fp-slidesNav{
    position: absolute;
    z-index: 4;
    opacity: 1;
    -webkit-transform: translate3d(0,0,0);
    -ms-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
    left: 0 !important;
    right: 0;
    margin: 0 auto !important;
}
.fp-slidesNav.fp-bottom {
    bottom: 17px;
}
.fp-slidesNav.fp-top {
    top: 17px;
}
#fp-nav ul,
.fp-slidesNav ul {
  margin: 0;
  padding: 0;
}
#fp-nav ul li,
.fp-slidesNav ul li {
    display: block;
    width: 14px;
    height: 13px;
    margin: 7px;
    position:relative;
}
.fp-slidesNav ul li {
    display: inline-block;
}
#fp-nav ul li a,
.fp-slidesNav ul li a {
    display: block;
    position: relative;
    z-index: 1;
    width: 100%;
    height: 100%;
    cursor: pointer;
    text-decoration: none;
}
#fp-nav ul li a.active span,
.fp-slidesNav ul li a.active span,
#fp-nav ul li:hover a.active span,
.fp-slidesNav ul li:hover a.active span{
    height: 12px;
    width: 12px;
    margin: -6px 0 0 -6px;
    border-radius: 100%;
 }
#fp-nav ul li a span,
.fp-slidesNav ul li a span {
    border-radius: 50%;
    position: absolute;
    z-index: 1;
    height: 4px;
    width: 4px;
    border: 0;
    background: #333;
    left: 50%;
    top: 50%;
    margin: -2px 0 0 -2px;
    -webkit-transition: all 0.1s ease-in-out;
    -moz-transition: all 0.1s ease-in-out;
    -o-transition: all 0.1s ease-in-out;
    transition: all 0.1s ease-in-out;
}
#fp-nav ul li:hover a span,
.fp-slidesNav ul li:hover a span{
    width: 10px;
    height: 10px;
    margin: -5px 0px 0px -5px;
}
#fp-nav ul li .fp-tooltip {
    position: absolute;
    top: -2px;
    color: #fff;
    font-size: 14px;
    font-family: arial, helvetica, sans-serif;
    white-space: nowrap;
    max-width: 220px;
    overflow: hidden;
    display: block;
    opacity: 0;
    width: 0;
    cursor: pointer;
}
#fp-nav ul li:hover .fp-tooltip,
#fp-nav.fp-show-active a.active + .fp-tooltip {
    -webkit-transition: opacity 0.2s ease-in;
    transition: opacity 0.2s ease-in;
    width: auto;
    opacity: 1;
}
#fp-nav ul li .fp-tooltip.fp-right {
    right: 20px;
}
#fp-nav ul li .fp-tooltip.fp-left {
    left: 20px;
}
.fp-auto-height.fp-section,
.fp-auto-height .fp-slide{
    height: auto !important;
    min-height: auto !important;
}

.fp-responsive .fp-is-overflow.fp-section{
    height: auto !important;
}

/* Used with autoScrolling: false */
.fp-scrollable.fp-responsive .fp-is-overflow.fp-section,
.fp-scrollable .fp-section,
.fp-scrollable .fp-slide{
   /* Fallback for browsers that do not support Custom Properties */
   height: 100vh;
   height: calc(var(--vh, 1vh) * 100);
}

.fp-scrollable.fp-responsive .fp-is-overflow.fp-section:not(.fp-auto-height),
.fp-scrollable .fp-section:not(.fp-auto-height),
.fp-scrollable .fp-slide:not(.fp-auto-height){
    /* Fallback for browsers that do not support Custom Properties */
    min-height: 100vh;
    min-height: calc(var(--vh, 1vh) * 100);
}

/* Disabling vertical centering on scrollable elements */
.fp-overflow{
    justify-content: flex-start;
    max-height: 100%;
}

.fp-is-overflow .fp-overflow.fp-auto-height-responsive,
.fp-is-overflow .fp-overflow.fp-auto-height,
.fp-is-overflow > .fp-overflow{
    overflow-y: auto;
}
.fp-overflow{
    outline:none;
}

.fp-overflow.fp-table{
    display: block;
}

.fp-responsive .fp-auto-height-responsive.fp-section,
.fp-responsive .fp-auto-height-responsive .fp-slide{
    height: auto !important;
    min-height: auto !important;
}

/*Only display content to screen readers*/
.fp-sr-only{
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
}

/* Customize website's scrollbar like Mac OS
Not supports in Firefox and IE */
.fp-scroll-mac .fp-overflow::-webkit-scrollbar {
    background-color: transparent;
    width: 9px;
}
.fp-scroll-mac .fp-overflow::-webkit-scrollbar-track {
    background-color: transparent;
}
.fp-scroll-mac .fp-overflow::-webkit-scrollbar-thumb {
    background-color: rgba(0,0,0,.4);
    border-radius: 16px;
    border: 4px solid transparent;
}
.fp-warning,
.fp-watermark{
    z-index: 9999999;
    position: absolute;
    bottom: 0;
}
.fp-warning,
.fp-watermark a{
    text-decoration: none;
    color: #000;
    background: rgba(255,255,255,0.6);
    padding: 5px 8px;
    font-size: 14px;
    font-family: arial;
    color: black;
    display: inline-block;
    border-radius: 3px;
    margin: 12px;
}
.fp-noscroll .fp-overflow{
    overflow: hidden;
}


text:
package com.betfair.publicapi.types.exchange.v5;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for GetMarketReq complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="GetMarketReq">
 *   <complexContent>
 *     <extension base="{http://www.betfair.com/publicapi/types/exchange/v5/}APIRequest">
 *       <sequence>
 *         <element name="locale" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="marketId" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="includeCouponLinks" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetMarketReq", propOrder = {
    "locale",
    "marketId",
    "includeCouponLinks"
})
public class GetMarketReq
    extends APIRequest
{

    @XmlElement(required = true, nillable = true)
    protected String locale;
    protected int marketId;
    protected boolean includeCouponLinks;

    /**
     * Gets the value of the locale property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLocale() {
        return locale;
    }

    /**
     * Sets the value of the locale property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLocale(String value) {
        this.locale = value;
    }

    /**
     * Gets the value of the marketId property.
     *
     */
    public int getMarketId() {
        return marketId;
    }

    /**
     * Sets the value of the marketId property.
     *
     */
    public void setMarketId(int value) {
        this.marketId = value;
    }

    /**
     * Gets the value of the includeCouponLinks property.
     *
     */
    public boolean isIncludeCouponLinks() {
        return includeCouponLinks;
    }

    /**
     * Sets the value of the includeCouponLinks property.
     *
     */
    public void setIncludeCouponLinks(boolean value) {
        this.includeCouponLinks = value;
    }

}


text:
/*
 * NNTPSwitch Server Configuration
 *
 * $Id: server.c,v 1.20 2011-02-16 07:21:08 tommy Exp $
 */

#include "aconfig.h"
#include "nntpd.h"
#include "memory.h"
#include "aprotos.h"

int linenr;
char lastgroups[MAX_CFGLINE];
int lastlevel;

/* sort function */
int cmp_server_level(const void *a, const void *b)
{
	const SERVER *s1 = *((const SERVER **) a);
	const SERVER *s2 = *((const SERVER **) b);

	if ( s1->Level > s2->Level )
		return -1;

	if ( s1->Level < s2->Level )
		return 1;

	return 0;
}

PROTO void clear_servers(void)
{
	master->numservers = 0;
}

PROTO void reload_servers(void)
{
	struct stat _stat;

	if ( stat(cfg.ServerFile, &_stat) == -1 )
		die("Can't stat server config file %s", cfg.ServerFile);

	if ( master->laststatserver < _stat.st_mtime )
	{
		clear_servers();
		load_servers();
	}
}

PROTO void load_servers(void)
{
	FILE *f;
	struct stat _stat;
	char buf[MAX_CFGLINE];
	SERVER *def;
	int i,s;

	if ( (f=fopen(cfg.ServerFile,"r")) == NULL )
		die("Can't open server config %s", cfg.ServerFile);

	linenr = 0;
	lastgroups[0] = 0;
	lastlevel = 0;

	while( fgets(buf, MAX_CFGLINE, f) )
	{
		chop(buf);
		linenr++;

		if ( buf[0] == ';' || buf[0] == '#' || buf[0] == 0 )
			continue;

		if ( strncasecmp(buf, "server", 6) == 0 )
			parsecfg_server(buf,f);
		else
			die("Syntax error in %s on line %d", cfg.ServerFile, linenr);
	}
	fclose(f);

	def = getserver("default");
	if ( def  == NULL )
		die("Server \"default\" not defined");

	/* Sort the servers by level which we'll use later */
	s=0;
	for (i=0; i<master->numservers; i++ )
		if ( (master->servers+i) != def )
			master->lservers[s++] = (master->servers+i);

	qsort(master->lservers, master->numservers-1, sizeof(SERVER*), cmp_server_level);

	stat(cfg.ServerFile,&_stat);
	master->laststatserver = _stat.st_mtime;

	/* clear the balance position list */
	for ( i=0; i< MAX_LEVEL; i++ )
		master->balance_pos[i] = 0;

        check_server_redundancy();

	info("Loaded %d Servers", master->numservers);
}

PROTO void parsecfg_server(char *buf, FILE *f)
{
	char key[64], val[MAX_CFGLINE];
	int i;
	SERVER *def;

	if ( (sscanf(buf, "%s %s", key, val)) != 2 )
		die("Server Syntax error on line %d of %s", linenr, cfg.ServerFile);

	/* Some basic initialization */
	(master->servers+master->numservers)->MaxConnections = 0;

	if ( strcmp(val, "default") != 0 )
	{
		/* we inherit (copy) from default server */
		if ( (def = getserver("default")) == NULL )
			die("Could not retrieve default server, the default server must be listed first.");

		memcpy((master->servers+master->numservers), def, sizeof(SERVER));
	}
	strcpy((master->servers+master->numservers)->Name, val);

        if ( getserver(val) != NULL )
            die("Servername \"%s\" already defined online %d of %s", val, linenr, cfg.ServerFile);

	i=0;
	while( !i && fgets(buf, MAX_CFGLINE, f) )
	{
		chop(buf);

		linenr++;
		if ( buf[0] == ';' || buf[0] == '#' || buf[0] == 0 )
			continue;

		if ( strncasecmp(buf, "end", 3) == 0 )
		{
			i++;
			break;
		}

		if ( sscanf(buf, "%*[ \t]%64s%*[ \t]%16384s[^\r\n]%*[\t\r\n]", key, val) != 2 )
			die("Error on line %d of %s (%s - %s)", linenr, cfg.ServerFile, key, val);

		/* start scanning parameters */

		if ( strcasecmp(key, "hostname") == 0 )
			strcpy((master->servers+master->numservers)->Hostname, val);
		else
		if ( strcasecmp(key, "groups") == 0 )
		{
			if ( lastgroups == NULL || strcmp(lastgroups, val) )
			{
				strcpy(lastgroups, val);
				lastlevel ++;
			}
			strcpy((master->servers+master->numservers)->Groups, val);
			(master->servers+master->numservers)->Level = lastlevel;
		}
		else
		if ( strcasecmp(key, "Username") == 0 )
			strcpy((master->servers+master->numservers)->Username, val);
		else
		if ( strcasecmp(key, "Password") == 0 )
			strcpy((master->servers+master->numservers)->Password, val);
		else
		if ( strcasecmp(key, "timeout") == 0 )
			(master->servers+master->numservers)->Timeout = atoi(val);
		else
		if ( strcasecmp(key, "port") == 0 )
			(master->servers+master->numservers)->Port = atoi(val);
		else
		if ( strcasecmp(key, "maxconnections") == 0 )
			(master->servers+master->numservers)->MaxConnections = atoi(val);
		else
		if ( strcasecmp(key, "type") == 0 )
		{
			if ( strcasecmp(val, "spool") == 0 )
				(master->servers+master->numservers)->ServerType = type_spool;
			else
			if ( strcasecmp(val, "xover") == 0 )
				(master->servers+master->numservers)->ServerType = type_xover;
			else
			if ( strcasecmp(val, "post") == 0 )
				(master->servers+master->numservers)->ServerType = type_post;
			else
				die("Unknown server type on line %d of %s", linenr, cfg.ServerFile);
		}
		else
		if ( strcasecmp(key, "policy") == 0 )
		{
			if ( strcasecmp(val, "single") == 0 )
				(master->servers+master->numservers)->Policy = policy_single;
			else
			if ( strcasecmp(val, "backup") == 0 )
				(master->servers+master->numservers)->Policy = policy_backup;
			else
			if ( strcasecmp(val, "balance") == 0 )
				(master->servers+master->numservers)->Policy = policy_balance;
			else
				die("Unknown server policy on line %d of %s", linenr, cfg.ServerFile);
		}
		else
		if ( strcasecmp(key, "activetimes") == 0 )
		{
			if ( strcasecmp(val, "false") == 0 )
				(master->servers+master->numservers)->ActiveTimes = 0;
			else
			if ( strcasecmp(val, "true") == 0 )
				(master->servers+master->numservers)->ActiveTimes = 1;
			else
				(master->servers+master->numservers)->ActiveTimes = atoi(val);
		}
		else
		if ( strcasecmp(key, "descriptions") == 0 )
		{
			if ( strcasecmp(val, "false") == 0 )
				(master->servers+master->numservers)->Descriptions = 0;
			else
			if ( strcasecmp(val, "true") == 0 )
				(master->servers+master->numservers)->Descriptions = 1;
			else
				(master->servers+master->numservers)->Descriptions = atoi(val);
		}
		else
		if ( strcasecmp(key, "splitlist") == 0 )
		{
			if ( strcasecmp(val, "false") == 0 )
				(master->servers+master->numservers)->SplitList = 0;
			else
			if ( strcasecmp(val, "true") == 0 )
				(master->servers+master->numservers)->SplitList = 1;
			else
				(master->servers+master->numservers)->SplitList = atoi(val);
		}
		else
			info("Unknown servers.conf option: %s %s", key, val);
	}

	master->numservers++;
}

PROTO SERVER* getserver(const char *name)
{
	int i;

	for (i=0; i<master->numservers; i++)
		if ( strcmp((master->servers+i)->Name, name) == 0 )
			return (master->servers+i);

	return NULL;
}

/*
 * count the number of servers with the same level as us
 */

int count_server_level(int level)
{
	int i;
	int num = 0;

	for (i=0; i<master->numservers; i++)
		if ( (master->servers+i)->Level == level )
			num++;

	return num;
}

/*
 * Increase the current server number
 */

void add_level_usage(int lv)
{
	int max = count_server_level(lv);

	/* roll the number */
	master->balance_pos[lv]++;
	if ( master->balance_pos[lv] >= max )
		master->balance_pos[lv] = 0;
}

/*
 * get the next server from the list
 */

SERVER * get_next_server(int lv)
{
	int i, num;

	/* otherwise we have to pick one according to the balancer */
	num = master->balance_pos[lv];

	for (i=0; i<master->numservers-1; i++)
	{
		if ( master->lservers[i]->Level == lv )
		{

			if ( num == 0 )
			{
				add_level_usage(lv);

				uint max = master->lservers[i]->MaxConnections;
				uint cur = master->lservers[i]->connections;
				if ( max != 0 && cur >= max )
					return get_next_server(lv);

				return master->lservers[i];
			}
			num--;
		}
	}

	return NULL;
}

/*
 * select first server based on some servername
 */

PROTO SERVER* selectserver_primary(const char *name)
{
	SERVER *s;

	s = getserver(name);
	if ( (int)s->connections < 0 ) {
		syslog(LOG_NOTICE, "Server %s has < 0 connections (%d)", s->Name, s->connections);
	}

	/* in case of backup scheme, check for maxconnections on server */
	if ( s->Policy == policy_backup && (s->MaxConnections != 0 && s->connections >= s->MaxConnections) )
		return get_next_server(s->Level);

	/* single or backup policy's just pick the first server */
	if ( s == NULL || s->Policy == policy_single || s->Policy == policy_backup )
		return s;

	s = get_next_server(s->Level);

	if ( s == NULL )
		syslog(LOG_DEBUG, "Hmm, could not find the other balancing server for %s", name);

	return s;
}

/*
 * Find the next server with the same level. This most likely
 * is a backup servers. Give backup servers the same level
 * in the servers.conf.
 */
PROTO SERVER* selectserver_backup(SERVER *current, SERVER *primary)
{
	SERVER *s;

	/* dont check single server policies */
	if ( current == NULL || current->Policy == policy_single )
		return NULL;

	s = get_next_server(primary->Level);

	/* too bad, no backup server */
	if ( s == NULL )
		syslog(LOG_DEBUG, "No next server for policy in %s", current->Name);

	return s;
}

/*
 * Connect to a backend server taking the backup and balancing
 * policies in account. Return false on some error, true on
 * success.
 */
PROTO int connect_groupserver(CLIENT *cl, char *server)
{
	SERVER *svr, *primary;

	svr = getserver(server);
	if ( cl->connected == 1 && strcmp(cl->groupserver->Groups, svr->Groups) == 0 )
		return CONNECT_OK;

	/* disconnect first if we have to change server */
	if ( cl->connected == 1 && strcmp(cl->groupserver->Name, server) != 0 )
		disconnect_server(cl);

	if ( cl->connected != 1 )
	{
		/* Get the real server and take balancing stuff in account */
		if ( (svr=selectserver_primary(server)) == NULL )
			return CONNECT_ERR;

		primary = svr;  /* remember where we started with */
		cl->groupserver = svr;

		if ( connect_server(cl, svr) )
		{
			if ( errno )
				errno = 0;

			/* On server down find backup servers and try to conect to them */
			while( cl->connected != 1 && (svr = selectserver_backup(cl->groupserver, primary)) != NULL )
			{
				cl->groupserver = svr;
				if ( connect_server(cl, svr) )
					if ( errno )
						errno = 0;
			}

			if ( cl->connected != 1 )
			{
				cl->group = NULL;
				cl->groupserver = NULL;
				return CONNECT_DOWN;
			}
		}
	}

	return CONNECT_OK;
}

/*
 * Check if servers configured with backup actually do have a backup server configured.
 */

PROTO void check_server_redundancy(void)
{
	int i;
        SERVER *s;
        int lev = -1;

	for (i=0; i<master->numservers-1; i++)
	{
                if ( master->lservers[i]->Level == lev )
                    continue;

		if (  master->lservers[i]->Policy == policy_backup
                   || master->lservers[i]->Policy == policy_balance )
		{
                    lev = master->lservers[i]->Level;
                        info("Checking server: %s", master->lservers[i]->Name);
                        add_level_usage(lev);
                        s = get_next_server( master->lservers[i]->Level );
                        if ( s == NULL || s == master->lservers[i] ) {
                                die("Configuration error, no secondary server found, for server %s", master->lservers[i]->Name);
                        }
		}
	}
}


text:
package com.jackwink.tweakable.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.SOURCE)
public @interface TwkFloat {
    // If this string is empty, preference will be added to the root screen.
    // By providing a name, this will create a subscreen for the preference
    String screen() default "";

    // If this string is empty, preference will be added to the screen root
    String category() default "";

    // If string is empty, this will use the field name.
    String title() default "";

    // Description of the value
    String summary() default "";

    float maxValue() default Float.MAX_VALUE;

    float minValue() default Float.MIN_VALUE;
}


text:
using namespace himan;
using namespace std;

lambert_conformal_grid::lambert_conformal_grid(HPScanningMode theScanningMode, const point& theFirstPoint, size_t ni,
                                               size_t nj, double di, double dj, double orientation,
                                               double standardParallel1, double standardParallel2,
                                               const earth_shape<double>& earthShape, bool firstPointIsProjected,
                                               const std::string& theName)
    : regular_grid(kLambertConformalConic, theScanningMode, di, dj, ni, nj, false, theName)
{
	itsLogger = logger("lambert_conformal_grid");

	if (IsMissing(earthShape.A()) && IsMissing(earthShape.B()))
	{
		itsLogger.Fatal("Cannot create area without knowing earth shape");
		himan::Abort();
	}

	const std::string ref =
	    fmt::format("+proj=lcc +lat_1={} +lat_2={} +lat_0={} +lon_0={} {} +units=m +no_defs +wktext", standardParallel1,
	                standardParallel2, standardParallel1, orientation, earthShape.Proj4String());

	itsSpatialReference = std::unique_ptr<OGRSpatialReference>(new OGRSpatialReference());
	itsSpatialReference->importFromProj4(ref.c_str());

#if GDAL_VERSION_MAJOR > 1
	itsSpatialReference->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
#endif

	CreateCoordinateTransformations(theFirstPoint, firstPointIsProjected);
	itsLogger.Trace(Proj4String());
}

lambert_conformal_grid::lambert_conformal_grid(HPScanningMode theScanningMode, const point& theFirstPoint, size_t ni,
                                               size_t nj, double di, double dj,
                                               std::unique_ptr<OGRSpatialReference> spRef, bool firstPointIsProjected,
                                               const std::string& theName)
    : regular_grid(kLambertConformalConic, theScanningMode, di, dj, ni, nj, false, theName)
{
	itsLogger = logger("lambert_conformal_grid");
	itsSpatialReference = std::move(spRef);

#if GDAL_VERSION_MAJOR > 1
	itsSpatialReference->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
#endif

	CreateCoordinateTransformations(theFirstPoint, firstPointIsProjected);
	itsLogger.Trace(Proj4String());
}

lambert_conformal_grid::lambert_conformal_grid(const lambert_conformal_grid& other) : regular_grid(other)
{
	itsLogger = logger("lambert_conformal_grid");
	itsSpatialReference = std::unique_ptr<OGRSpatialReference>(other.itsSpatialReference->Clone());
	itsLatLonToXYTransformer = std::unique_ptr<OGRCoordinateTransformation>(other.itsLatLonToXYTransformer->Clone());
	itsXYToLatLonTransformer = std::unique_ptr<OGRCoordinateTransformation>(other.itsXYToLatLonTransformer->Clone());
}

void lambert_conformal_grid::CreateCoordinateTransformations(const point& firstPoint, bool firstPointIsProjected)
{
	ASSERT(itsSpatialReference);
	ASSERT(itsSpatialReference->IsProjected());

	auto geogCS = std::unique_ptr<OGRSpatialReference>(itsSpatialReference->CloneGeogCS());

	itsLatLonToXYTransformer = std::unique_ptr<OGRCoordinateTransformation>(
	    OGRCreateCoordinateTransformation(geogCS.get(), itsSpatialReference.get()));
	itsXYToLatLonTransformer = std::unique_ptr<OGRCoordinateTransformation>(
	    OGRCreateCoordinateTransformation(itsSpatialReference.get(), geogCS.get()));

	double lat = firstPoint.Y(), lon = firstPoint.X();

	if (firstPointIsProjected == false)
	{
		if (!itsLatLonToXYTransformer->Transform(1, &lon, &lat))
		{
			itsLogger.Error("Failed to get false easting and northing");
			return;
		}
	}

	// HIMAN-336: limit false easting/northing accuracy to four decimal places (millimeters)

	lon = util::round(lon, 4);
	lat = util::round(lat, 4);

	if (fabs(lon) < 1e-4 and fabs(lat) < 1e-4)
	{
		return;
	}

	const double orientation = Orientation();
	const double parallel1 = StandardParallel1();
	const double parallel2 = StandardParallel2();

	const double fe = itsSpatialReference->GetProjParm(SRS_PP_FALSE_EASTING, 0.0) - lon;
	const double fn = itsSpatialReference->GetProjParm(SRS_PP_FALSE_NORTHING, 0.0) - lat;

	// need to recreate spatial reference to get SetLCC to accept new falsings
	itsSpatialReference = std::unique_ptr<OGRSpatialReference>(itsSpatialReference->CloneGeogCS());
	if (itsSpatialReference->SetLCC(parallel1, parallel2, parallel1, orientation, fe, fn) != OGRERR_NONE)
	{
		itsLogger.Error("Failed to create LCC projection");
		return;
	}

	itsLatLonToXYTransformer = std::unique_ptr<OGRCoordinateTransformation>(
	    OGRCreateCoordinateTransformation(geogCS.get(), itsSpatialReference.get()));
	itsXYToLatLonTransformer = std::unique_ptr<OGRCoordinateTransformation>(
	    OGRCreateCoordinateTransformation(itsSpatialReference.get(), geogCS.get()));
}

size_t lambert_conformal_grid::Hash() const
{
	vector<size_t> hashes;
	hashes.push_back(Type());
	hashes.push_back(FirstPoint().Hash());
	hashes.push_back(Ni());
	hashes.push_back(Nj());
	hashes.push_back(hash<double>{}(Di()));
	hashes.push_back(hash<double>{}(Dj()));
	hashes.push_back(ScanningMode());
	hashes.push_back(hash<double>{}(Orientation()));
	hashes.push_back(hash<double>{}(StandardParallel1()));
	hashes.push_back(hash<double>{}(StandardParallel2()));
	return boost::hash_range(hashes.begin(), hashes.end());
}

double lambert_conformal_grid::Orientation() const
{
	return itsSpatialReference->GetProjParm(SRS_PP_CENTRAL_MERIDIAN, MissingDouble());
}
bool lambert_conformal_grid::operator!=(const grid& other) const
{
	return !(other == *this);
}
bool lambert_conformal_grid::operator==(const grid& other) const
{
	const lambert_conformal_grid* g = dynamic_cast<const lambert_conformal_grid*>(&other);

	if (g)
	{
		return EqualsTo(*g);
	}

	return false;
}

bool lambert_conformal_grid::EqualsTo(const lambert_conformal_grid& other) const
{
	if (!regular_grid::EqualsTo(other))
	{
		return false;
	}

	if (!itsSpatialReference->IsSame(other.itsSpatialReference.get()))
	{
		itsLogger.Trace("Areas are not equal");
		return false;
	}

	return true;
}

unique_ptr<grid> lambert_conformal_grid::Clone() const
{
	return unique_ptr<grid>(new lambert_conformal_grid(*this));
}

ostream& lambert_conformal_grid::Write(std::ostream& file) const
{
	regular_grid::Write(file);

	file << "__itsOrientation__ " << Orientation() << endl
	     << "__itsStandardParallel1__ " << StandardParallel1() << endl
	     << "__itsStandardParallel2__ " << StandardParallel2() << endl;

	return file;
}

double lambert_conformal_grid::StandardParallel1() const
{
	return itsSpatialReference->GetProjParm(SRS_PP_STANDARD_PARALLEL_1, 0.0);
}
double lambert_conformal_grid::StandardParallel2() const
{
	return itsSpatialReference->GetProjParm(SRS_PP_STANDARD_PARALLEL_2, 0.0);
}

double lambert_conformal_grid::Cone() const
{
	const double sp1 = StandardParallel1(), sp2 = StandardParallel2();

	if (fabs(sp1 - sp2) < 0.0001)
	{
		return sin(fabs(sp1) * constants::kDeg);
	}

	return (log(cos(sp1 * constants::kDeg)) - log(cos(sp2 * constants::kDeg))) /
	       (log(tan((90 - fabs(sp1)) * constants::kDeg * 0.5)) - log(tan(90 - fabs(sp2)) * constants::kDeg * 0.5));
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using ECS_Engine.Engine.Managers;

namespace ECS_Engine.Engine.Systems.Interfaces {
    /// <summary>
    /// Interface for all update systems.
    /// </summary>
    public interface IUpdateSystem : ISystem{
        void Update(GameTime gametime, ComponentManager componentManager, MessageManager messageManager, SceneManagerFacade sceneManager);
    }
}


text:
package org.elasticsearch.action.search;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.OriginalIndices;
import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchException;
import org.elasticsearch.search.SearchShardTarget;
import org.elasticsearch.transport.RemoteClusterAware;

import java.io.IOException;

import static org.elasticsearch.common.xcontent.XContentParserUtils.ensureExpectedToken;

/**
 * Represents a failure to search on a specific shard.
 */
public class ShardSearchFailure extends ShardOperationFailedException {

    private static final String REASON_FIELD = "reason";
    private static final String NODE_FIELD = "node";
    private static final String INDEX_FIELD = "index";
    private static final String SHARD_FIELD = "shard";

    public static final ShardSearchFailure[] EMPTY_ARRAY = new ShardSearchFailure[0];

    private SearchShardTarget shardTarget;

    ShardSearchFailure(StreamInput in) throws IOException {
        shardTarget = in.readOptionalWriteable(SearchShardTarget::new);
        if (shardTarget != null) {
            index = shardTarget.getFullyQualifiedIndexName();
            shardId = shardTarget.getShardId().getId();
        }
        reason = in.readString();
        status = RestStatus.readFrom(in);
        cause = in.readException();
    }

    public ShardSearchFailure(Exception e) {
        this(e, null);
    }

    public ShardSearchFailure(Exception e, @Nullable SearchShardTarget shardTarget) {
        super(shardTarget == null ? null : shardTarget.getFullyQualifiedIndexName(),
            shardTarget == null ? -1 : shardTarget.getShardId().getId(),
            ExceptionsHelper.stackTrace(e),
            ExceptionsHelper.status(ExceptionsHelper.unwrapCause(e)),
            ExceptionsHelper.unwrapCause(e));

        final Throwable actual = ExceptionsHelper.unwrapCause(e);
        if (actual instanceof SearchException) {
            this.shardTarget = ((SearchException) actual).shard();
        } else if (shardTarget != null) {
            this.shardTarget = shardTarget;
        }
    }

    /**
     * The search shard target the failure occurred on.
     */
    @Nullable
    public SearchShardTarget shard() {
        return this.shardTarget;
    }

    @Override
    public String toString() {
        return "shard [" + (shardTarget == null ? "_na" : shardTarget) + "], reason [" + reason + "], cause [" +
                (cause == null ? "_na" : ExceptionsHelper.stackTrace(cause)) + "]";
    }

    public static ShardSearchFailure readShardSearchFailure(StreamInput in) throws IOException {
        return new ShardSearchFailure(in);

    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        out.writeOptionalWriteable(shardTarget);
        out.writeString(reason);
        RestStatus.writeTo(out, status);
        out.writeException(cause);
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        {
            builder.field(SHARD_FIELD, shardId());
            builder.field(INDEX_FIELD, index());
            if (shardTarget != null) {
                builder.field(NODE_FIELD, shardTarget.getNodeId());
            }
            builder.field(REASON_FIELD);
            builder.startObject();
            ElasticsearchException.generateThrowableXContent(builder, params, cause);
            builder.endObject();
        }
        builder.endObject();
        return builder;
    }

    public static ShardSearchFailure fromXContent(XContentParser parser) throws IOException {
        XContentParser.Token token;
        ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser);
        String currentFieldName = null;
        int shardId = -1;
        String indexName = null;
        String clusterAlias = null;
        String nodeId = null;
        ElasticsearchException exception = null;
        while((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token.isValue()) {
                if (SHARD_FIELD.equals(currentFieldName)) {
                    shardId  = parser.intValue();
                } else if (INDEX_FIELD.equals(currentFieldName)) {
                    indexName  = parser.text();
                    int indexOf = indexName.indexOf(RemoteClusterAware.REMOTE_CLUSTER_INDEX_SEPARATOR);
                    if (indexOf > 0) {
                        clusterAlias = indexName.substring(0, indexOf);
                        indexName = indexName.substring(indexOf + 1);
                    }
                } else if (NODE_FIELD.equals(currentFieldName)) {
                    nodeId  = parser.text();
                } else {
                    parser.skipChildren();
                }
            } else if (token == XContentParser.Token.START_OBJECT) {
                if (REASON_FIELD.equals(currentFieldName)) {
                    exception = ElasticsearchException.fromXContent(parser);
                } else {
                    parser.skipChildren();
                }
            } else {
                parser.skipChildren();
            }
        }
        SearchShardTarget searchShardTarget = null;
        if (nodeId != null) {
            searchShardTarget = new SearchShardTarget(nodeId,
                new ShardId(new Index(indexName, IndexMetadata.INDEX_UUID_NA_VALUE), shardId), clusterAlias, OriginalIndices.NONE);
        }
        return new ShardSearchFailure(exception, searchShardTarget);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `ast_node` trait in crate `rustc`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, ast_node">

    <title>rustc::middle::mem_categorization::ast_node - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

rustc::<wbr>middle::<wbr>mem_categorization

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

Trait rustc::<wbr>middle::<wbr>mem_categorization::<wbr>ast_node<wbr>Unstable
            [-] [+]
        [src]

pub trait ast_node {
    fn id(&self) -> NodeId;
    fn span(&self) -> Span;
}

Required Methods

fn id(&self) -> NodeId

fn span(&self) -> Span

Implementors

impl ast_node for Expr

impl ast_node for Pat

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
EDITOR="$(command -v vim)"
export EDITOR

unset -f prepend_to_path
prepend_to_path() {
  if ! [[ "$PATH" =~ (^|:)${1}($|:) ]]; then
    export PATH="$1:${PATH}"
  fi
}

unset -f append_to_path
append_to_path() {
  if ! [[ "$PATH" =~ (^|:)${1}($|:) ]]; then
    export PATH="${PATH}:$1"
  fi
}

if [[ "$(uname)" == "Darwin" ]]; then
  # shellcheck source=bash/macos.bash
  source "$HOME/.dotfiles/bash/macos.bash"
fi
if [[ "$(uname)" == "Linux" ]]; then
  # shellcheck source=bash/linux.bash
  source "$HOME/.dotfiles/bash/linux.bash"
fi

export CLICOLOR=1

# bash history
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
# https://news.ycombinator.com/item?id=11811272
export HISTCONTROL=ignoreboth
export HISTSIZE=""
export HISTIGNORE="ls:exit:history:[bf]g:jobs"
shopt -s histappend

# The single best bash config option of all time. Also, see .inputrc for more vi
# goodness in readline-enabled apps.
set -o vi

# =========================================================================== #
# Aliases
# =========================================================================== #
alias la='ls -la'

# and vimrc
alias vv='vim "$HOME/.vimrc"'

# Alias g=git and add bash completion
alias g='git'
__git_complete g __git_main

# Same for vim
alias v='vim'
complete -o filenames -F _filedir_xspec v

# json pretty printing
alias jsonpp='python -mjson.tool'

# =========================================================================== #
# useful shell functions
# =========================================================================== #
unset -f freq
unset -f is_not_ascii
unset -f diff_line_count
unset -f rand_string
unset -f rand_alpha_lower
unset -f ytld

# freq prints out a list of my most frequently used commands
freq() {
  cut -d" " -f1 ~/.bash_history |
    grep -Ev "^[[:space:]]*$" |
    sort |
    uniq -c |
    sort -rn |
    head
}

# This function prints out lines in the given files that
# contain non-ascii characters
is_not_ascii() {
  if [[ "$#" == "0" ]]; then
    echo "Usage: $0 file1 file2 ..."
    return 1
  fi
  local argc="$#"
  while (("$#")); do
    if [[ "$argc" -gt "1" ]]; then echo "$1:"; fi
    perl -nwe 'print if /[^[:ascii:]]/' "$1"
    shift
  done
}

diff_line_count() {
  git diff-index --numstat HEAD
}

# Generate a random ASCII alphanumeric string.
#
# This function takes a single optional argument for the string length, which
# defaults to 32.
#
# This function omits confusables like 1, i, I, l, and L.
rand_string() {
  LANG=C LC_ALL=C tr -dc 'A-HJ-KM-NP-Za-km-np-z2-9' </dev/urandom | fold -w "${1:-32}" | head -n 1
}

# Generate a random ASCII string with only lowercase alphabetic characters.
#
# This function takes a single optional argument for the string length, which
# defaults to 16.
#
# This function omits confusables like i, l.
rand_alpha_lower() {
  LANG=C LC_ALL=C tr -dc 'a-km-np-z' </dev/urandom | fold -w "${1:-16}" | head -n 1
}

# Generate a random ASCII string with only numeric characters.
#
# This function takes a single optional argument for the string length, which
# defaults to 6.
rand_pin() {
  LANG=C LC_ALL=C tr -dc '0-9' </dev/urandom | fold -w "${1:-6}" | head -n 1
}

ytdl() {
  local quality="bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4"
  if [[ "$1" == "--best" ]]; then
    quality="bestvideo+bestaudio"
    shift
  fi
  docker run --rm -i -v "$(pwd)":/workdir:rw mikenye/youtube-dl:latest -f "$quality" "$@"
}

# =========================================================================== #
# Tools
# =========================================================================== #

# stuff for moving around directories
# https://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/
CDPATH=".:$HOME:$HOME/dev/artichoke:$HOME/dev/hyperbola:$HOME/dev/repos:$HOME/dev"

if [[ -f "$HOME/.cargo/env" ]]; then
  # shellcheck disable=SC1091
  source "$HOME/.cargo/env"
  export CARGO_NET_GIT_FETCH_WITH_CLI=true
fi


text:
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="oval">
            <solid android:color="#ff99cc00"/>

        </shape>
    </item>

    <item>
        <shape android:shape="oval">
            <solid android:color="#ff0099cc"/>
        </shape>
    </item>
</transition>


text:
% A relaxed/smoothed definition of diameter: the number "d" at which
% a threshold fraction "p" of pairs of nodes are at distance at most
%                       "d". Can be non-integer using interpolation.
%
% Idea: Leskovec et al, "Graphs over Time: Densification Laws,
%                     Shrinking Diameters and Possible Explanations"
%
% Input: adjacency matrix of graph and diameter threshold, p in [0,1]
% Output: relaxed or "effective" diameter
%
% Other routines used: simpleDijkstra.m
% GB: last updated, Oct 8 2012

function diam = smoothDiameter(adj,p)

n=size(adj,1);

dij=[];
for i=1:n; dij=[dij; simpleDijkstra(adj,i)]; end

dij(find(dij==0))=inf;
for i=1:n-1; ddist(i)=length(find(dij<=i)); end
ddist=ddist/(n*(n-1));

lb = max(find(ddist<=p)); % lower bound
ub = min(find(ddist>=p)); % upper bound

if p==1; diam = ub;
elseif ub==lb; diam = lb;
elseif p<ddist(1); diam=0;
else
  % interpolation: yj = y1 + (y2-y1)*(xj-x1)/(x2-x1), where ys are diameters, xs are fractions
  diam = lb + (ub - lb) * (p - ddist(lb)) / (ddist(ub)-ddist(lb));
end


text:
import { Injectable, NgZone } from '@angular/core';
import { ReplaySubject, zip } from 'rxjs';
import { map, switchMapTo } from 'rxjs/operators';
import { AMapService } from '../../shared/amap.service';
import { LoggerService } from '../../shared/logger/logger.service';
import { PluginLoaderService } from '../../shared/plugin-loader.service';
import { WithEditor } from '../../base/interfaces';
declare const AMap: any;

const TAG = 'AmapPolygon';

@Injectable()
export class AmapPolygonService implements WithEditor<AMap.Polygon, any> {
  private polygon: any;
  private polygon$ = new ReplaySubject<any>(1);
  private editor: any;
  private editor$ = new ReplaySubject<any>(1);

  constructor(
    private amaps: AMapService,
    private logger: LoggerService,
    private ngZone: NgZone,
    private plugins: PluginLoaderService,
  ) {}

  /**
   * 获取折线
   */
  get() {
    return this.polygon$.asObservable();
  }

  /**
   * 创建折线 AMap.Polygon
   * @param options 选项
   */
  create(options: AMap.Polygon.Options) {
    return this.amaps.get().pipe(
      map(m => {
        options.map = m;
        this.polygon = this.ngZone.runOutsideAngular(() => new AMap.Polygon(options));
        this.logger.d(TAG, 'new Polygon created.');
        this.polygon$.next(this.polygon);
        this.polygon$.complete();
        return this.polygon;
      }),
    );
  }

  /**
   * 销毁折线
   */
  destroy() {
    this.get().subscribe(m => {
      m.setMap(null);
      this.logger.d(TAG, 'Polygon destroyed.');
      this.polygon = null;
    });
  }

  getEditor() {
    // plugin is loading:
    return this.editor$.asObservable();
  }

  /**
   * 加载编辑插件
   */
  loadEditor() {
    return this.plugins.load('AMap.PolyEditor');
  }

  /**
   * 创建编辑器
   */
  createEditor() {
    return this.loadEditor().pipe(
      switchMapTo(zip(this.amaps.get(), this.get())),
      map(([m, p]) => {
        this.editor = this.ngZone.runOutsideAngular(() => new AMap.PolyEditor(m, p));
        this.logger.d(TAG, 'new PolyEditor created.');
        this.editor$.next(this.editor);
        this.editor$.complete();
        return this.editor;
      }),
    );
  }

  /**
   * 开关编辑器
   * @param v 开关选项
   */
  toggleEditor(v: boolean) {
    if (v && !this.editor) {
      this.createEditor().subscribe(editor => editor.open());
      return;
    }

    if (this.editor) {
      if (v) {
        this.editor.open();
      } else {
        this.editor.close();
      }
    }
  }
}


text:
'use strict';
import { expect } from 'chai';
import { describe, it } from 'mocha';

import flashsale from '../flashsale';
import ActionTypes from '../../actions/ActionTypes';

describe('reducer.flashsale', () => {
  it(`process flashsale info.`, () => {

  });
});