text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_license_name" translatable="false">Apache 2.0</string>
    <string name="app_community_url" translatable="false">https://matrix.to/#/#openlauncher:matrix.org</string>
    <string name="app_bug_report_url" translatable="false">https://github.com/openlauncherteam/openlauncher/issues</string>
    <string name="app_translate_url" translatable="false"><![CDATA[https://lonamiwebs.github.io/stringlate/translate?git=https%3A%2F%2Fgithub.com%2Fopenlauncherteam%2Fopenlauncher.git&mail=gro.xobliam@@rentnasg&name=OpenLauncher&web=https%3A%2F%2Fgithub.com%2Fopenlauncherteam%2Fopenlauncher]]></string>
    <string name="app_web_url" translatable="false">https://github.com/openlauncherteam/openlauncher</string>
    <string name="app_source_code_url" translatable="false">https://github.com/openlauncherteam/openlauncher</string>
    <string name="app_donate_url" translatable="false"><![CDATA[https://gsantner.net/supportme/?project=openlauncher&source=inapp_supdon]]></string>
    <string name="app_contribution_info_url" translatable="false">https://github.com/openlauncherteam/openlauncher/blob/master/README.md#contributions</string>

    <string name="pref_default__date_bar_date_format_custom_1" translatable="false"><![CDATA[EEEE\', \'dd\'.\']]></string>
    <string name="pref_default__date_bar_date_format_custom_2" translatable="false"><![CDATA[MMMM yyyy\', KW \'ww]]></string>
    <string name="pref_default__search_bar_base_uri" translatable="false"><![CDATA[https://duckduckgo.com/?kae=c&k1=-1&kaj=m&kv=l&kp=-1&q={query}]]></string>

    <string name="icon_badge_service_title" translatable="false">Icon Badges</string>

    <!-- Preference Keys -->
    <string name="pref_key__desktop_columns" translatable="false">pref_key__desktop_columns</string>
    <string name="pref_key__desktop_rows" translatable="false">pref_key__desktop_rows</string>
    <string name="pref_key__desktop_indicator_style" translatable="false">pref_key__desktop_indicator_style</string>
    <string name="pref_key__desktop_orientation" translatable="false">pref_key__desktop_orientation</string>
    <string name="pref_key__desktop_wallpaper_scroll" translatable="false">pref_key__desktop_wallpaper_scroll</string>
    <string name="pref_key__minibar" translatable="false">pref_key__minibar</string>
    <string name="pref_key__minibar_enable" translatable="false">pref_key__minibar_enable</string>
    <string name="pref_key__minibar_items" translatable="false">pref_key__minibar_items</string>
    <string name="pref_key__desktop_show_grid" translatable="false">pref_key__desktop_show_grid</string>
    <string name="pref_key__desktop_fullscreen" translatable="false">pref_key__desktop_fullscreen</string>
    <string name="pref_key__desktop_show_position_indicator" translatable="false">pref_key__desktop_show_position_indicator</string>
    <string name="pref_key__desktop_show_label" translatable="false">pref_key__desktop_show_label</string>
    <string name="pref_key__search_bar_enable" translatable="false">pref_key__search_bar_enable</string>
    <string name="pref_key__search_bar_starts_with" translatable="false">pref_key__search_bar_starts_with</string>
    <string name="pref_key__search_bar_base_uri" translatable="false">pref_key__search_bar_base_uri</string>
    <string name="pref_key__search_bar_force_browser" translatable="false">pref_key__search_bar_force_browser</string>
    <string name="pref_key__search_bar_show_hidden_apps" translatable="false">pref_key__search_bar_show_hidden_apps</string>
    <string name="pref_key__date_bar_date_format_type" translatable="false">pref_key__date_bar_date_format_type</string>
    <string name="pref_key__date_bar_date_format_custom_1" translatable="false">pref_key__date_bar_date_format_custom_1</string>
    <string name="pref_key__date_bar_date_format_custom_2" translatable="false">pref_key__date_bar_date_format_custom_2</string>
    <string name="pref_key__date_bar_date_text_color" translatable="false">pref_key__date_bar_date_text_color</string>
    <string name="pref_key__desktop_background_color" translatable="false">pref_key__desktop_background_color</string>
    <string name="pref_key__desktop_inset_color" translatable="false">pref_key__desktop_inset_color</string>
    <string name="pref_key__desktop_folder_color" translatable="false">pref_key__desktop_folder_color</string>
    <string name="pref_key__minibar_background_color" translatable="false">pref_key__minibar_background_color</string>

    <string name="pref_key__dock_enable" translatable="false">pref_key__dock_enable</string>
    <string name="pref_key__dock_columns" translatable="false">pref_key__dock_columns</string>
    <string name="pref_key__dock_rows" translatable="false">pref_key__dock_rows</string>
    <string name="pref_key__dock_show_label" translatable="false">pref_key__dock_show_label</string>
    <string name="pref_key__dock_background_color" translatable="false">pref_key__dock_background_color</string>

    <string name="pref_key__drawer_columns" translatable="false">pref_key__drawer_columns</string>
    <string name="pref_key__drawer_rows" translatable="false">pref_key__drawer_rows</string>
    <string name="pref_key__drawer_style" translatable="false">pref_key__drawer_style</string>
    <string name="pref_key__drawer_show_card_view" translatable="false">pref_key__drawer_show_card_view</string>
    <string name="pref_key__drawer_remember_position" translatable="false">pref_key__drawer_remember_position</string>
    <string name="pref_key__drawer_show_position_indicator" translatable="false">pref_key__drawer_show_position_indicator</string>
    <string name="pref_key__drawer_show_label" translatable="false">pref_key__drawer_show_label</string>
    <string name="pref_key__drawer_label_font_size" translatable="false">pref_key__drawer_label_font_size</string>
    <string name="pref_key__drawer_background_color" translatable="false">pref_key__drawer_background_color</string>
    <string name="pref_key__drawer_card_color" translatable="false">pref_key__drawer_card_color</string>
    <string name="pref_key__drawer_label_color" translatable="false">pref_key__drawer_label_color</string>
    <string name="pref_key__drawer_fast_scroll_color" translatable="false">pref_key__drawer_fast_scroll_color</string>

    <string name="pref_key__gesture_notifications" translatable="false">pref_key__gesture_notifications</string>
    <string name="pref_key__gesture_feedback" translatable="false">pref_key__gesture_feedback</string>
    <string name="pref_key__gesture_quick_swipe" translatable="false">pref_key__gesture_quick_swipe</string>
    <string name="pref_key__gesture_double_tap" translatable="false">pref_key__gesture_double_tap</string>
    <string name="pref_key__gesture_swipe_up" translatable="false">pref_key__gesture_swipe_up</string>
    <string name="pref_key__gesture_swipe_down" translatable="false">pref_key__gesture_swipe_down</string>
    <string name="pref_key__gesture_pinch_in" translatable="false">pref_key__gesture_pinch_in</string>
    <string name="pref_key__gesture_pinch_out" translatable="false">pref_key__gesture_pinch_out</string>

    <string name="pref_key__theme" translatable="false">pref_key__theme</string>
    <string name="pref_key__primary_color" translatable="false">pref_key__primary_color</string>
    <string name="pref_key__icon_size" translatable="false">pref_key__icon_size</string>
    <string name="pref_key__icon_pack" translatable="false">pref_key__icon_pack</string>
    <string name="pref_key__animation_speed" translatable="false">pref_key__animation_speed</string>

    <string name="pref_key__language" translatable="false">pref_key__language</string>
    <string name="pref_key__backup" translatable="false">pref_key__backup</string>
    <string name="pref_key__restore" translatable="false">pref_key__restore</string>
    <string name="pref_key__reset_settings" translatable="false">pref_key__reset_settings</string>
    <string name="pref_key__reset_database" translatable="false">pref_key__reset_database</string>
    <string name="pref_key__restart" translatable="false">pref_key__restart</string>

    <string name="pref_key__cat_desktop" translatable="false">pref_key__cat_desktop</string>
    <string name="pref_key__cat_dock" translatable="false">pref_key__cat_dock</string>
    <string name="pref_key__cat_app_drawer" translatable="false">pref_key__cat_app_drawer</string>
    <string name="pref_key__cat_appearance" translatable="false">pref_key__cat_appearance</string>
    <string name="pref_key__cat_behavior" translatable="false">pref_key__cat_behavior</string>
    <string name="pref_key__cat_hide_apps" translatable="false">pref_key__cat_hide_apps</string>
    <string name="pref_key__cat_advanced" translatable="false">pref_key__cat_advanced</string>
    <string name="pref_key__cat_about" translatable="false">pref_key__cat_about</string>

    <string name="pref_key__show_intro" translatable="false">pref_key__show_intro</string>
    <string name="pref_key__first_start" translatable="false">pref_key__first_start</string>
    <string name="pref_key__hidden_apps" translatable="false">pref_key_hidden_apps</string>
    <string name="pref_key__desktop_lock" translatable="false">pref_key__desktop_lock</string>
    <string name="pref_key__desktop_current_position" translatable="false">pref_key__desktop_current_position</string>
    <string name="pref_key__queue_restart" translatable="false">pref_key__queue_restart</string>
    <string name="pref_key__desktop_search_use_grid" translatable="false">pref_key__desktop_search_use_grid</string>

    <string name="pref_key__more_info__settings" translatable="false">pref_key__more_info__settings</string>
    <string name="pref_key__more_info__source_code" translatable="false">pref_key__more_info__source_code</string>
    <string name="pref_key__more_info__project_license" translatable="false">pref_key__more_info__project_license</string>
    <string name="pref_key__more_info__open_source_licenses" translatable="false">pref_key__more_info__open_source_licenses</string>
    <string name="pref_key__more_info__bug_reports" translatable="false">pref_key__more_info__bug_reports</string>
    <string name="pref_key__more_info__help" translatable="false">pref_key__more_info__help</string>
    <string name="pref_key__more_info__rate_app" translatable="false">pref_key__more_info__rate_app</string>
    <string name="pref_key__more_info__translate" translatable="false">pref_key__more_info__translate</string>
    <string name="pref_key__more_info__join_community" translatable="false">pref_key__more_info__join_community</string>
    <string name="pref_key__more_info__android_contribution_guide" translatable="false">pref_key__more_info__android_contribution_guide</string>
    <string name="pref_key__more_info__app" translatable="false">pref_key__more_info__app</string>
    <string name="pref_key__more_info__donate" translatable="false">pref_key__more_info__donate</string>
    <string name="pref_key__more_info__project_contribution_info" translatable="false">pref_key__more_info__project_contribution_info</string>
    <string name="pref_key__more_info__project_community" translatable="false">pref_key__more_info__project_community</string>
    <string name="pref_key__more_info__project_team" translatable="false">pref_key__more_info__project_team</string>
    <string name="pref_key__more_info__contributors_public_info" translatable="false">pref_key__more_info__contributors_public_info</string>
    <string name="pref_key__more_info__copy_build_information" translatable="false">pref_key__more_info__copy_build_information</string>

</resources>

redpajama_set_name: RedPajamaGithub


text:
#include <libintl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

/* Return a string describing the errno code in ERRNUM.
   The storage is good only until the next call to strerror.
   Writing to the storage causes undefined behavior.  */
libc_freeres_ptr (static char *buf);

char *
strerror (errnum)
     int errnum;
{
  char *ret = __strerror_r (errnum, NULL, 0);
  int saved_errno;

  if (__builtin_expect (ret != NULL, 1))
    return ret;
  saved_errno = errno;
  if (buf == NULL)
    buf = malloc (1024);
  __set_errno (saved_errno);
  if (buf == NULL)
    return _("Unknown error");
  return __strerror_r (errnum, buf, 1024);
}


text:
package org.springside.modules.orm.hibernate;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.springframework.util.Assert;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.orm.PropertyFilter.MatchType;
import org.springside.modules.utils.DBUtils;
import org.springside.modules.utils.UtilDateTime;
import org.springside.modules.utils.reflection.ReflectionUtils;

/**
 * 封装SpringSide扩展功能的Hibernat DAO泛型基类.
 *
 * 扩展功能包括分页查询,按属性过滤条件列表查询.
 * 可在Service层直接使用,也可以扩展泛型DAO子类使用,见两个构造函数的注释.
 *
 * @param <T> DAO操作的对象类型
 * @param <PK> 主键类型
 *
 * @author calvin
 */
public class HibernateDao<T, PK extends Serializable> extends SimpleHibernateDao<T, PK> {
    /**
     * 用于Dao层子类的构造函数.
     * 通过子类的泛型定义取得对象类型Class.
     * eg.
     * public class UserDao extends HibernateDao<User, Long>{
     * }
     */
    public HibernateDao() {
        super();
    }

    /**
     * 用于省略Dao层, Service层直接使用通用HibernateDao的构造函数.
     * 在构造函数中定义对象类型Class.
     * eg.
     * HibernateDao<User, Long> userDao = new HibernateDao<User, Long>(sessionFactory, User.class);
     */
    public HibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
        super(sessionFactory, entityClass);
    }

    //-- 分页查询函数 --//

    /**
     * 分页获取全部对象.
     */
    public Page<T> getAll(final Page<T> page) {
        return findPage(page);
    }

    /**
     * 按HQL分页查询.
     *
     * @param page 分页参数. 注意不支持其中的orderBy参数.
     * @param hql hql语句.
     * @param values 数量可变的查询参数,按顺序绑定.
     *
     * @return 分页查询结果, 附带结果列表及所有查询输入参数.
     */
    @SuppressWarnings("unchecked")
    public Page<T> findPage(final Page<T> page, final String hql, final Object... values) {
        Assert.notNull(page, "page不能为空");

        Query q = createQuery(hql, values);

        if (page.isAutoCount()) {
            long totalCount = countHqlResult(hql, values);
            page.setTotalCount(totalCount);
        }

        setPageParameterToQuery(q, page);

        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * 按HQL分页查询.
     *
     * @param page 分页参数. 注意不支持其中的orderBy参数.
     * @param hql hql语句.
     * @param values 命名参数,按名称绑定.
     *
     * @return 分页查询结果, 附带结果列表及所有查询输入参数.
     */
    @SuppressWarnings("unchecked")
    public Page<T> findPage(final Page<T> page, final String hql, final Map<String, ?> values) {
        Assert.notNull(page, "page不能为空");

        Query q = createQuery(hql, values);

        if (page.isAutoCount()) {
            long totalCount = countHqlResult(hql, values);
            page.setTotalCount(totalCount);
        }

        setPageParameterToQuery(q, page);

        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * 按Criteria分页查询.
     *
     * @param page 分页参数.
     * @param criterions 数量可变的Criterion.
     *
     * @return 分页查询结果.附带结果列表及所有查询输入参数.
     */
    @SuppressWarnings("unchecked")
    public Page<T> findPage(final Page<T> page, final Criterion... criterions) {
        Assert.notNull(page, "page不能为空");

        Criteria c = createCriteria(criterions);

        if (page.isAutoCount()) {
            long totalCount = countCriteriaResult(c);
            page.setTotalCount(totalCount);
        }

        setPageParameterToCriteria(c, page);

        List result = c.list();
        page.setResult(result);
        return page;
    }

    /**
     * 设置分页参数到Query对象,辅助函数.
     */
    protected Query setPageParameterToQuery(final Query q, final Page<T> page) {

        Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

        //hibernate的firstResult的序号从0开始
        q.setFirstResult(page.getFirst() - 1);
        q.setMaxResults(page.getPageSize());
        return q;
    }

    /**
     * 设置分页参数到Criteria对象,辅助函数.
     */
    protected Criteria setPageParameterToCriteria(final Criteria c, final Page<T> page) {

        Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

        //hibernate的firstResult的序号从0开始
        c.setFirstResult(page.getFirst() - 1);
        c.setMaxResults(page.getPageSize());

        if (page.isOrderBySetted()) {
            String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
            String[] orderArray = StringUtils.split(page.getOrder(), ',');

            Assert.isTrue(orderByArray.length == orderArray.length, "分页多重排序参数中,排序字段与排序方向的个数不相等");

            for (int i = 0; i < orderByArray.length; i++) {
                if (Page.ASC.equals(orderArray[i])) {
                    c.addOrder(Order.asc(orderByArray[i]));
                } else {
                    c.addOrder(Order.desc(orderByArray[i]));
                }
            }
        }
        return c;
    }

    /**
     * 执行count查询获得本次Hql查询所能获得的对象总数.
     *
     * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
     */
    protected long countHqlResult(final String hql, final Object... values) {
        String countHql = prepareCountHql(hql);

        try {
            Long count = findUnique(countHql, values);
            return count;
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    /**
     * 执行count查询获得本次Hql查询所能获得的对象总数.
     *
     * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
     */
    protected long countHqlResult(final String hql, final Map<String, ?> values) {
        String countHql = prepareCountHql(hql);

        try {
            Long count = findUnique(countHql, values);
            return count;
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    private String prepareCountHql(String orgHql) {
        String fromHql = orgHql;
        //select子句与order by子句会影响count查询,进行简单的排除.
        fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
        fromHql = StringUtils.substringBefore(fromHql, "order by");

        String countHql = "select count(*) " + fromHql;
        return countHql;
    }

    /**
     * 执行count查询获得本次Criteria查询所能获得的对象总数.
     */
    @SuppressWarnings("unchecked")
    protected long countCriteriaResult(final Criteria c) {
        CriteriaImpl impl = (CriteriaImpl) c;

        // 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
        Projection projection = impl.getProjection();
        ResultTransformer transformer = impl.getResultTransformer();

        List<CriteriaImpl.OrderEntry> orderEntries = null;
        try {
            orderEntries = (List) ReflectionUtils.getFieldValue(impl, "orderEntries");
            ReflectionUtils.setFieldValue(impl, "orderEntries", new ArrayList());
        } catch (Exception e) {
            logger.error("不可能抛出的异常:{}", e.getMessage());
        }

        // 执行Count查询
        Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
        long totalCount = (totalCountObject != null) ? totalCountObject : 0;

        // 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
        c.setProjection(projection);

        if (projection == null) {
            c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
        }
        if (transformer != null) {
            c.setResultTransformer(transformer);
        }
        try {
            ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
        } catch (Exception e) {
            logger.error("不可能抛出的异常:{}", e.getMessage());
        }

        return totalCount;
    }

    //-- 属性过滤条件(PropertyFilter)查询函数 --//

    /**
     * 按属性查找对象列表,支持多种匹配方式.
     *
     * @param matchType 匹配方式,目前支持的取值见PropertyFilter的MatcheType enum.
     */
    public List<T> findBy(final String propertyName, final Object value, final MatchType matchType) {
        Criterion criterion = buildCriterion(propertyName, value, matchType);
        return find(criterion);
    }

    /**
     * 按属性过滤条件列表查找对象列表.
     */
    public List<T> find(List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return find(criterions);
    }

    /**
     * 按属性过滤条件列表分页查找对象.
     */
    public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return findPage(page, criterions);
    }

    /**
     * 按属性条件参数创建Criterion,辅助函数.
     */
    protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) {
        Assert.hasText(propertyName, "propertyName不能为空");
        Criterion criterion = null;
        //根据MatchType构造criterion
        switch (matchType) {
        case EQ:
            criterion = Restrictions.eq(propertyName, propertyValue);
            break;

        case NE:
            criterion = Restrictions.ne(propertyName, propertyValue);
            break;

        case GT:
            criterion = Restrictions.gt(propertyName, propertyValue);
            break;

        case GE:
            criterion = Restrictions.ge(propertyName, propertyValue);
            break;

        case LT:
            criterion = Restrictions.lt(propertyName, propertyValue);
            break;

        case LE:
            criterion = Restrictions.le(propertyName, propertyValue);
            break;

        case ISNULL:
            criterion = Restrictions.isNull(propertyName);
            break;

        case ISNOTNULL:
            criterion = Restrictions.isNotNull(propertyName);
            break;

        case LIKE:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE).ignoreCase();
            break;

        case STARTLIKE:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.START).ignoreCase();
            break;

        case ENDLIKE:
            criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.END).ignoreCase();
            break;

        case IN:
            criterion = Restrictions.in(propertyName, (Collection<?>) propertyValue);
        }

        return criterion;
    }

    /**
     * 按属性条件列表创建Criterion数组,辅助函数.
     */
    protected Criterion[] buildCriterionByPropertyFilter(final List<PropertyFilter> filters) {
        List<Criterion> criterionList = new ArrayList<Criterion>();
        for (PropertyFilter filter : filters) {
            if (!filter.hasMultiProperties()) { //只有一个属性需要比较的情况.
                Criterion criterion = buildCriterion(filter.getPropertyName(), filter.getMatchValue(),
                        filter.getMatchType());
                criterionList.add(criterion);
            } else {//包含多个属性需要比较的情况,进行or处理.
                Disjunction disjunction = Restrictions.disjunction();
                for (String param : filter.getPropertyNames()) {
                    Criterion criterion = buildCriterion(param, filter.getMatchValue(), filter.getMatchType());
                    disjunction.add(criterion);
                }
                criterionList.add(disjunction);
            }
        }
        return criterionList.toArray(new Criterion[criterionList.size()]);
    }

    /**
     * 获取服务器端的指定格式的当前时间字符串,oracle数据库的时间格式为"yyyy.MM.dd HH24:mi:ss"
     */
    public String getNowString(String format) {
        String sdate = UtilDateTime.nowDateString("yyyy-MM-dd HH:mm:ss");
        try {
            String sql = "";
            if (DBUtils.isOracle(getSession().connection())) {
                sql = "select to_char(sysdate,'yyyy-MM-dd HH24:mi:ss') as sys_date from dual";
            } else if (DBUtils.isMSSqlServer(getSession().connection())) {
                sql = "Select CONVERT(varchar(100), GETDATE(), 120)";
            } else {
                sql = ""; // 其他数据库,则采用应用服务器系统时间
            }

            if (StringUtils.isNotEmpty(sql)) {
                Object result = getSession().createSQLQuery(sql).uniqueResult();
                if (result != null) {
                    sdate = result.toString();
                }
            }

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = formatter.parse(sdate);
            sdate = new SimpleDateFormat(format).format(date);

        } catch (Exception se) {
            logger.error(se.toString());
        }

        return sdate;
    }

    /**
     * 获取服务器端的当前时间字符串
     */
    public String getNowString() {
        return getNowString("yyyy.MM.dd HH:mm:ss");
    }
}


text:
<TITLE>Review for Quest for Camelot (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Quest for Camelot (1998)

reviewed by
Matt Williams

QUEST FOR CAMELOT
A film review by Matt Williams

RATING: * 1/2* out of * * * *

Everybody wants a piece of the Disney animated pie.  It's too bad that
most of the newcomers, such as Warner Brothers' Quest for Camelot,
concentrate more on replicating the Disney formula of story elements,
and less on the overall quality of animation.

Quest for Camelot tells the tale of Kayley (Jessalyn Gilsig speaking,
Andrea Corr singing), a young girl who dreams of being a knight of the
round table in Camelot, just like her father, Sir Lionel (Gabriel
Byrne). She gets a chance to prove herself when the exiled knight Sir
Ruber (Gary Oldman) hatches a plan to steal King Arthur's famous sword
Excalibur, along with Kayley's mother, The Lady Juliana (Jane Seymour).

But when Ruber loses the sword in the Forbidden Forest, Kayley sees it
as her chance to recover the lost weapon for the King. (The film never
quite explains why all the knights of the round table are simply sitting
on their thumbs back in Camelot.)  Evading Sir Ruber and his legion of
half-human half-weapon henchmen, Kayley teams up with the blind hermit
Garrett (Cary Elwes speaking, Bryan White singing), his seeing-eye
falcon, and a two headed dragon, Devon and Cornwall (Eric Idle and Don
Rickles).

The animation of Quest for Camelot is very inconsistent.  There are a
few key shots which are done very well (The Forbidden Forest vs. the
Griffin, for example, or the attack of the fire breathing dragons).  The
rest of the film is shortchanged.  It ranges from barely passable to
glaringly awful.  Kids who watch the film may not care, but apparently
neither do the filmmakers.

The story follows a standard formula, and there's not much to surprise
anyone here.  They might be trying to score some points by having a
female hero and a blind sidekick (who only acts blind on the rare
occasions the script calls for it), but that's about the only thing
unusual in the film.  Even the songs seemed tired and routine, having no
individual flavor or style.

There are a few nice touches here and there (the liveliness of the
Forbidden Forest is interesting, and a few passing moments of humor, but
for the most part, Quest for Camelot is dull and lifeless (particularly
when compared to the average Disney cartoon, or even Fox's Anastasia.)

Children may get a kick out of seeing the film once or twice, though it
doesn't bear the hallmarks of being a child's favorite must-watch film.
Adults, on the other hand, will simply have to suffer through.

Copyright 1998 Matt Williams

- Matt Williams (matt@cinematter.com)
Reviewer for Cinematter: http://www.cinematter.com
Home of over 500 reviews, and information on over 600 upcoming releases

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
module SmallServerAdmin.Localization {

  /** Default localization resources. */
  export class Default implements ILocalization {

    //#region ..Common..

    /**
     * Loading...
     */
    public Loading: string = 'Loading...';

    /** Saving... */
    public Saving: string = 'Saving...';

    /** Deleting... */
    public Deleting: string = 'Deleting...';

    /** Preparing... */
    public Preparing: string = 'Preparing...';

    /** Preparing form. Please wait... */
    public PreparingFormWait: string = 'Preparing form. Please wait...';

    /** Success */
    public Success: string = 'Success';

    /**
     * Error
     */
    public Error: string = 'Error';

    /** Ok */
    public Ok: string = 'Ok';

    /** Total */
    public Total: string = 'Total';

    /** Kb */
    public Kb: string = 'Kb';

    /** Mb */
    public Mb: string = 'Mb';

    /** Gb */
    public Gb: string = 'Gb';

    /** In Use */
    public InUse: string = 'In Use';

    /** New Group */
    public NewGroup: string = 'New Group';

    /** New User */
    public NewUser: string = 'New User';

    //#endregion
    //#region ..MasterController..

    /**
     * Config not found.
Please check $config[\'client\'] of the /ssa.config.php.
     */
    public ConfigNotFound: string = 'Config not found.
Please check $config[\'client\'] of the /ssa.config.php.';

    /**
     * Servers controller not found.
     */
    public ServersControllerNotFound: string = 'Servers controller not found.';

    //#endregion
    //#region ..FileListController..

    /**
     * Loading the file contents...
     */
    public LoadingFileContents: string = 'Loading the file contents...';

    /**
     * Getting the file info...
     */
    public GettingFileInfo: string = 'Getting the file info...';

    //#endregion
    //#region ..PanelServersController..

    /** Unable to connect to the server.
Check the connection settings and try again. */
    public UnableToConnectTheServer: string = 'Unable to connect to the server.
Check the connection settings and try again.';

    /** Connection error */
    public ConnectionError: string = 'Connection error';

    //#endregion
    //#region ..ServiceListController..

    /** No services to reload. */
    public NoServicesToReload: string = 'No services to reload.';

    /**
     * Cannot reload service {0}.
     */
    public CannotReloadService: string = 'Cannot reload service {0}.';

    /**
     * Server is required.
     */
    public ServerIsRequired: string = 'Server is required.';

    //#endregion
    //#region ..ServiceListController..

    /** Incorrect site name! */
    public IncorrectSiteName: string = 'Incorrect site name!';

    /**
     * Is removed the site {0}. Please wait...
     */
    public IsRemovedSiteWait: string = 'Is removed the site {0}. Please wait...';

    /** Loading list of sites... */
    public LoadingListOfSites: string = 'Loading list of sites...';

    //#endregion
    //#region ..SVN..

    /** Obtaining the group data from the server. Please wait... */
    public ObtainingTheGroupWait: string = 'Obtaining the group data from the server. Please wait...';

    /** Saving the group. Please wait... */
    public SavingTheGroupWait: string = 'Saving the group. Please wait...';

    /** Saved successfully!
Loading list of groups. Please wait... */
    public SavedSuccessfullyLoadingListOfGroups: string = 'Saved successfully!
Loading list of groups. Please wait...';

    /** Incorrect group name! */
    public IncorrectGroupName: string = 'Incorrect group name!';

    /**
     * Is removed the group {0}. Please wait...
     */
    public IsRemovedTheGroupWait: string = 'Is removed the group {0}. Please wait...';

    /** Loading list of groups... */
    public LoadingListOfGroups: string = 'Loading list of groups...';

    /** Obtaining the repository info from the server. Please wait... */
    public ObtainingTheRepositoryWait: string = 'Obtaining the repository info from the server. Please wait...';

    /** New Repository */
    public NewRepository: string = 'New Repository';

    /** Saving the respository. Please wait... */
    public SavingTheRepositoryWait: string = 'Saving the respository. Please wait...';

    /** Saved successfully!
Loading list of repositories. Please wait... */
    public SavedSuccessfullyLoadingListOfRepositories: string = 'Saved successfully!
Loading list of repositories. Please wait...';

    /** Incorrect repository name! */
    public IncorrectRepositoryName: string = 'Incorrect repository name!';

    /** Is removed the repository {0}. Please wait... */
    public IsRemovedTheRepositoryWait: string = 'Is removed the repository {0}. Please wait...';

    /** Loading list of repositories... */
    public LoadingListOfRepositories: string = 'Loading list of repositories...';

    //#endregion
    //#region ..Users..

    /** Obtaining the user data from the server. Please wait... */
    public ObtainingTheUserWait: string = 'Obtaining the user data from the server. Please wait...';

    /** Saving the user. Please wait... */
    public SavingTheUserWait: string = 'Saving the user. Please wait...';

    /** Saved successfully!
Loading list of users. Please wait... */
    public SavedSuccessfullyLoadingListOfUsers: string = 'Saved successfully!
Loading list of users. Please wait...';

    /** Is removed the user {0}. Please wait... */
    public IsRemovedUserWait: string = 'Is removed the user {0}. Please wait...';

    /** Loading list of users... */
    public LoadingListOfUsers: string = 'Loading list of users...';

    /** The account has been successfully updated! */
    public TheAccountHasBeenUpdated: string = 'The account has been successfully updated!';

    /** The user data has been successfully updated! */
    public TheUserHasBeenUpdated: string = 'The user data has been successfully updated!';

    /** The user groups list has been successfully updated! */
    public TheUserGroupsHasBeenUpdated: string = 'The user groups list has been successfully updated!';

    /** The user has been successfully created! */
    public TheUserHasBeenCreated: string = 'The user has been successfully created!';

    /** Incorrect user name! */
    public IncorrectUserName: string = 'Incorrect user name!';

    //#endregion

  }

}


text:
from django.db import migrations
from django.db.models.signals import post_migrate
from django.apps import apps as registry

def update_groups_with_manage_products_with_new_permission(apps, schema_editor):
    def on_migrations_complete(sender=None, **kwargs):
        Group = apps.get_model("auth", "Group")
        Permission = apps.get_model("auth", "Permission")
        ContentType = apps.get_model("contenttypes", "ContentType")

        ct, _ = ContentType.objects.get_or_create(
            app_label="product", model="producttype"
        )
        product_type_and_attribute_permission, _ = Permission.objects.get_or_create(
            codename="manage_product_types_and_attributes",
            content_type=ct,
            name="Manage product types and attributes.",
        )

        groups = Group.objects.filter(
            permissions__content_type__app_label="product",
            permissions__codename="manage_products",
        )
        for group in groups:
            group.permissions.add(product_type_and_attribute_permission)

    sender = registry.get_app_config("product")
    post_migrate.connect(on_migrations_complete, weak=False, sender=sender)

class Migration(migrations.Migration):

    dependencies = [
        ("product", "0128_update_publication_date"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="producttype",
            options={
                "ordering": ("slug",),
                "permissions": (
                    (
                        "manage_product_types_and_attributes",
                        "Manage product types and attributes.",
                    ),
                ),
            },
        ),
        migrations.RunPython(
            update_groups_with_manage_products_with_new_permission,
            migrations.RunPython.noop,
        ),
    ]


text:
class AddStatusToVms < ActiveRecord::Migration
  def change
    add_column :vms, :status, :integer
  end
end


text:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-44625620-1']);
_gaq.push(['_trackPageview']);

(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = 'https://ssl.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

// Track button clicks (sent to Google Analytics)
function trackButtonClick(e) {
	_gaq.push(['_trackEvent', e.target.id, 'clicked']);
};

// Track the events associated with saving defaults
function trackSaveDefaults(colorScheme,
						   font,
						   fontSize,
						   WPM,
						   wordsPerSlide,
						   autoStartReader,
						   autoStartReaderSeconds,
						   autoCloseReader,
						   textOrientationIsRightToLeft,
						   textOrientationAutoDetect) {
	var saved = 'saved';
	// Track the default settings which are saved
	_gaq.push(['_trackEvent', 'Font', saved, font, fontSize, true]);
	_gaq.push(['_trackEvent', 'Colour Scheme', saved, colorScheme, true]);
	_gaq.push(['_trackEvent', 'Words per minute', saved, 'words per minute', WPM, true]);
	_gaq.push(['_trackEvent', 'Words per slide', saved, 'words per slide', wordsPerSlide, true]);
	_gaq.push(['_trackEvent', 'Auto start reader', saved, autoStartReader, autoStartReaderSeconds, true]);
	_gaq.push(['_trackEvent', 'Auto close reader', saved, 'auto close reader', autoCloseReader, true]);
	_gaq.push(['_trackEvent', 'Word right-to-left', saved, 'word right-to-left', textOrientationIsRightToLeft, true]);
	_gaq.push(['_trackEvent', 'Word right-to-left', saved, 'auto-detect', textOrientationAutoDetect, true]);
}

// Track the events associated with saving advanced defaults
function trackSaveAdvancedDefaults(algorithm,
								   pauseAfterComma,
								   pauseAfterCommaDelay,
								   pauseAfterPeriod,
								   pauseAfterPeriodDelay,
								   pauseAfterParagraph,
								   pauseAfterParagraphDelay,
								   highlightoptimalletter,
								   highlightoptimallettercolour,
								   textposition) {
   	var saved = 'saved';
	// Track the default settings which are saved
	_gaq.push(['_trackEvent', 'Algorithm', saved, algorithm, true]);
	_gaq.push(['_trackEvent', 'Pause after comma', saved, pauseAfterComma, pauseAfterCommaDelay, true]);
	_gaq.push(['_trackEvent', 'Pause after period', saved, pauseAfterPeriod, pauseAfterPeriodDelay, true]);
	_gaq.push(['_trackEvent', 'Pause after paragraph', saved, pauseAfterParagraph, pauseAfterParagraphDelay, true]);
	_gaq.push(['_trackEvent', 'Highlight optimal letter', saved, 'highlight optimal letter', highlightoptimalletter, true]);
	_gaq.push(['_trackEvent', 'Highlight optimal letter colour', saved, 'highlight optimal letter colour', highlightoptimallettercolour, true]);
	_gaq.push(['_trackEvent', 'Text position', saved, 'text position', textposition, true]);
}

// Track the events associated with saving more advanced defaults
function trackSaveMoreAdvancedDefaults(madvStaticFocalUnicodeCharacter,
									   madvEnableSpaceInsertion,
									   madvRemoveLastSlideNullOrEmpty,
									   madvEnableHyphenatedWordSplit,
									   madvConsolidateHyphenatedWord,
									   madvEnableLongWordHyphenation,
									   madvLongWordTriggerCharacterCount,
									   madvLongWordCharacterPerSlidePostSplit,
									   madvLongWordCharacterTriggerDoNotJoin,
									   madvEnableAcronymDetection,
									   madvEnableNumberDecimalDetection,
									   madvDeleteEmptySlides,
									   madvOptimisedPositionLeftMarginPercent) {
   	var saved = 'saved';
	// Track the default settings which are saved
	_gaq.push(['_trackEvent', 'Satic focal character', saved, 'static focal character', madvStaticFocalUnicodeCharacter, true]);
	_gaq.push(['_trackEvent', 'Enable space insertion', saved, 'enable space insertion', madvEnableSpaceInsertion, true]);
	_gaq.push(['_trackEvent', 'Remove last slide null or empty', saved, 'remove last slide null or empty', madvRemoveLastSlideNullOrEmpty, true]);
	_gaq.push(['_trackEvent', 'Enable hyphenated word split', saved, 'enable hyphenated word split', madvEnableHyphenatedWordSplit, true]);
	_gaq.push(['_trackEvent', 'Consolidate hyphenated word', saved, 'consolidated hyphenated word', madvConsolidateHyphenatedWord, true]);
	_gaq.push(['_trackEvent', 'Enable long word hyphenation', saved, 'enable long word hyphenation', madvEnableLongWordHyphenation, true]);
	_gaq.push(['_trackEvent', 'Long word trigger character count', saved, 'long word trigger character count', madvLongWordTriggerCharacterCount, true]);
	_gaq.push(['_trackEvent', 'Long word character per slide post', saved, 'long word character per slide post', madvLongWordCharacterPerSlidePostSplit, true]);
	_gaq.push(['_trackEvent', 'Long word trigger do not join', saved, 'long word trigger do not join', madvLongWordCharacterTriggerDoNotJoin, true]);
	_gaq.push(['_trackEvent', 'Enable acronym detection', saved, 'Enable acronym detection', madvEnableAcronymDetection, true]);
	_gaq.push(['_trackEvent', 'Enable number decimal detection', saved, 'enable number decimal detection', madvEnableNumberDecimalDetection, true]);
	_gaq.push(['_trackEvent', 'Delete empty slides', saved, 'delete empty slides', madvDeleteEmptySlides, true]);
	_gaq.push(['_trackEvent', 'Optimised position left margin %', saved, 'optimised position left margin %', madvOptimisedPositionLeftMarginPercent, true]);
}

// Track the selected word count
function trackSelectedWordCount(wordcount,
								language,
								displayReaderRightToLeft) {
	_gaq.push(['_trackEvent', 'Selected word count', 'reader opened', 'word count', wordcount, true]);
	_gaq.push(['_trackEvent', 'Selected text', 'language', 'fullname', language.fullname, true]);
	_gaq.push(['_trackEvent', 'Selected text', 'language', 'shortname', language.shortname, true]);
	_gaq.push(['_trackEvent', 'Selected text', 'direction', 'right to left', displayReaderRightToLeft, true]);
}


text:
<?php
/**
 * @package WPSEO\Premium
 */

/**
 * Registers the endpoint for the redirects to WordPress.
 */
class WPSEO_Premium_Redirect_EndPoint implements WPSEO_WordPress_Integration {

	const REST_NAMESPACE = 'yoast/v1';
	const ENDPOINT_QUERY = 'redirects';

	const CAPABILITY_RETRIEVE = 'edit_posts';

	/**
	 * @var WPSEO_Premium_Redirect_Service
	 */
	protected $service;

	/**
	 * Sets the service to handle the request.
	 *
	 * @param WPSEO_Premium_Redirect_Service $service The service to handle the requests to the endpoint.
	 */
	public function __construct( WPSEO_Premium_Redirect_Service $service ) {
		$this->service = $service;
	}

	/**
	 * Registers all hooks to WordPress.
	 */
	public function register_hooks() {
		add_action( 'rest_api_init', array( $this, 'register' ) );
	}

	/**
	 * Register the REST endpoint to WordPress.
	 */
	public function register() {
		register_rest_route( self::REST_NAMESPACE, self::ENDPOINT_QUERY, array(
			'methods'             => 'POST',
			'args'                => array(
				'origin' => array(
					'required'    => true,
					'type'        => 'string',
					'description' => 'The origin to redirect',
				),
				'target' => array(
					'required'    => false,
					'type'        => 'string',
					'description' => 'The redirect target',
				),
				'type' => array(
					'required'    => true,
					'type'        => 'integer',
					'description' => 'The redirect type',
				),
			),
			'callback'            => array(
				$this->service,
				'save',
			),
			'permission_callback' => array(
				$this,
				'can_retrieve_data',
			),
		) );
	}

	/**
	 * Determines if the current user is allowed to use this endpoint.
	 *
	 * @return bool True user is allowed to use this endpoint.
	 */
	public function can_retrieve_data() {
		return current_user_can( self::CAPABILITY_RETRIEVE );
	}
}


text:
title: "Social Realtionship"
excerpt: "An Andriod app predicting user's best friends and modeling social relationships"
header:
  overlay_color: "#333"
  teaser: /socialRelationship/welcome.png

gallery:
  - url:  /socialRelationship/login.png
    image_path: /socialRelationship/login.png
    alt: "placeholder image 1"
  - url: /socialRelationship/main.png
    image_path: /socialRelationship/main.png
    alt: "placeholder image 2"
  - url: /socialRelationship/playStore.png
    image_path: /socialRelationship/playStore.png
    alt: "placeholder image 3"

tags:
  - JAVA
  - Android
---

## Project Description

It's an interesting Android app that can model and build user's social relationships presented by ranking user's possible best friends
  from strongest to weakest intimacy by extracting and analyzing all user's posted and tagged photos on facebook.

Here is [Git Repo](https://github.com/jiangxiaoyong/SocialRelationships)

{% include gallery caption="Screenshots of welcome view, relationships ranking view and app in play store." %}

## Features

 * Extracting and modeling social relationships for both user and user's friends based on tagged Facebook photos to predicting who is the best friend
 * Login by Facebook login button, a list-view showing ranked best friends
 * Letting user manually select backend algorithms and sharing of app link in Facebook post


text:
"""signalfd: Recive signals over a file descriptor"""

from .utils import Eventlike as _Eventlike
from .utils import CLOEXEC_DEFAULT as _CLOEXEC_DEFAULT
from ._signalfd import SFD_CLOEXEC, SFD_NONBLOCK, NEW_SIGNALFD
from ._signalfd import SIG_BLOCK, SIG_UNBLOCK, SIG_SETMASK
from ._signalfd import SIGINFO_LENGTH as _SIGINFO_LENGTH
from ._signalfd import signalfd, pthread_sigmask
from ._signalfd import signum_to_signame
from ._signalfd import ffi as _ffi, C as _C
import os as _os

class Signalfd(_Eventlike):
    def __init__(self, sigmask=set(), flags=0, closefd=_CLOEXEC_DEFAULT):
        """Create a new Signalfd object

        Arguments
        ----------
        :param int sigmask: Set of signals to respond on
        :param int flags: Flags to open the signalfd with

        Flags
        ------
        SFD_CLOEXEC: Close the signalfd when executing a new program
        SFD_NONBLOCK: Open the socket in non-blocking mode
        """
        super(self.__class__, self).__init__()

        self._flags = flags

        self._sigmask = sigmask = _ffi.new('sigset_t[1]')

        self._fd = signalfd(sigmask, NEW_SIGNALFD, flags)

    def __contains__(self, signal):
        val = _C.sigismember(self._sigmask, signal)

        if val < 0:
            raise ValueError('Signal is not a valid signal number')

        return bool(val)

    def _update(self):
        return signalfd(self._sigmask, self.fileno(), self._flags)

    def enable(self, signals):
        """Mark signals as active on signalfd

        :param int signals: A single signal to listen for
        :param list signals: A list of signals to listen for

        enable will mark all signals passed in on signalfd and takes
        ethier a signal integer representing the signal to add or an
        iterable if signals to (bulk) add

        The latter for is used for more efficent updates of signal masks
        """
        # if we have multipel signals then all is good
        try:
            signals = iter(signals)
        except TypeError:
        # if not make the value iterable
            signals = [signals]

        for signal in signals:
            _C.sigaddset(self._sigmask, signal)

        self._update()

    def enable_all(self):
        _C.sigfillset(self._sigmask)
        self._update()

    def disable(self, signal):
        _C.sigdelset(self._sigmask, signal)
        self._update()

    def disable_all(self):
        _C.sigemptyset(self._sigmask)
        self._update()

    def _read_events(self):
        buf = _os.read(self.fileno(), _SIGINFO_LENGTH)
        siginfo = _ffi.new('struct signalfd_siginfo *')

        _ffi.buffer(siginfo)[0:_SIGINFO_LENGTH] = buf

        return [Signal(siginfo)]

class Signal(object):
    """Proxy object for data returned by signalfd when a signal is recived

    Maps to most fields in a signalfd_siginfo

    Ommited mappings are ones that deal with traps and SIGQUEUE
    """
    def __init__(self, siginfo):
        self._siginfo = siginfo

    @property
    def signal(self):
        """The number of the signal being sent"""
        return self._siginfo.ssi_signo

    @property
    def signal_code(self):
        """The signal code"""
        return self._siginfo.ssi_code

    @property
    def pid(self):
        """PID of the sender of the signal"""
        return self._siginfo.ssi_pid

    @property
    def uid(self):
        """UID of the sender of the signal"""
        return self._siginfo.ssi_uid

    @property
    def sigio_fd(self):
        """FD that triggered the SIGIO signal"""
        return self._siginfo.ssi_fd

    @property
    def timer_id(self):
        """Kernel timer ID (POSIX Timers)"""
        return self._siginfo.ssi_tid

    @property
    def sigio_band(self):
        """SIGIO Band event"""
        return self._siginfo.ssi_band

    @property
    def overrun(self):
        """POSIX timer overrun count"""
        return self._siginfo.ssi_overrun

    @property
    def trapno(self):
        """Trap number that caused the signal"""
        return self._siginfo.trapno

    @property
    def child_status(self):
        """The return code of the exiting child process"""
        return self._siginfo.ssi_status

    @property
    def child_user_time(self):
        """The ammount of user time used by the exiting child process"""
        return self._siginfo.ssi_utime

    @property
    def child_system_time(self):
        """The ammount of system time used by the exiting child process"""
        return self._siginfo.ssi_stime

    def __repr__(self):
        # convert to Alpha name, else just return the int
        signame = signum_to_signame.get(self.signal, self.signal)
        return "<{} signal={} uid={} pid={}>".format(self.__class__.__name__, signame, self.uid, self.pid)


text:
package me.himanshusoni.quantumflux.model.annotation.Column;

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

/**
 * Indicates that a field is a primary key field
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface PrimaryKey {

    /**If this field should be auto incremented. Default is true.  Requires that the field type is long*/
    boolean autoIncrement() default true;
}


text:
. $(dirname $0)/testsuite-common.sh

setup_test

# How large should the file with random data be
randomsize=5000 # kiB

# Try to trigger scanner problem discovered 2015-10-28
echo "badfile, should be ignored" > "${srcdir}/$(printf "\002")"

echo test1 > "${srcdir}/test1"
echo 'test(2)' > "${srcdir}/test (2).txt"
echo test2 > "${srcdir}/test2"
mkdir "${srcdir}/d"
echo test3 > "${srcdir}/d/test3"

dd bs=1k count=${randomsize} \
    if=/dev/urandom \
    of="${srcdir}/${randomsize}krandom" > /dev/null 2>&1

md5start=$(cd ${srcdir}; md5sum ${randomsize}krandom)

# First a run to copy toplevel files/directories
run_daemon -1

# Next a run to copy next level files
run_daemon -1

for good in test1 test2 d/test3 ; do
	if [ ! -e "${dstdir}/${good}" ] ; then
		fail_test "missing: ${dstdir}/${good}"
	elif ! cmp -s "${srcdir}/${good}" "${dstdir}/${good}" ; then
		fail_test "incorrect: ${dstdir}/${good}"
	fi
done

for bad in "test (2).txt" ; do
	if [ -e "${bad}" ] ; then
		fail_test "should not exist: ${bad}"
	fi
done

md5end=$(cd ${dstdir}; md5sum ${randomsize}krandom)
if [ "$md5start" != "$md5end" ]; then
    fail_test "${randomsize}krandom file changed from source to destination"
fi

# Make sure failed copy of "test (2).txt" and others are reported as
# errors in destination directory.
if [ ! -e "${dstdir}/tsdfx-error.log" ] ; then
    fail_test "missing ${dstdir}/tsdfx-error.log"
fi

cleanup_test


text:
import numpy as np
import pandas as pd
from pyrates.utility.visualization import plot_connectivity
from matplotlib.pyplot import show
import pickle, os

path = "/home/rgast/ownCloud/data/qif_rc_scores/lorenz_vs_stuartlandau"

# STEP 1: Load pre-generated RNN parameters
###########################################

config = pickle.load(open(f"{path}/qif_micro_config.pkl", 'rb'))

# connectivity matrix
C = config['C']

# input
inp = config['inp']

# input weights
W_in = config['W_in']

# simulation config
T = config['T']
dt = config['dt']
dts = config['dts']
cutoff = config['cutoff']

# target values
targets = config['targets']

# STEP 2: Go through results files and store scores
###################################################

etas, alphas, scores = [], [], []
for f in [f for f in os.listdir(path) if '.npy' in f]:
    idx = int(f.split(".")[0].split("_")[-1])
    alphas.append(config['alphas'][idx])
    etas.append(config['etas'][idx])
    scores.append(np.load(f"{path}/{f}"))

# STEP 3: Visualization
#######################

# visualization
etas_unique = np.sort(np.unique(etas))
alphas_unique = np.sort(np.unique(alphas))
scores_2d = np.zeros((len(alphas_unique), len(etas_unique)))
for eta, alpha, score in zip(etas, alphas, scores):
    idx_c = np.argwhere(etas_unique == eta)
    idx_r = np.argwhere(alphas_unique == alpha)
    if score >= 0.0:
        scores_2d[idx_r, idx_c] = score

plot_connectivity(scores_2d, xticklabels=np.round(etas_unique, decimals=2),
                  yticklabels=np.round(alphas_unique, decimals=2))
show()


text:
package brooklyn.location.basic;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import brooklyn.config.ConfigKey;
import brooklyn.entity.basic.ConfigKeys;
import brooklyn.location.Location;
import brooklyn.location.LocationSpec;
import brooklyn.location.MachineLocation;
import brooklyn.location.MachineProvisioningLocation;
import brooklyn.location.NoMachinesAvailableException;
import brooklyn.location.cloud.AbstractAvailabilityZoneExtension;
import brooklyn.location.cloud.AvailabilityZoneExtension;
import brooklyn.management.ManagementContext;
import brooklyn.util.collections.MutableList;
import brooklyn.util.collections.MutableMap;
import brooklyn.util.exceptions.CompoundRuntimeException;
import brooklyn.util.exceptions.Exceptions;
import brooklyn.util.flags.SetFromFlag;
import brooklyn.util.text.Strings;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.reflect.TypeToken;

/** A location which consists of multiple locations stitched together to form availability zones.
 * The first location will be used by default, but if an {@link AvailabilityZoneExtension}-aware entity
 * is used, it may stripe across each of the locations.  See notes at {@link AvailabilityZoneExtension}. */
public class MultiLocation<T extends MachineLocation> extends AbstractLocation implements MachineProvisioningLocation<T> {

    private static final long serialVersionUID = 7993091317970457862L;

    @SuppressWarnings("serial")
    @SetFromFlag("subLocations")
    public static final ConfigKey<List<MachineProvisioningLocation<?>>> SUB_LOCATIONS = ConfigKeys.newConfigKey(
            new TypeToken<List<MachineProvisioningLocation<?>>>() {},
            "subLocations",
            "The sub-machines that this location can delegate to");

    @Override
    public void init() {
        super.init();
        List<MachineProvisioningLocation<?>> subLocs = getSubLocations();
        checkState(subLocs.size() >= 1, "sub-locations must not be empty");
        AvailabilityZoneExtension azExtension = new AvailabilityZoneExtensionImpl(getManagementContext(), subLocs);
        addExtension(AvailabilityZoneExtension.class, azExtension);
    }

    public T obtain() throws NoMachinesAvailableException {
        return obtain(MutableMap.of());
    }

    /** finds (creates) and returns a {@link MachineLocation};
     * this always tries the first sub-location, moving on the second and subsequent if the first throws {@link NoMachinesAvailableException}.
     * (if you want striping across locations, see notes in {@link AvailabilityZoneExtension}.) */
    @SuppressWarnings("unchecked")
    @Override
    public T obtain(Map<?, ?> flags) throws NoMachinesAvailableException {
        List<MachineProvisioningLocation<?>> sublocsList = getSubLocations();
        Iterator<MachineProvisioningLocation<?>> sublocs = sublocsList.iterator();
        List<NoMachinesAvailableException> errors = MutableList.of();
        while (sublocs.hasNext()) {
            try {
                return (T) sublocs.next().obtain(flags);
            } catch (NoMachinesAvailableException e) {
                errors.add(e);
            }
        }
        Exception wrapped;
        String msg;
        if (errors.size()>1) {
            wrapped = new CompoundRuntimeException(errors.size()+" sublocation exceptions, including: "+
                Exceptions.collapseText(errors.get(0)), errors);
            msg = Exceptions.collapseText(wrapped);
        } else if (errors.size()==1) {
            wrapped = errors.get(0);
            msg = wrapped.getMessage();
            if (Strings.isBlank(msg)) msg = wrapped.toString();
        } else {
            msg = "no sub-locations set for this multi-location";
            wrapped = null;
        }
        throw new NoMachinesAvailableException("No machines available in any of the "+sublocsList.size()+" location"+Strings.s(sublocsList.size())+
            " configured here: "+msg, wrapped);
    }

    public List<MachineProvisioningLocation<?>> getSubLocations() {
        return getRequiredConfig(SUB_LOCATIONS);
    }

    @SuppressWarnings("unchecked")
    @Override
    public MachineProvisioningLocation<T> newSubLocation(Map<?, ?> newFlags) {
        // TODO shouldn't have to copy config bag as it should be inherited (but currently it is not used inherited everywhere; just most places)
        return getManagementContext().getLocationManager().createLocation(LocationSpec.create(getClass())
                .parent(this)
                .configure(getLocalConfigBag().getAllConfig())  // FIXME Should this just be inherited?
                .configure(newFlags));
    }

    @SuppressWarnings("unchecked")
    @Override
    public void release(T machine) {
        ((MachineProvisioningLocation<T>)machine.getParent()).release(machine);
    }

    @Override
    public Map<String, Object> getProvisioningFlags(Collection<String> tags) {
        return Maps.<String,Object>newLinkedHashMap();
    }

    @SuppressWarnings("unchecked")
    protected MachineProvisioningLocation<T> firstSubLoc() {
        return (MachineProvisioningLocation<T>) Iterables.get(getSubLocations(), 0);
    }

    protected <K> K getRequiredConfig(ConfigKey<K> key) {
        return checkNotNull(getConfig(key), key.getName());
    }

    public static class AvailabilityZoneExtensionImpl extends AbstractAvailabilityZoneExtension implements AvailabilityZoneExtension {

        private final List<MachineProvisioningLocation<?>> subLocations;

        public AvailabilityZoneExtensionImpl(ManagementContext managementContext, List<MachineProvisioningLocation<?>> subLocations) {
            super(managementContext);
            this.subLocations = ImmutableList.copyOf(subLocations);
        }

        @Override
        protected List<Location> doGetAllSubLocations() {
            return ImmutableList.<Location>copyOf(subLocations);
        }

        @Override
        protected boolean isNameMatch(Location loc, Predicate<? super String> namePredicate) {
            return namePredicate.apply(loc.getDisplayName());
        }
    }
}


text:
Game type: <input ng-model="model.game.game_type" type="radio" value="mcr">MCR</input>
<input ng-model="model.game.game_type" type="radio" value="riichi">Riichi</input>

Number of winds: <input ng-model="model.game.number_of_winds" placeholder="1-4"></input>

Date: <input ng-model="model.date" placeholder="format: YYYY-MM-DD"></input>

Finished time: <input ng-model="model.finished_time" placeholder="format: HH:MM"></input>

    Player <input ng-model="gp.player_name" typeahead="player.name for player in model.players | filter:$viewValue | limitTo:8" typeahead-on-select="gp.player = $item.id"></input> Score <input ng-model="gp.score"></input>

<button class="btn btn-primary" ng-click="save()">Create</button>


text:
package com.github.tanacasino.sample

class WordCount {

 def countFruitsFromLines(lines: List[String]): Map[String, Int] = {
   lines
     .flatMap(_.split(" "))
     .groupBy(identity)
     .map{
       case (k, v) => (k, v.size)
     }
 }

  def countFruitsFromLines2(lines: List[String]): Map[String, Int] = {
    lines
      .flatMap(_.split(" "))
      .foldLeft(Map.empty[String, Int]){ case (result, keyword) =>
        result + (keyword -> (result.getOrElse(keyword, 0) + 1))
      }
  }

  def countFruitsFromLines3(lines: List[String]): Map[String, Int] = {
    val words = for {
      line <- lines
      word <- line.split(" ")
    } yield {
      word
    }
    words.groupBy(x => x)
    words.groupBy(_.toString)
    words.groupBy(x => identity(x))
    words.groupBy(identity(_))
    words.groupBy(identity).map(e => e._1 -> e._2.size)
    words.groupBy(identity).map{ case (word, list) => word -> list.size}
  }

}


text:
declare namespace java {
  namespace util {

    class PropertyResourceBundle extends java.util.ResourceBundle {
      public constructor(arg0: java.io.InputStream)
      public constructor(arg0: java.io.Reader)
      public handleGetObject(arg0: java.lang.String | string): java.lang.Object
      public getKeys(): java.util.Enumeration<java.lang.String>
      protected handleKeySet(): java.util.Set<java.lang.String>
    }

  }
}


text:
.. Copyright 2011, 2012 Bastien Léonard. All rights reserved.

.. Redistribution and use in source (reStructuredText) and 'compiled'
   forms (HTML, PDF, PostScript, RTF and so forth) with or without
   modification, are permitted provided that the following conditions are
   met:

.. 1. Redistributions of source code (reStructuredText) must retain
   the above copyright notice, this list of conditions and the
   following disclaimer as the first lines of this file unmodified.

.. 2. Redistributions in compiled form (converted to HTML, PDF,
   PostScript, RTF and other formats) must reproduce the above
   copyright notice, this list of conditions and the following
   disclaimer in the documentation and/or other materials provided
   with the distribution.

.. THIS DOCUMENTATION IS PROVIDED BY BASTIEN LÉONARD ``AS IS'' AND ANY
   EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BASTIEN LÉONARD BE LIABLE
   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
   BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
   OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENTATION,
   EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

System
======

.. module:: sfml

.. attribute:: default_encoding

   Currently, this encoding is used when the user passes a Unicode
   object to method that will call a SFML method which only supports
   ``std::string`` argument. The user-supplised Unicode object will be
   encoded with this encoding and the resulting bytes will be passed
   to SFML. This is mostly for Python 3 users, so they don't have to
   use byte strings all the time. Here is the list of valid encodings:
   http://docs.python.org/py3k/library/codecs.html#standard-encodings

.. class:: Time(seconds=-1.0, milliseconds=-1, microseconds=-1)

   Instead of forcing the user to use a specific time units, SFML uses
   this class to encapsulate time values. The user can get an actual
   time value by using the following methods: :meth:`as_seconds`,
   :meth:`as_milliseconds` and :meth:`as_microseconds`. You can also
   create your own time objects by calling the constructor with one
   keyword argument.

   Using one keyword argument is equivalent to calling the
   corresponding function. For example, ``sfml.seconds(10) ==
   sfml.Time(seconds=10)``.

   This class provides the following special methods:

   * Comparison operators: ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``.
   * Arithmetic operators: ``+``, ``-``, ``*``, ``/``, unary ``-``.
   * ``str()`` returns a representation of the number of seconds.

   .. attribute:: ZERO

      Predefind "zero" time value (class attribute).

   .. method:: as_seconds()

      Return a ``float`` containing the number of seconds for this time object.

   .. method:: as_milliseconds()

      Return an ``int`` containing the number of milliseconds for this time
      object.

   .. method:: as_microseconds()

      Return an ``int`` containing the number of microseconds for this time
      object.

   .. method:: copy()

      Return a new Time object with the same value as self.

.. class:: Clock

   Utility class that measures the elapsed time.

   Its provides the most precise time that the underlying OS can
   achieve (generally microseconds or nanoseconds). It also ensures
   monotonicity, which means that the returned time can never go
   backward, even if the system time is changed.

   Usage example::

      clock = sfml.Clock()
      ...
      time1 = clock.elapsed_time
      ...
      time2 = clock.restart()

   The :class:`Time` object returned by the clock can then be
   converted to a number of seconds, milliseconds or even
   microseconds.

   .. attribute:: elapsed_time

      A :class:`Time` object containing the time elapsed since the
      last call to :meth:`restart`, or the construction of the
      instance if :meth:`restart` has not been called yet.

   .. method:: restart()

      Restart the clock, and return a :class:`Time` object containing
      the elapsed time since the clock started.

.. class:: Vector2f(float x=0.0; float y=0.0)

   You don't have to use this class; everywhere you can pass a
   :class:`Vector2f`, you should be able to pass a tuple as
   well. However, it can be more practical to use it, as it overrides
   arithmetic and comparison operators, is mutable and requires that
   you use the :attr:`x` and :attr:`y` members instead of indexing.

   This class provides the following special methods:

   * Comparison operators: ``==`` and ``!=``.

   .. attribute:: x

      *x* coordinate for this vector.

   .. attribute:: y

      *y* coordinate for this vector.

   .. method:: copy()

      Return a new :class:`Vector2f` with ``x`` and ``y`` set to the
      value of ``self``.


text:
<?php return array (
  'Comments have been disabled for this post.' => '',
  '/blog/2014/06/12/sample-post' => '',
  'General' => '',
  'Post created.' => '',
  'Show Avatars from Gravatar.' => '',
  'Enter Excerpt' => '',
  '{0} No pending|{1} One pending|]1,Inf[ %comments% pending' => '',
  'Comments are closed.' => '',
  'Appearance' => '',
  'Draft' => '',
  'Comments (%count%)' => '',
  'Approve' => '',
  'latest first.' => '',
  'Permalink' => '',
  '- Select Post -' => '',
  'Submit comment' => '',
  '/blog/123' => '',
  'Continue Reading' => '',
  '{0} No comment status updated.|{1} Comment status updated.|]1,Inf[ Comment statuses updated.' => '',
  'Author' => '',
  'Unapprove' => '',
  'Require name and e-mail.' => '',
  'Posts View' => '',
  'Default post settings' => '',
  'Post saved.' => '',
  '{0} No post unpublished.|{1} Post unpublished.|]1,Inf[ Posts unpublished.' => '',
  'You are not allowed to view comments.' => '',
  'Comments' => '',
  '/blog/2014/06/sample-post' => '',
  'Posts' => '',
  'Pending' => '',
  'Comment' => '',
  'Approved' => '',
  'Edit Post' => '',
  'Enable Comments' => '',
  'Unable to access this post!' => '',
  'Pending Review' => '',
  'Excerpt' => '',
  'In response to' => '',
  'Invalid post id.' => '',
  'Blog' => '',
  'Enter Title' => '',
  'Logged in as %name%' => '',
  'Older posts' => '',
  '{0} No post copied.|{1} Post copied.|]1,Inf[ Posts copied.' => '',
  'Order comments by' => '',
  'Please login to leave a comment.' => '',
  'Posts per page' => '',
  'E-mail' => '',
  'Post with slug "%slug%" not found!' => '',
  'Please wait another %seconds% seconds before commenting again.' => '',
  '/blog/sample-post' => '',
  'No comments found.' => '',
  'Publish on' => '',
  'Please provide valid name and email.' => '',
  'You are not allowed to post comments.' => '',
  'Publish' => '',
  'Unpublished' => '',
  'Mark as spam' => '',
  '%date% at %time%' => '',
  'Custom' => '',
  'Newer posts' => '',
  'Published' => '',
  'Add Post' => '',
  'Date' => '',
  'Reply' => '',
  'Day and name' => '',
  'You\'ve made some changes! Leaving the post without saving will discard all changes.' => '',
  'levels deep.' => '',
  'Comment created.' => '',
  'In response to %post%' => '',
  'Comments on %title%' => '',
  '{0} No post published.|{1} Post published.|]1,Inf[ Posts published.' => '',
  'Comment saved.' => '',
  '{0} No comment deleted.|{1} Comment deleted.|]1,Inf[ Comments deleted.' => '',
  'Please login to view comments.' => '',
  'Post with id "%id%" not found!' => '',
  'days.' => '',
  'Thanks for commenting!' => '',
  'No posts found.' => '',
  'Month and name' => '',
  'Close comments on articles older than' => '',
  'Whoops, something went wrong!' => '',
  'Unpublish' => '',
  'Your email address will not be published.' => '',
  'Written by %name% on %date%' => '',
  'Enable nested comments of' => '',
  '{0} No post deleted.|{1} Post deleted.|]1,Inf[ Posts deleted.' => '',
  'Spam' => '',
  'Leave a comment' => '',
  '{0} No comments|{1} %num% Comment|]1,Inf[ %num% Comments' => '',
  'Post' => '',
  'Numeric' => '',
  'latest last.' => '',
);


text:
DogeCommunityImages
===================

Dogecoin Community Images

These images are created by the Dogecoin Community and are free to use and modify.

Repository Created By u/4moves --

If you like please donate -->>Dogecoin: DQRxmUhZYeGhxVNXBrh4jRftEoysTTDiWi

To request images to be added go to

http://www.reddit.com/message/compose?to=4moves&subject=Dogecoin%20Community%20Images&message=Message%20Here


text:
    <mat-toolbar td-sidenav-content (click)="gotoFeeds()" style="cursor:pointer">
      <mat-toolbar-row>
        <mat-icon class="push-left-xs" style="margin-right:20px">linear_scale</mat-icon>
        {{'views.main.feeds' | translate}}
      </mat-toolbar-row>
    </mat-toolbar>

      <mat-nav-list>

        <ng-template let-link let-last="last" ngFor [ngForOf]="summaryLinks" >

            <mat-icon [color]=" link.selected ? 'accent': ''" mat-list-icon *ngIf="link.icon != null">{{link.icon}}</mat-icon>

{{link.label | translate}}

        </ng-template>

        <ng-container >

          <ng-template let-link let-last="last" ngFor [ngForOf]="staticFeedLinks">

              <mat-icon [color]=" link.selected ? 'accent': ''" mat-list-icon *ngIf="link.icon != null">{{link.icon}}</mat-icon>

{{link.label | translate}}

          </ng-template>
        </ng-container>

      </mat-nav-list>

          <ui-view></ui-view>


text:
function plot_individ_spheres_per_sub(settings,params)
numranspheres = 10;
rng(10);
randsphers = 32234;
%randsphers = randperm(52503,numranspheres);
numshufs = 50;
spheredir = 'sphers_for_jonathan_z_scored';
spherdirwrite = 'spheres';
figdir = 'figures';
for j = 1:length(randsphers)%:length(settings.experconds) % loop on experiment
    start = tic;
    rawbetafn = findFilesBVQX(...
        fullfile(settings.datadir,...
        settings.experconds{1}),...
        [settings.datafileprefix '*.mat'],...
        struct('maxdepth',1));
    rng(j); % set seed
    hfig = figure('Visible','off');
    hfig.Position = [-1919         281        1920        1083];
    for k = 1:length(rawbetafn) % loop on subjects
        load(rawbetafn{k});
        idx = knnsearch(locations, locations, 'K', 27); % neighbours
        sphreidx = randsphers(j);
        sphere = data(:,idx(sphreidx ,:));
        for m = 1:numshufs
            if m == 1
                labelsuse = labels;
            else
                rng(m*k);
                labelsuse = labels(randperm(length(labels)));
            end
        x = sphere(labelsuse==1,:); y = sphere(labelsuse==2,:);
        tmp = calcTstatMuniMengTwoGroup(x,y);
        ansmat(m) = tmp(1);
        end
        seclevel(k,:) = ansmat;
        [pn, fn] = fileparts(rawbetafn{k});
        tmp1 = regexp(fn,'[0-9]+','match'); subnum = str2num(tmp1{1});
        spherename = sprintf('sub_%.3d_sphere_%d_tval_%.2f.txt',...
            subnum,randsphers(j),ansmat(1));
        spherefolder = fullfile(settings.resfold,spheredir,spherdirwrite);
        csvwrite(fullfile(spherefolder,spherename),[labels, sphere]);
        subplot(4,5,k);hold on;
        histogram(ansmat(2:end));
        scatter(ansmat(1),0,100,'r','filled');
        xlabel('tval (2013)');
        ylabel('count');
        title(strrep(spherename(1:end-4),'_',' '),'FontSize',11);
        set(gca,'FontSize',10);
    end
    spherefigfolder = fullfile(settings.resfold,spheredir,figdir);
    hfigname = sprintf('individ_sub_sphere_%d.pdf',randsphers(j));
    printFigToPDFa4(hfig,fullfile(spherefigfolder,hfigname));

    realvals = mean(seclevel(:,1));
    % loop on second level to randomize
    seclevelshuf = seclevel(:,2:end);
    for i = 1:size(seclevelshuf,1);
        idxs = randperm(size(seclevelshuf,2));
        shufsseclevel(:,i) = seclevelshuf(i,idxs);
    end
    % plot second levle
    hfig = figure('Visible','off');hold on;
    histogram(shufsseclevel);
    scatter(realvals(1),0,100,'r','filled');
    xlabel('tval (2013)');
    ylabel('count');
    hfigname = sprintf('sec_level_sphere_%d.pdf',randsphers(j));
    figtitle = sprintf('sec level sphere %d', randsphers(j));
    title(strrep(figtitle,'_',' '),'FontSize',8);
    printFigToPDFa4(hfig,fullfile(spherefigfolder,hfigname));
    fprintf('sphere %d done in %f\n',randsphers(j),toc(start));
end

end


text:
package org.apache.syncope.client.console.commons;

import java.io.Serializable;
import org.apache.wicket.extensions.markup.html.repeater.data.sort.SortOrder;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;

public abstract class DirectoryDataProvider<T extends Serializable> extends SortableDataProvider<T, String> {

    private static final long serialVersionUID = 6267494272884913376L;

    protected final int paginatorRows;

    public DirectoryDataProvider(final int paginatorRows) {
        super();
        this.paginatorRows = paginatorRows;

        // default sorting
        setSort("key", SortOrder.ASCENDING);
    }
}


text:
package uk.nhs.hdn.barcodes.gs1.keys.globalTradeItemNumbers;

import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import uk.nhs.hdn.common.digits.Digit;
import uk.nhs.hdn.common.digits.DigitList;
import uk.nhs.hdn.common.digits.Digits;
import uk.nhs.hdn.barcodes.gs1.Gs1ExtractingCheckDigitCalculator;
import uk.nhs.hdn.barcodes.gs1.keys.KeyFormat;
import uk.nhs.hdn.common.exceptions.ImpossibleEnumeratedStateException;

import java.util.Set;

import static uk.nhs.hdn.common.digits.Digit.*;
import static uk.nhs.hdn.common.VariableArgumentsHelper.unmodifiableSetOf;

public enum GlobalTradeItemNumberFormat implements KeyFormat
{
	// ???
	GTIN_8("GTIN-8", 8, "EAN-UCC-8", "EAN-8")
	{
		@NotNull
		@Override
		public Digits gs1PrefixDigits(@NotNull final Digits digits)
		{
			throw new UnsupportedOperationException("Not implemented due to time pressures");
		}
	},
	// 2 digit prefix*, 9 digits company prefix + item, 1 check digit
	// From the old US GS1 MO range, so prefix with a zero
	GTIN_12("GTIN-12", 12, "EAN-UCC-12", "EAN-12", "UPC")
	{
		@NotNull
		@Override
		public Digits gs1PrefixDigits(@NotNull final Digits digits)
		{
			return new Digits(false, Zero).add(digits.slice(1, 2));
		}
	},
	// 3 digit prefix, 3-8 digits company prefix, 6 - 1 item, 1 check digit
	GTIN_13("GTIN-13", 13, "EAN-UCC-13", "EAN-13", "CIP")
	{
		@NotNull
		@Override
		public Digits gs1PrefixDigits(@NotNull final Digits digits)
		{
			return digits.slice(1, 3);
		}
	},
	// 1 indicator digit, 3 digit prefix, 3-8 digits company prefix, 6 - 1 item, 1 check digit
	GTIN_14("GTIN-14", 14)
	{
		@NotNull
		@Override
		public Digits gs1PrefixDigits(@NotNull final Digits digits)
		{
			return digits.slice(2, 4);
		}
	},
	;

	@SuppressWarnings("UtilityClassWithoutPrivateConstructor")
	private static final class CompilerWorkaround
	{
		private static final GlobalTradeItemNumberFormat[] Index = new GlobalTradeItemNumberFormat[14 + 1];
	}

	public static final int T1 = 1;
	public static final int T2 = 2;
	public static final int T13 = 13;
	public static final int T14 = 14;
	public static final int MaximumOneBasedPositionT = T14;

	@NotNull
	private final String actualName;
	private final Set<String> formerActualNames;
	private final int oneBasedPositionTOffset;
	private final Gs1ExtractingCheckDigitCalculator gs1CheckDigitCalculator;

	GlobalTradeItemNumberFormat(@NonNls @NotNull final String actualName, final int correctNumberOfDigits, @NonNls @NotNull final String... formerActualNames)
	{
		this.actualName = actualName;
		this.formerActualNames = unmodifiableSetOf(formerActualNames);

		oneBasedPositionTOffset = MaximumOneBasedPositionT - correctNumberOfDigits;

		CompilerWorkaround.Index[correctNumberOfDigits] = this;
		gs1CheckDigitCalculator = new Gs1ExtractingCheckDigitCalculator
		(
			correctNumberOfDigits
		);
	}

	@NonNls
	@NotNull
	@Override
	public String actualName()
	{
		return actualName;
	}

	@Override
	public void guardCorrectNumberOfDigitsIfNoCheckDigit(@NotNull final Digits digits)
	{
		gs1CheckDigitCalculator.guardCorrectNumberOfDigitsIfNoCheckDigit(digits);
	}

	@Override
	public void guardCorrectNumberOfDigits(@NotNull final Digits digits)
	{
		gs1CheckDigitCalculator.guardCorrectNumberOfDigits(digits);
	}

	@Override
	public void guardCheckDigitCorrect(@NotNull final Digits digits)
	{
		gs1CheckDigitCalculator.guardCheckDigitCorrect(digits);
	}

	@Override
	@NotNull
	public Digit calculateCheckDigit(@NotNull final Digits digits)
	{
		return gs1CheckDigitCalculator.calculateCheckDigit(digits);
	}

	@NotNull
	@Override
	public Digits addCheckDigit(@NotNull final Digits withoutCheckDigits)
	{
		return gs1CheckDigitCalculator.addCheckDigit(withoutCheckDigits);
	}

	@Override
	@NotNull
	public Digit extract(@NotNull final DigitList digits, final int oneBasedPositionT)
	{
		final int index = oneBasedPositionT - oneBasedPositionTOffset;
		if (index < T1)
		{
			return Zero;
		}
		return digits.digitAtPositionT(index);
	}

	@SuppressWarnings("ReturnOfCollectionOrArrayField")
	@NotNull
	@Override
	public Set<String> formerActualNames()
	{
		return formerActualNames;
	}

	@SuppressWarnings("RefusedBequest")
	@Override
	@NotNull
	public String toString()
	{
		return actualName;
	}

	@Override
	public int size()
	{
		return MaximumOneBasedPositionT;
	}

	@Nullable
	public static GlobalTradeItemNumberFormat globalTradeItemNumberFormatNumberOfDigits(final int numberOfDigits)
	{
		if (numberOfDigits < CompilerWorkaround.Index.length)
		{
			return CompilerWorkaround.Index[numberOfDigits];
		}
		return null;
	}

	@NotNull
	public abstract Digits gs1PrefixDigits(@NotNull final Digits digits);

	@NotNull
	public static Digits upcEToUpcA(@SuppressWarnings("TypeMayBeWeakened") @NotNull final Digits eightDigits)
	{
		if (eightDigits.size() != 8)
		{
			throw new IllegalArgumentException("digits must have a size of 8");
		}

		final Digit digit1 = eightDigits.digitAt(1);
		final Digit digit2 = eightDigits.digitAt(2);
		final Digit digit3 = eightDigits.digitAt(3);
		final Digit digit4 = eightDigits.digitAt(4);
		final Digit digit5 = eightDigits.digitAt(5);
		final Digit digit6 = eightDigits.digitAt(6);

		final Digits manufacturerNumber;
		final Digits itemNumber;
		switch (digit6)
		{
			case Zero:
				manufacturerNumber = new Digits(false, digit1, digit2, digit6, Zero, Zero);
				itemNumber = new Digits(false, Zero, Zero, digit3, digit4, digit5);
				break;

			case One:
				manufacturerNumber = new Digits(false, digit1, digit2, digit6, Zero, Zero);
				itemNumber = new Digits(false, Zero, Zero, digit3, digit4, digit5);
				break;

			case Two:
				manufacturerNumber = new Digits(false, digit1, digit2, digit6, Zero, Zero);
				itemNumber = new Digits(false, Zero, Zero, digit3, digit4, digit5);
				break;

			case Three:
				manufacturerNumber = new Digits(false, digit1, digit2, digit3, Zero, Zero);
				itemNumber = new Digits(false, Zero, Zero, Zero, digit4, digit5);
				break;

			case Four:
				manufacturerNumber = new Digits(false, digit1, digit2, digit3, digit4, Zero);
				itemNumber = new Digits(false, Zero, Zero, Zero, Zero, digit5);
				break;

			case Five:
			case Six:
			case Seven:
			case Eight:
			case Nine:
				manufacturerNumber = new Digits(false, digit1, digit2, digit3, digit4, digit5);
				itemNumber = new Digits(false, Zero, Zero, Zero, Zero, digit6);
				break;

			default:
				throw new ImpossibleEnumeratedStateException();
		}

		final Digits withoutCheckDigit = new Digits(false, Zero).add(manufacturerNumber).add(itemNumber);
		final Digit checkDigit = GTIN_12.calculateCheckDigit(withoutCheckDigit);
		return withoutCheckDigit.add(checkDigit);
	}

	public static Digits upcAToUpcE(@SuppressWarnings("TypeMayBeWeakened") @NotNull final Digits twelveDigits) throws DigitsCanNotbeCompressedException
	{
		final Digit first = twelveDigits.digitAt(0);
		if (!first.isZeroToOne())
		{
			throw new DigitsCanNotbeCompressedException("as they do not start with zero or one");
		}

		final Digits withoutCheckDigit = new Digits(false, first).add(extract(twelveDigits));
		final Digit checkDigit = GTIN_8.calculateCheckDigit(withoutCheckDigit);
		return withoutCheckDigit.add(checkDigit);
	}

	private static Digits extract(final Digits twelveDigits) throws DigitsCanNotbeCompressedException
	{
		final Digit thirdDigit = twelveDigits.digitAt(3);
		final Digit fourthDigit = twelveDigits.digitAt(4);
		final Digit fifthDigit = twelveDigits.digitAt(5);
		if (thirdDigit.isZeroToTwo() && fourthDigit == Zero && fifthDigit == Zero)
		{
			return twelveDigits.slice(1, 3).add(twelveDigits.slice(8, 11)).add(twelveDigits.slice(3, 4));
		}
		if (fourthDigit == Zero && fifthDigit == Zero)
		{
			return twelveDigits.slice(1, 4).add(twelveDigits.slice(9, 11)).add(Three);
		}
		if (fifthDigit == Zero)
		{
			return twelveDigits.slice(1, 5).add(twelveDigits.digitAt(10)).add(Four);
		}
		if (twelveDigits.digitAt(10).isGreaterThanOrEqualTo(Five))
		{
			return twelveDigits.slice(1, 6).add(twelveDigits.digitAt(10));
		}
		throw new DigitsCanNotbeCompressedException("because the product coder is not between 00005 and 00009");
	}
}


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace EasyWeChat\Tests\Work\Server\Handlers;

use EasyWeChat\Kernel\Decorators\FinallyResult;
use EasyWeChat\Kernel\Encryptor;
use EasyWeChat\Kernel\ServiceContainer;
use EasyWeChat\Tests\TestCase;
use EasyWeChat\Work\Server\Handlers\EchoStrHandler;
use Symfony\Component\HttpFoundation\Request;

class EchoStrHandlerTest extends TestCase
{
    public function testHandle()
    {
        $time = time();
        $nonce = 'foo';
        $signature = 'mock-signature';
        $request = Request::create('/path/to/resource?foo=bar', 'GET', [
            'timestamp' => $time,
            'nonce' => $nonce,
            'msg_signature' => $signature,
            'echostr' => 'mock-encrypted-echostr',
        ]);
        $encryptor = \Mockery::mock(Encryptor::class);
        $encryptor->allows()->decrypt('mock-encrypted-echostr', $signature, $nonce, $time)->andReturn('mock-decrypted-echostr');
        $app = new ServiceContainer([], [
            'request' => $request,
            'encryptor' => $encryptor,
        ]);
        $handler = new EchoStrHandler($app);

        $result = $handler->handle();
        $this->assertInstanceOf(FinallyResult::class, $result);
        $this->assertSame('mock-decrypted-echostr', $result->content);
    }

    public function testHandleWithoutEchoStr()
    {
        $request = Request::create('/path/to/resource?foo=bar');
        $app = new ServiceContainer([], [
            'request' => $request,
        ]);
        $handler = new EchoStrHandler($app);

        $this->assertNull($handler->handle());
    }
}


text:
package com.snatik.storage;

/**
 * As it sounds, anything that can stored and represented as byte array.
 */
public interface Storable {
    byte[] getBytes();
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.restapi.controller;

import com.yahoo.concurrent.maintenance.JobControl;
import com.yahoo.restapi.SlimeJsonResponse;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;

import java.util.TreeSet;

/**
 * A response containing maintenance job status
 *
 * @author bratseth
 */
public class JobsResponse extends SlimeJsonResponse {

    public JobsResponse(JobControl jobControl) {
        super(toSlime(jobControl));
    }

    private static Slime toSlime(JobControl jobControl) {
        Slime slime = new Slime();
        Cursor root = slime.setObject();

        Cursor jobArray = root.setArray("jobs");
        for (String jobName : jobControl.jobs())
            jobArray.addObject().setString("name", jobName);

        Cursor inactiveArray = root.setArray("inactive");
        for (String jobName : new TreeSet<>(jobControl.inactiveJobs()))
            inactiveArray.addString(jobName);

        return slime;
    }

}


text:
package com.reactnativenavigation.views.collapsingToolbar;

import com.reactnativenavigation.layouts.BottomTabsLayout;
import com.reactnativenavigation.params.StyleParams;
import com.reactnativenavigation.screens.Screen;
import com.reactnativenavigation.utils.ViewUtils;

public class CollapsingViewPagerContentViewMeasurer extends CollapsingViewMeasurer {
    private int titleBarHeight;
    private boolean layoutHasBottomTabs;

    public CollapsingViewPagerContentViewMeasurer(final CollapsingTopBar topBar, final Screen screen, StyleParams styleParams) {
        super(topBar, screen, styleParams);
        ViewUtils.runOnPreDraw(screen, new Runnable() {
            @Override
            public void run() {
                layoutHasBottomTabs = screen.getParent() instanceof BottomTabsLayout;
            }
        });
        ViewUtils.runOnPreDraw(topBar, new Runnable() {
            @Override
            public void run() {
                titleBarHeight = topBar.getTitleBarHeight();
            }
        });
    }

    @Override
    public int getMeasuredHeight(int heightMeasureSpec) {
        int height = screenHeight - topBar.getCollapsedHeight();
        if (hasBottomTabs() && drawScreenUnderBottomTabs()) {
            height -= bottomTabsHeight;
        }
        if (!styleParams.titleBarHideOnScroll) {
            height -= titleBarHeight;
        }
        return height;
    }

    private boolean drawScreenUnderBottomTabs() {
        return !styleParams.drawScreenAboveBottomTabs;
    }

    private boolean hasBottomTabs() {
        return layoutHasBottomTabs && !styleParams.bottomTabsHidden;
    }
}


text:
namespace Poco {

class Foundation_API SharedLibraryImpl
{
protected:
	SharedLibraryImpl();
	~SharedLibraryImpl();
	void loadImpl(const std::string& path, int flags);
	void unloadImpl();
	bool isLoadedImpl() const;
	void* findSymbolImpl(const std::string& name);
	const std::string& getPathImpl() const;
	static std::string suffixImpl();

private:
	std::string _path;
	static FastMutex _mutex;
};

} // namespace Poco

#endif // Foundation_SharedLibrary_VMS_INCLUDED


text:
using RippleSharp.Rippled.Constants;
using RippleSharp.Rippled.Models.Requests.AccountInformation;

namespace RippleSharp.Rippled.Client.RpcJson.Requests.AccountInformation
{
    public class AccountCurrencyRequest : RpcJsonRequest<AccountCurrencyRequestParams>
    {
        public override string Method => ApiMethod.AccountCurrencies;
    }
}


text:
package prospector.routiduct.gui.blueprint.element;

import jline.internal.Nullable;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import prospector.routiduct.Routiduct;
import prospector.routiduct.gui.GuiRoutiduct;
import prospector.routiduct.gui.Sprite;

public class ElementBase {

	protected final int x;
	protected final int y;
	protected final Sprite sprite;

	public ElementBase(Sprite sprite, int x, int y) {
		this.sprite = sprite;
		this.x = x;
		this.y = y;
	}

	public ElementBase(int x, int y) {
		this(null, x, y);
	}

	/**
	 * @return the element's sprite **MAY BE NULL**
	 */
	@Nullable
	public Sprite getSprite() {
		return sprite;
	}

	@SideOnly(Side.CLIENT)
	public void draw(GuiRoutiduct gui) {
		if (sprite != null) {
			GlStateManager.color(1F, 1F, 1F);
			Routiduct.proxy.getGuiAssembler().setTextureSheet(sprite.textureLocation);
			gui.drawTexturedModalRect(x + gui.getOffsetFactorX(), y + gui.getOffsetFactorY(), sprite.x, sprite.y, sprite.width, sprite.height);
		}
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}
}


text:
import config from './config'
import { coinbase, keys } from './keys'
import Tx from 'ethereumjs-tx'
import ethUtil from 'ethereumjs-util'
import keythereum from 'keythereum'

const hasAddress = async function (address, callback) {
  var account = keys[address]
  callback(null, typeof account !== 'undefined' && account != null)
}

const signTransaction = async function signTransaction(tx_params,callback) {
  var account = keys[tx_params.from]

  if (typeof account === 'undefined' || account == null) {
    callback(new Error("Cannot find from Address"))
  }

  const rawTx = {
    nonce: tx_params.nonce,
    gasPrice: "0x0",
    gasLimit: "0x3d0901",
    value: '0x0',
    data: ''
  }

  if (tx_params.gas != null) {
    rawTx.gasLimit = tx_params.gas
  }

  if (tx_params.to != null) {
    rawTx.to = tx_params.to
  }

  if (tx_params.value != null) {
    rawTx.value = tx_params.value
  }

  if (tx_params.data != null) {
    rawTx.data = tx_params.data
  }

  const tx = new Tx(rawTx)

  tx.sign(account.privateKey)

  const serializedTx =  ethUtil.addHexPrefix(tx.serialize().toString('hex'))

  callback(null, serializedTx)
}

export default {
    hasAddress,
    signTransaction
}


text:
Very simple Chrome extension for Tidal media keys

## Usage

  F7 => Previous

  F8 => Play

  F9 => Next


text:
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
)

func runConfig() (err error) {

	clientID := getClientID()
	clientSecret := getClientSecret()
	code := getCode(clientID)
	refreshToken, err := getRefreshToken(clientID, clientSecret, code)
	if err != nil {
		return err
	}
	usernames := getTeamAndUserNames()

	fmt.Printf("Saving your configuration file...\n")

	c := ClientConfig{
		ClientID:     clientID,
		ClientSecret: clientSecret,
		RefreshToken: refreshToken,
		Usernames:    usernames,
	}

	return saveClientConfig(c)
}

func getClientID() (clientID string) {

	fmt.Printf("Please enter your client id: ")
	fmt.Scanln(&clientID)

	return
}

func getClientSecret() (clientSecret string) {

	fmt.Printf("Please enter your client secret: ")
	fmt.Scanln(&clientSecret)

	return
}

func getCode(clientID string) (code string) {

	authUri := fmt.Sprintf(AUTHORIZE_URI, clientID)
	fmt.Printf("Please visit this URI and finish authorization: \n%s\n", authUri)
	fmt.Printf("After authorization, please copy the code URI parameter and paste it here: ")
	fmt.Scanln(&code)

	return
}

func getRefreshToken(clientID, clientSecret, code string) (string, error) {

	values := url.Values{"grant_type": {"authorization_code"}, "code": {code}}.Encode()
	req, err := http.NewRequest("POST", ACCESS_TOKEN_URI, strings.NewReader(values))

	if err != nil {
		return "", err
	}

	req.SetBasicAuth(clientID, clientSecret)
	req.Header.Add("content-type", "application/x-www-form-urlencoded")

	client := http.Client{
		Timeout: 10 * time.Second,
	}
	resp, err := client.Do(req)

	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)

	if err != nil {
		return "", err
	}

	var oc Oauth2Config
	err = json.Unmarshal(respBody, &oc)

	if err != nil {
		return "", err
	}

	return oc.RefreshToken, nil
}

func getTeamAndUserNames() (usernames []string) {

	fmt.Printf("Now please enter the usernames/team names one by one, \n" +
		"separated by Enter, and finish with an empty line:\n")

	for {
		var username string
		fmt.Scanln(&username)

		if len(username) < 1 {
			break
		}

		usernames = append(usernames, username)
	}

	return
}


text:
<?php

namespace BinSoul\Db\Orm\Definition;

use BinSoul\Db\Definition\DataType;

/**
 * Builds instances of the {@see DataType} interface.
 */
interface DataTypeFactory
{
    /**
     * @param string $type
     * @param mixed  $options
     *
     * @return DataType
     */
    public function build($type, array $options);
}