text:
"""This submodule contains modifications of functions
included in ArviZ's plots.plot_utils submodule. I include them here with
slight modifications because of a bug in the purge_duplicates() function
in ArviZ version 0.6.1. This bug is addressed in this pull request:
https://github.com/arviz-devs/arviz/pull/1027. Until that is merged,
this submodule is used in bebi103 to convert xarray data to Numpy
arrays.

The code is licensed under an Apache 2.0 License, reproduced below.

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

"""

import itertools
import numpy as np
import xarray as xr

def _dims(data, var_name, skip_dims):
    return [dim for dim in data[var_name].dims if dim not in skip_dims]

def _zip_dims(new_dims, vals):
    return [{k: v for k, v in zip(new_dims, prod)} for prod in itertools.product(*vals)]

def purge_duplicates(list_in):
    """Remove duplicates from list while preserving order.

    Parameters
    ----------
    list_in: Iterable

    Returns
    -------
    list
        List of first occurrences in order
    """
    # Algorithm taken from Stack Overflow,
    # https://stackoverflow.com/questions/480214. Content by Georgy
    # Skorobogatov (https://stackoverflow.com/users/7851470/georgy) and
    # Markus Jarderot
    # (https://stackoverflow.com/users/22364/markus-jarderot), licensed
    # under CC-BY-SA 4.0.
    # https://creativecommons.org/licenses/by-sa/4.0/.

    seen = set()
    seen_add = seen.add
    return [x for x in list_in if not (x in seen or seen_add(x))]

def make_label(var_name, selection, position="below"):
    """Consistent labelling for plots.
    Parameters
    ----------
    var_name : str
       Name of the variable
    selection : dict[Any] -> Any
        Coordinates of the variable
    position : str
        Whether to position the coordinates' label "below" (default) or "beside"
        the name of the variable
    Returns
    -------
    label
        A text representation of the label
    """
    if selection:
        sel = selection_to_string(selection)
        if position == "below":
            sep = "\n"
        elif position == "beside":
            sep = " "
    else:
        sep = sel = ""
    return "{}{}{}".format(var_name, sep, sel)

def selection_to_string(selection):
    """Convert dictionary of coordinates to a string for labels.
    Parameters
    ----------
    selection : dict[Any] -> Any
    Returns
    -------
    str
        key1: value1, key2: value2, ...
    """
    return ", ".join(["{}".format(v) for _, v in selection.items()])

def xarray_sel_iter(
    data, var_names=None, combined=False, skip_dims=None, reverse_selections=False
):
    """Convert xarray data to an iterator over variable names and selections.
    Iterates over each var_name and all of its coordinates, returning the variable
    names and selections that allow properly obtain the data from ``data`` as desired.
    Parameters
    ----------
    data : xarray.Dataset
        Posterior data in an xarray
    var_names : iterator of strings (optional)
        Should be a subset of data.data_vars. Defaults to all of them.
    combined : bool
        Whether to combine chains or leave them separate
    skip_dims : set
        dimensions to not iterate over
    reverse_selections : bool
        Whether to reverse selections before iterating.
    Returns
    -------
    Iterator of (var_name: str, selection: dict(str, any))
        The string is the variable name, the dictionary are coordinate names to values,.
        To get the values of the variable at these coordinates, do
        ``data[var_name].sel(**selection)``.
    """
    if skip_dims is None:
        skip_dims = set()

    if combined:
        skip_dims = skip_dims.union({"chain", "draw"})
    else:
        skip_dims.add("draw")

    if var_names is None:
        if isinstance(data, xr.Dataset):
            var_names = list(data.data_vars)
        elif isinstance(data, xr.DataArray):
            var_names = [data.name]
            data = {data.name: data}

    for var_name in var_names:
        if var_name in data:
            new_dims = _dims(data, var_name, skip_dims)
            vals = [purge_duplicates(data[var_name][dim].values) for dim in new_dims]
            dims = _zip_dims(new_dims, vals)
            if reverse_selections:
                dims = reversed(dims)

            for selection in dims:
                yield var_name, selection

def xarray_var_iter(
    data, var_names=None, combined=False, skip_dims=None, reverse_selections=False
):
    """Convert xarray data to an iterator over vectors.
    Iterates over each var_name and all of its coordinates, returning the 1d
    data.
    Parameters
    ----------
    data : xarray.Dataset
        Posterior data in an xarray
    var_names : iterator of strings (optional)
        Should be a subset of data.data_vars. Defaults to all of them.
    combined : bool
        Whether to combine chains or leave them separate
    skip_dims : set
        dimensions to not iterate over
    reverse_selections : bool
        Whether to reverse selections before iterating.
    Returns
    -------
    Iterator of (str, dict(str, any), np.array)
        The string is the variable name, the dictionary are coordinate names to values,
        and the array are the values of the variable at those coordinates.
    """
    data_to_sel = data
    if var_names is None and isinstance(data, xr.DataArray):
        data_to_sel = {data.name: data}

    for var_name, selection in xarray_sel_iter(
        data,
        var_names=var_names,
        combined=combined,
        skip_dims=skip_dims,
        reverse_selections=reverse_selections,
    ):
        yield var_name, selection, data_to_sel[var_name].sel(**selection).values

def xarray_to_ndarray(data, *, var_names=None, combined=True):
    """Take xarray data and unpacks into variables and data into list and numpy array respectively.
    Assumes that chain and draw are in coordinates
    Parameters
    ----------
    data: xarray.DataSet
        Data in an xarray from an InferenceData object. Examples include posterior or sample_stats
    var_names: iter
        Should be a subset of data.data_vars not including chain and draws. Defaults to all of them
    combined: bool
        Whether to combine chain into one array
    Returns
    -------
    var_names: list
        List of variable names
    data: np.array
        Data values
    """
    data_to_sel = data
    if var_names is None and isinstance(data, xr.DataArray):
        data_to_sel = {data.name: data}

    iterator1, iterator2 = itertools.tee(
        xarray_sel_iter(data, var_names=var_names, combined=combined)
    )
    vars_and_sel = list(iterator1)
    unpacked_var_names = [
        make_label(var_name, selection) for var_name, selection in vars_and_sel
    ]

    # Merge chains and variables, check dtype to be compatible with divergences data
    data0 = data_to_sel[vars_and_sel[0][0]].sel(**vars_and_sel[0][1])
    unpacked_data = np.empty((len(unpacked_var_names), data0.size), dtype=data0.dtype)
    for idx, (var_name, selection) in enumerate(iterator2):
        unpacked_data[idx] = data_to_sel[var_name].sel(**selection).values.flatten()

    return unpacked_var_names, unpacked_data


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using Mozu.Api;
using Mozu.Api.Security;
using Mozu.Api.Test.Helpers;
using System.Diagnostics;
using Newtonsoft.Json.Linq;
using System.Threading;

#endregion

namespace Mozu.Api.Test.Factories.Platform.Developer
{
	/// <summary>
	/// Use the Authtickets resource to manage authentication tickets for your developer account.
	/// </summary>
	public partial class DeveloperAdminUserAuthTicketFactory : BaseDataFactory
	{

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = DeveloperAdminUserAuthTicketFactory.CreateDeveloperUserAuthTicket(handler : handler,  userAuthInfo :  userAuthInfo,  developerAccountId :  developerAccountId,  responseFields :  responseFields,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<DeveloperAdminUserAuthTicket/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static Mozu.Api.Contracts.AdminUser.DeveloperAdminUserAuthTicket CreateDeveloperUserAuthTicket(ServiceClientMessageHandler handler,
 		 Mozu.Api.Contracts.Core.UserAuthInfo userAuthInfo, int? developerAccountId = null, string responseFields = null,
		 HttpStatusCode expectedCode = HttpStatusCode.Created, HttpStatusCode successCode = HttpStatusCode.Created)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Platform.Developer.DeveloperAdminUserAuthTicketClient.CreateDeveloperUserAuthTicketClient(
				 userAuthInfo :  userAuthInfo,  developerAccountId :  developerAccountId,  responseFields :  responseFields		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = DeveloperAdminUserAuthTicketFactory.RefreshDeveloperAuthTicket(handler : handler,  existingAuthTicket :  existingAuthTicket,  developerAccountId :  developerAccountId,  responseFields :  responseFields,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<DeveloperAdminUserAuthTicket/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static Mozu.Api.Contracts.AdminUser.DeveloperAdminUserAuthTicket RefreshDeveloperAuthTicket(ServiceClientMessageHandler handler,
 		 Mozu.Api.Contracts.AdminUser.DeveloperAdminUserAuthTicket existingAuthTicket, int? developerAccountId = null, string responseFields = null,
		 HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Platform.Developer.DeveloperAdminUserAuthTicketClient.RefreshDeveloperAuthTicketClient(
				 existingAuthTicket :  existingAuthTicket,  developerAccountId :  developerAccountId,  responseFields :  responseFields		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

		/// <summary>
		///
		/// <example>
		///  <code>
		/// var result = DeveloperAdminUserAuthTicketFactory.DeleteUserAuthTicket(handler : handler,  refreshToken :  refreshToken,  expectedCode: expectedCode, successCode: successCode);
		/// var optionalCasting = ConvertClass<Stream/>(result);
		/// return optionalCasting;
		///  </code>
		/// </example>
		/// </summary>
		public static System.IO.Stream DeleteUserAuthTicket(ServiceClientMessageHandler handler,
 		 string refreshToken,
		 HttpStatusCode expectedCode = HttpStatusCode.OK, HttpStatusCode successCode = HttpStatusCode.OK)
		{
			SetSdKparameters();
			var currentClassName = System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType.Name;
			var currentMethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
			Debug.WriteLine(currentMethodName  + '.' + currentMethodName );
			var apiClient = Mozu.Api.Clients.Platform.Developer.DeveloperAdminUserAuthTicketClient.DeleteUserAuthTicketClient(
				 refreshToken :  refreshToken		);
			try
			{
				apiClient.WithContext(handler.ApiContext).ExecuteAsync(default(CancellationToken)).Wait();
			}
			catch (ApiException ex)
			{
				// Custom error handling for test cases can be placed here
				Exception customException = TestFailException.GetCustomTestException(ex, currentClassName, currentMethodName, expectedCode);
				if (customException != null)
					throw customException;
				return null;
			}
			return ResponseMessageFactory.CheckResponseCodes(apiClient.HttpResponse.StatusCode, expectedCode, successCode)
					 ? (apiClient.Result())
					 : null;

		}

	}

}

redpajama_set_name: RedPajamaGithub


text: To generate hompage of Yunjeong Lee


text:
import json

from wechatpy.client.api.base import BaseWeChatAPI

class WeChatMaterial(BaseWeChatAPI):
    def add(self, media_type, media_file, title=None, introduction=None):
        """
        新增其它类型永久素材
        详情请参考
        https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Adding_Permanent_Assets.html

        :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb)
        :param media_file: 要上传的文件,一个 File-object
        :param title: 视频素材标题,仅上传视频素材时需要
        :param introduction: 视频素材简介,仅上传视频素材时需要
        :return: 返回的 JSON 数据包
        """
        params = {"access_token": self.access_token, "type": media_type}
        if media_type == "video":
            assert title, "Video title must be set"
            assert introduction, "Video introduction must be set"
            description = {"title": title, "introduction": introduction}
            params["description"] = json.dumps(description)
        return self._post("material/add_material", params=params, files={"media": media_file})

    def get(self, media_id):
        """
        获取永久素材
        详情请参考
        https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Getting_Permanent_Assets.html

        :param media_id: 素材的 media_id
        :return: 图文素材返回图文列表,其它类型为素材的内容
        """

        def _processor(res):
            if isinstance(res, dict) and "news_item" in res:
                # 图文素材
                return res["news_item"]
            return res

        return self._post("material/get_material", data={"media_id": media_id}, result_processor=_processor)

    def delete(self, media_id):
        """
        删除永久素材
        详情请参考
        https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Deleting_Permanent_Assets.html

        :param media_id: 素材的 media_id
        :return: 返回的 JSON 数据包
        """
        return self._post("material/del_material", data={"media_id": media_id})

    def batchget(self, media_type, offset=0, count=20):
        """
        获取素材列表
        详情请参考
        https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_materials_list.html

        :param media_type: 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(news)
        :param offset: 从全部素材的该偏移位置开始返回,0 表示从第一个素材返回
        :param count: 返回素材的数量,取值在1到20之间
        :return: 返回的 JSON 数据包
        """
        return self._post("material/batchget_material", data={"type": media_type, "offset": offset, "count": count})

    def get_count(self):
        """
        获取素材总数
        详情请参考
        https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_the_total_of_all_materials.html

        :return: 返回的 JSON 数据包
        """
        return self._get("material/get_materialcount")

    def open_comment(self, msg_data_id, index=1):
        """
        打开已群发文章评论
        https://mp.weixin.qq.com/wiki?id=mp1494572718_WzHIY
        """
        return self._post("comment/open", data={"msg_data_id": msg_data_id, "index": index})

    def close_comment(self, msg_data_id, index=1):
        """
        关闭已群发文章评论
        """
        return self._post("comment/close", data={"msg_data_id": msg_data_id, "index": index})

    def list_comment(self, msg_data_id, index=1, begin=0, count=50, type=0):
        """
        查看指定文章的评论数据
        """
        return self._post(
            "comment/list",
            data={"msg_data_id": msg_data_id, "index": index, "begin": begin, "count": count, "type": type},
        )

    def markelect_comment(self, msg_data_id, index, user_comment_id):
        """
        将评论标记精选
        """
        return self._post(
            "comment/markelect",
            data={"msg_data_id": msg_data_id, "index": index, "user_comment_id": user_comment_id},
        )

    def unmarkelect_comment(self, msg_data_id, index, user_comment_id):
        """
        将评论取消精选
        """
        return self._post(
            "comment/unmarkelect",
            data={"msg_data_id": msg_data_id, "index": index, "user_comment_id": user_comment_id},
        )

    def delete_comment(self, msg_data_id, index, user_comment_id):
        """
        删除评论
        """
        return self._post(
            "comment/delete",
            data={"msg_data_id": msg_data_id, "index": index, "user_comment_id": user_comment_id},
        )

    def add_reply_comment(self, msg_data_id, index, user_comment_id, content):
        """
        回复评论
        """
        return self._post(
            "comment/reply/add",
            data={"msg_data_id": msg_data_id, "index": index, "user_comment_id": user_comment_id, "content": content},
        )

    def delete_reply_comment(self, msg_data_id, index, user_comment_id):
        """
        删除回复
        """
        return self._post(
            "comment/reply/delete",
            data={"msg_data_id": msg_data_id, "index": index, "user_comment_id": user_comment_id},
        )


text:
from ..models import Post, Category
from django import template

register = template.Library()

@register.simple_tag
def get_recent_posts(num=5):
	return Post.objects.all().order_by('-created_time')[:num]

@register.simple_tag
def archives():
	return Post.objects.dates('created_time', 'month', order='DESC')

@register.simple_tag
def get_categories():
	return Category.objects.all()


text:
using System;

namespace DAQ.Pattern.Test
{
	public class PatternBuilderTest
	{

		[STAThread]
		public static void Main()
		{
			SupersonicTestPattern p = new SupersonicTestPattern();
			Console.WriteLine("Building pattern ...");
			p.Clear();
			p.ShotSequence(0,100,100000,350,235,500,750,100,15000);
			p.BuildPattern(p.GetMinimumLength());
			Console.WriteLine("Done ...");
			Console.WriteLine("Pattern length is " + p.GetMinimumLength() + " long words.");
			Console.WriteLine(p.LayoutToString());
			Console.WriteLine(p.ArrayToString());
		}

	}
}


text:
package github.hellocsl.gallerylayoutmanager.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import github.hellocsl.gallerylayoutmanager.BuildConfig;

/**
 * Created by chensuilun on 16-8-9.
 */
public abstract class BaseRestoreFragment extends Fragment {
    public static final String IS_SHOW = "is_show";
    protected View mRootView;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (BuildConfig.DEBUG) {
            Log.d(getClass().getSimpleName(), "onCreate:");
        }
        if (savedInstanceState != null && getFragmentManager() != null) {
            boolean isShow = savedInstanceState.getBoolean(IS_SHOW, true);
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (BuildConfig.DEBUG) {
                Log.d(this.getClass().getSimpleName(), "restore show:" + isShow);
            }
            if (!isShow) {
                ft.hide(this);
            } else {
                ft.show(this);
            }
            ft.commit();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(IS_SHOW, !isHidden());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (BuildConfig.DEBUG) {
            Log.d(getClass().getSimpleName(), "onCreateView:");
        }
        mRootView = onCreateContentView(inflater, container, savedInstanceState);
        return mRootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (BuildConfig.DEBUG) {
            Log.v(getClass().getSimpleName(), "onViewCreated: ");
        }
        initView(view, savedInstanceState);
        initData(savedInstanceState);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (BuildConfig.DEBUG) {
            Log.d(getClass().getSimpleName(), "onStop: ");
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (BuildConfig.DEBUG) {
            Log.d(getClass().getSimpleName(), "onDestroyView ");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (BuildConfig.DEBUG) {
            Log.d(getClass().getSimpleName(), "onDestroy: ");
        }
    }

    protected abstract View onCreateContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    protected abstract void initView(View root, Bundle savedInstanceState);

    protected abstract void initData(Bundle savedInstanceState);

}


text:
<?php

namespace Terminal42\FacebookAlbumsBundle;

use Contao\Files;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Facebook;
use Facebook\GraphNodes\GraphAlbum;

/**
 * Class FacebookAlbum
 *
 * Provide methods to handle Facebook albums.
 */
class FacebookAlbum
{

    /**
     * Account model
     * @var AccountModel
     */
    protected $accountModel;

    /**
     * Album ID
     * @var string
     */
    protected $albumId;

    /**
     * Facebook instance
     * @var Facebook
     */
    protected $facebook;

    /**
     * Meta file name
     * @var string
     */
    protected $metaFileName = 'facebook_meta';

    /**
     * Initialize the object
     *
     * @param AccountModel $accountModel
     */
    public function __construct(AccountModel $accountModel)
    {
        $this->accountModel = $accountModel;
    }

    /**
     * Get the account model
     *
     * @return AccountModel
     */
    public function getAccountModel()
    {
        return $this->accountModel;
    }

    /**
     * Set the account model
     *
     * @param AccountModel $accountModel
     */
    public function setAccountModel(AccountModel $accountModel)
    {
        $this->accountModel = $accountModel;
    }

    /**
     * Get album ID
     *
     * @return string
     */
    public function getAlbumId()
    {
        return $this->albumId;
    }

    /**
     * Set album ID
     *
     * @param string $albumId
     */
    public function setAlbumId($albumId)
    {
        $this->albumId = $albumId;
    }

    /**
     * Connect to the Facebook
     *
     * @return bool
     */
    public function connect()
    {
        try {
            $this->facebook = new Facebook(
                [
                    'app_id'                => $this->accountModel->appId,
                    'app_secret'            => $this->accountModel->appSecret,
                    'default_graph_version' => 'v5.0'
                ]
            );
        } catch (FacebookSDKException $e) {
            \System::log('Facebook SDK exception: ' . $e->getMessage(), __METHOD__, TL_ERROR);

            $this->facebook = null;
        }

        return $this->facebook !== null;
    }

    /**
     * Return true if the album is outdated and should be fetched again
     *
     * @return bool
     */
    public function isOutdated()
    {
        $album = $this->getAlbum();

        if ($album === null) {
            return false;
        }

        $metaFile = $this->getMetaFile();

        // There is no meta file yet
        if ($metaFile === null) {
            return true;
        }

        $data = json_decode($metaFile->getContent(), true);

        if ($data === null) {
            return true;
        }

        return $album->getUpdatedTime()->getTimestamp() > $data['date_updated'];
    }

    /**
     * Return true if the album is new and must be fetched
     *
     * @return bool
     */
    public function isNew()
    {
        $folder = $this->getAlbumFolder();

        if ($folder === null) {
            return false;
        }

        return !is_file(TL_ROOT . '/' . $folder->path . '/' . $this->metaFileName . '.json');
    }

    /**
     * Get the root folder
     *
     * @return \Folder|null
     */
    public function getRootFolder()
    {
        $folderModel = $this->accountModel->getFolder();

        if ($folderModel === null) {
            return null;
        }

        return new \Folder($folderModel->path);
    }

    /**
     * Get the album folder
     *
     * @return \Folder|null
     */
    public function getAlbumFolder()
    {
        $rootFolder = $this->getRootFolder();

        if ($rootFolder === null) {
            return null;
        }

        return new \Folder($rootFolder->path . '/' . $this->albumId);
    }

    /**
     * Get the meta file
     *
     * @return \File|null
     *
     * @throws \Exception
     */
    public function getMetaFile()
    {
        $folder = $this->getAlbumFolder();

        if ($folder === null) {
            return null;
        }

        $path = $folder->path . '/' . $this->metaFileName . '.json';

        // Create the file if it does not exist
        if (!is_file(TL_ROOT . '/' . $path)) {
            Files::getInstance()->fopen($path, 'wb');
        }

        $file = new \File($path);

        // Synchronize the file with database
        if ($file->getModel() === null) {
            \Dbafs::addResource($file->path);
        }

        return $file;
    }

    /**
     * Update the meta file
     *
     * @param array $photos
     */
    protected function updateMetaFile(array $photos)
    {
        $file = $this->getMetaFile();

        if ($file === null) {
            return;
        }

        $album = $this->getAlbum();

        if ($album === null) {
            return;
        }

        $dateCreated = $album->getCreatedTime();
        $dateUpdated = $album->getUpdatedTime();

        $data = [
            'id'           => $album->getId(),
            'link'         => $album->getLink(),
            'count'        => $album->getCount(),
            'date_created' => $dateCreated ? $dateCreated->getTimestamp() : 0,
            'date_updated' => $dateUpdated ? $dateUpdated->getTimestamp() : 0,
            'files'        => [],
        ];

        foreach ($photos as $photo) {
            $dateCreated = new \DateTime($photo['created_time']);
            $dateUpdated = new \DateTime($photo['updated_time']);
            $source      = parse_url($photo['source']);

            $data['files'][] = [
                'id'           => $photo['id'],
                'name'         => basename($source['path']),
                'date_created' => $dateCreated ? $dateCreated->getTimestamp() : 0,
                'date_updated' => $dateUpdated ? $dateUpdated->getTimestamp() : 0,
            ];
        }

        $file->truncate();
        $file->write(json_encode($data, JSON_PRETTY_PRINT));
        $file->close();
    }

    /**
     * Fetch the album images and save them into the folder
     */
    public function fetchImages()
    {
        $folder = $this->getAlbumFolder();

        if ($folder === null) {
            return;
        }

        $photos = $this->getPhotos();

        if (empty($photos)) {
            return;
        }

        foreach ($photos as $photo) {
            $request = new \Request();
            $request->send($photo['source']);

            if ($request->hasError()) {
                continue;
            }

            $source = parse_url($photo['source']);

            $file = new \File($folder->path . '/' . basename($source['path']));
            $file->write($request->response);
            $file->close();
        }

        $this->updateMetaFile($photos);
    }

    /**
     * Get the albums
     *
     * @param int $limit
     *
     * @return array
     */
    public function getAlbums($limit = 1000)
    {
        $response = $this->request(sprintf('/%s/albums?limit=%s', $this->accountModel->pageId, $limit));

        if ($response === null) {
            return [];
        }

        $albums = [];

        foreach ($response->getGraphEdge() as $album) {
            $albums[] = $album->uncastItems();
        }

        // Sort the albums alphabetically
        usort($albums, function ($a, $b) {
            $i = strnatcasecmp($a['name'], $b['name']);

            if ($i === 0) {
                return 0;
            }

            return ($i > 0) ? 1 : -1;
        });

        return $albums;
    }

    /**
     * Get the album
     *
     * @return GraphAlbum|null
     */
    public function getAlbum()
    {
        $response = $this->request(sprintf('/%s?fields=count,created_time,link,updated_time', $this->albumId));

        if ($response === null) {
            return null;
        }

        return $response->getGraphAlbum();
    }

    /**
     * Get the photos of particular album
     *
     * @return array
     */
    public function getPhotos()
    {
        $response = $this->request(sprintf('/%s/photos?fields=id,source,created_time,updated_time', $this->albumId));

        if ($response === null) {
            return [];
        }

        $photos = [];

        foreach ($response->getGraphEdge() as $photo) {
            $photos[] = $photo->uncastItems();
        }

        return $photos;
    }

    /**
     * Perform a Facebook request
     *
     * @param string $action
     *
     * @return \Facebook\FacebookResponse|null
     */
    protected function request($action)
    {
        if ($this->facebook === null) {
            return null;
        }

        try {
            $response = $this->facebook->get($action, $this->accountModel->accessToken ?: $this->facebook->getApp()->getAccessToken());
        } catch (FacebookResponseException $e) {
            \System::log('Facebook response exception: ' . $e->getMessage(), __METHOD__, TL_ERROR);

            return null;
        } catch (FacebookSDKException $e) {
            \System::log('Facebook SDK exception: ' . $e->getMessage(), __METHOD__, TL_ERROR);

            return null;
        }

        return $response;
    }

    /**
     * Get the file models
     *
     * @return \Model\Collection|null
     */
    public function getFileModels()
    {
        $albumFolder = $this->getAlbumFolder();

        if ($albumFolder === null) {
            return null;
        }

        return \FilesModel::findByPid($albumFolder->getModel()->uuid);
    }

    /**
     * Get the images
     *
     * @param string $sorting
     * @param string $metaLanguage
     * @param bool   $metaIgnore
     * @param string $metaFallbackLanguage
     *
     * @return array
     */
    public function getImages($sorting, $metaLanguage, $metaIgnore = false, $metaFallbackLanguage = null)
    {
        $files = $this->getFileModels();

        if ($files === null) {
            return [];
        }

        $images = [];

        while ($files->next()) {
            // Skip subfolders
            if ($files->type == 'folder') {
                continue;
            }

            $file = new \File($files->path, true);

            if (!$file->isImage) {
                continue;
            }

            $meta = \Frontend::getMetaData($files->meta, $metaLanguage);

            if (empty($meta)) {
                if ($metaIgnore) {
                    continue;
                } elseif ($metaFallbackLanguage !== null) {
                    $meta = \Frontend::getMetaData($files->meta, $metaFallbackLanguage);
                }
            }

            // Use the file name as title if none is given
            if (($meta['title'] ?? null) == '') {
                $meta['title'] = specialchars($file->basename);
            }

            // Add the image
            $images[$files->path] = [
                'id'        => $files->id,
                'uuid'      => $files->uuid,
                'name'      => $file->basename,
                'singleSRC' => $files->path,
                'alt'       => $meta['title'] ?? null,
                'imageUrl'  => $meta['link'] ?? null,
                'caption'   => $meta['caption'] ?? null
            ];
        }

        return $this->sortImages($images, $this->getMetaData(), $sorting);
    }

    /**
     * Get the meta data
     *
     * @return array
     */
    public function getMetaData()
    {
        $file = $this->getMetaFile();

        if ($file === null) {
            return [];
        }

        $data = json_decode($file->getContent(), true);

        if ($data === null) {
            return [];
        }

        return $data;
    }

    /**
     * Sort the images
     *
     * @param array  $images
     * @param array  $metaData
     * @param string $sorting
     *
     * @return array
     */
    protected function sortImages(array $images, array $metaData, $sorting)
    {
        switch ($sorting) {
            default:
            case 'facebook':
                $order = [];

                // Order the images
                foreach (($metaData['files'] ?? []) as $meta) {
                    foreach ($images as $path => $image) {
                        if ($meta['name'] == $image['name']) {
                            $order[] = $image;
                            unset($images[$path]);
                        }
                    }
                }

                // Append the rest of images
                if (!empty($images)) {
                    $order = array_merge($order, $images);
                }

                // Revert the variable
                $images = $order;
                break;

            case 'date_asc':
            case 'date_desc':
                $orderHelper = [];

                // Prepare the order array
                foreach (($metaData['files'] ?? []) as $meta) {
                    $orderHelper[$meta['name']] = $meta['date_updated'];
                }

                asort($orderHelper, SORT_NUMERIC);

                // Sort descending
                if (($sorting == 'date_desc')) {
                    $orderHelper = array_reverse($orderHelper, true);
                }

                $order = [];

                // Order images
                foreach (array_keys($orderHelper) as $orderImage) {
                    foreach ($images as $path => $image) {
                        if ($orderImage == $image['name']) {
                            $order[] = $image;
                            unset($images[$path]);
                        }
                    }
                }

                // Append the rest of images
                if (!empty($images)) {
                    $order = array_merge($order, $images);
                }

                // Revert the variable
                $images = $order;
                break;

            case 'random':
                shuffle($images);
                break;
        }

        return $images;
    }
}


text:
import {RouteInfo, HttpRequest} from "kamboja-core"
import {BinderBase} from "./binder-base"
import {convert} from "./value-converter"

export class DefaultBinder extends  BinderBase{
    bind(routeInfo:RouteInfo, parameterName:string, request:HttpRequest){
        return this.exit(convert(routeInfo, parameterName, request.getParam(parameterName)))
    }
}


text:
<!DOCTYPE html>

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

    <title>Philip Dixon</title>

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

    <link href="css/landing-page.css" rel="stylesheet">

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

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Philip Dixon

                        About

                        Contact

Philip Dixon

An Online Portfolio

                                 Twitter

                                 Medium

                                 Instagram

                                 Linkedin

Teaching

Teacher for 4 years, currently working as Head of Physics at a Secondary School in Yorkshire.
Dedicated to improving the use of technology within education.
Details of my current and previous roles and resposibilities can be found on LinkedIn.

                      Linkedin

EduTech

New to Education blogging, but not blogging itself. I'm currently working on releasing reviews, previews and recommendations of ways schools and similar education establishments can move forward with the ever changing world of technology.

                     Medium

Connect via social media:

                                 Twitter

                                 Medium

                                 Instagram

                            Home

⋅

                            About

⋅

                            Contact

Copyright © Philip Dixon 2016. All Rights Reserved


text:
import json

from tests.support.asserts import assert_success
from . import execute_script

_window_id = "window-fcc6-11e5-b4f8-330a88ab9d7f"
_frame_id = "frame-075b-4da1-b6ba-e579c2d3230a"

def test_initial_window(session):
    # non-auxiliary top-level browsing context
    response = execute_script(session, "return window;")
    raw_json = assert_success(response)

    obj = json.loads(raw_json)
    assert len(obj) == 1
    assert _window_id in obj
    handle = obj[_window_id]
    assert handle in session.window_handles

def test_window_open(session):
    # auxiliary browsing context
    session.execute_script("window.foo = window.open()")

    response = execute_script(session, "return window.foo;")
    raw_json = assert_success(response)

    obj = json.loads(raw_json)
    assert len(obj) == 1
    assert _window_id in obj
    handle = obj[_window_id]
    assert handle in session.window_handles

def test_frame(session):
    # nested browsing context
    append = """
        window.frame = document.createElement('iframe');
        document.body.appendChild(frame);
    """
    session.execute_script(append)

    response = execute_script(session, "return frame.contentWindow;")
    raw_json = assert_success(response)

    obj = json.loads(raw_json)
    assert len(obj) == 1
    assert _frame_id in obj
    handle = obj[_frame_id]
    assert handle not in session.window_handles


text:
package main

import (
	"github.com/ctdk/goiardi/actor"
	"github.com/ctdk/goiardi/gerror"
	"github.com/ctdk/goiardi/util"
	"github.com/tideland/golib/logger"
	"net/http"
)

// Functions and types for HEAD responses for various endpoints
//
// Implements Chef RFC090 -
// (https://github.com/chef/chef-rfc/blob/master/rfc090-server-http-head.md)
//
// From the RFC:
//
// Code 	Reason
// ---- 	------
// 200 		object exists
// 401 		request signature is invalid
// 403 		requestor does not have READ on the object
// 404 		object does not exist
//
// Obviously, the 403 bit will be a little bit different for goiardi 0.x.y vs.
// the 1.0.0 branch because of the different permissions scheme.
//
// HEAD should be present everywhere GET is, even if the HEAD request isn't
// particularly meaningful.

type headChecker interface {
	actor.Actor
	DoesExist(string) (bool, util.Gerror)
}

type exists func(resource string) (bool, util.Gerror)

type permChecker func(r *http.Request, resource string, obj actor.Actor) util.Gerror

// for when no perm check is actually necessary
func nilPermCheck(r *http.Request, resource string, obj actor.Actor) util.Gerror {
	return nil
}

func headResponse(w http.ResponseWriter, r *http.Request, status int) {
	logger.Debugf("HEAD response status %d for %s", status, r.URL.Path)
	w.WriteHeader(status)
	return
}

func headDefaultResponse(w http.ResponseWriter, r *http.Request) {
	logger.Debugf("HEAD default response issued for %s", r.URL.Path)
	w.WriteHeader(http.StatusOK)
}

func headChecking(w http.ResponseWriter, r *http.Request, obj actor.Actor, resource string, doesExist exists, permCheck permChecker) {
	found, err := doesExist(resource)
	if err != nil {
		headResponse(w, r, err.Status())
	}
	err = permCheck(r, resource, obj)
	if err != nil {
		headResponse(w, r, err.Status())
	}
	if !found {
		headResponse(w, r, http.StatusNotFound)
	}
	headResponse(w, r, http.StatusOK)
}

func headForbidden() util.Gerror {
	err := gerror.StatusError("forbidden", http.StatusForbidden)
	return err
}


text:
using System;
using Microsoft.EntityFrameworkCore.Migrations;

namespace Money.EntityFrameworkCore.Migrations
{
    public partial class Initial : MigrationWithSchema<EventSourcingContext>
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            if (Schema.Name != null)
                migrationBuilder.EnsureSchema(Schema.Name);

            migrationBuilder.CreateTable(
                name: "Command",
                schema: Schema.Name,
                columns: table => new
                {
                    ID = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    CommandID = table.Column<Guid>(nullable: false),
                    CommandType = table.Column<string>(nullable: true),
                    Payload = table.Column<string>(nullable: true),
                    RaisedAt = table.Column<DateTime>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Command", x => x.ID);
                });

            migrationBuilder.CreateTable(
                name: "Event",
                schema: Schema.Name,
                columns: table => new
                {
                    ID = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    EventID = table.Column<Guid>(nullable: false),
                    EventType = table.Column<string>(nullable: true),
                    AggregateID = table.Column<Guid>(nullable: false),
                    AggregateType = table.Column<string>(nullable: true),
                    Payload = table.Column<string>(nullable: true),
                    Version = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Event", x => x.ID);
                });

            migrationBuilder.CreateTable(
                name: "UnPublishedCommand",
                schema: Schema.Name,
                columns: table => new
                {
                    ID = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    CommandID = table.Column<int>(nullable: false),
                    IsHandled = table.Column<bool>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UnPublishedCommand", x => x.ID);
                    table.ForeignKey(
                        name: "FK_UnPublishedCommand_Command_CommandID",
                        column: x => x.CommandID,
                        principalSchema: Schema.Name,
                        principalTable: "Command",
                        principalColumn: "ID",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "UnPublishedEvent",
                schema: Schema.Name,
                columns: table => new
                {
                    ID = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    EventID = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UnPublishedEvent", x => x.ID);
                    table.ForeignKey(
                        name: "FK_UnPublishedEvent_Event_EventID",
                        column: x => x.EventID,
                        principalSchema: Schema.Name,
                        principalTable: "Event",
                        principalColumn: "ID",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateTable(
                name: "EventPublishedToHandler",
                schema: Schema.Name,
                columns: table => new
                {
                    ID = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    EventID = table.Column<int>(nullable: false),
                    HandlerIdentifier = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_EventPublishedToHandler", x => x.ID);
                    table.ForeignKey(
                        name: "FK_EventPublishedToHandler_UnPublishedEvent_EventID",
                        column: x => x.EventID,
                        principalSchema: Schema.Name,
                        principalTable: "UnPublishedEvent",
                        principalColumn: "ID",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_EventPublishedToHandler_EventID",
                schema: Schema.Name,
                table: "EventPublishedToHandler",
                column: "EventID");

            migrationBuilder.CreateIndex(
                name: "IX_UnPublishedCommand_CommandID",
                schema: Schema.Name,
                table: "UnPublishedCommand",
                column: "CommandID");

            migrationBuilder.CreateIndex(
                name: "IX_UnPublishedEvent_EventID",
                schema: Schema.Name,
                table: "UnPublishedEvent",
                column: "EventID");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "EventPublishedToHandler",
                schema: Schema.Name);

            migrationBuilder.DropTable(
                name: "UnPublishedCommand",
                schema: Schema.Name);

            migrationBuilder.DropTable(
                name: "UnPublishedEvent",
                schema: Schema.Name);

            migrationBuilder.DropTable(
                name: "Command",
                schema: Schema.Name);

            migrationBuilder.DropTable(
                name: "Event",
                schema: Schema.Name);
        }
    }
}


text:
<?php

defined('_JEXEC') or die;

// Include the syndicate functions only once
require_once __DIR__ . '/helper.php';

$isMobile = 0;

if ( class_exists('MobileDetector') ) {
	$isMobile = MobileDetector::isMobile();
}

$cacheparams = new stdClass;
$cacheparams->cachemode = 'id';
$cacheparams->class = 'ModAkvideosvideosHelper';
$cacheparams->method = 'getList';
$cacheparams->methodparams = $params;

$cacheid = md5(serialize(array ($module->module, $module->id)));

$cacheparams->modeparams = $cacheid;

$videos = JModuleHelper::moduleCache($module, $params, $cacheparams);

if (!count($videos))
{
	error_log(" ModAkvideosvideos NO RECIPES. returning");
	return;
}

if ( $isMobile && $params->get('mobile_layout', 'default') === 'default') {
	require JModuleHelper::getLayoutPath('mod_akvideos_videos', $params->get('layout', 'default'));
} elseif ( $isMobile && $params->get('mobile_layout', 'default') != 'default') {
	 require JModuleHelper::getLayoutPath('mod_akvideos_videos', $params->get('mobile_layout', 'default'));
} else {
	require JModuleHelper::getLayoutPath('mod_akvideos_videos', $params->get('layout', 'default'));
}


text:
namespace webrtc {
namespace test {

extern const int kAudioLevelExtensionId;
extern const int kTOffsetExtensionId;
extern const int kAbsSendTimeExtensionId;
extern const int kTransportSequenceNumberExtensionId;
extern const int kVideoRotationExtensionId;
extern const int kVideoContentTypeExtensionId;
extern const int kVideoTimingExtensionId;
}  // namespace test
}  // namespace webrtc


text:
from __future__ import division

import numpy as np
import pytest

import pandas.util.testing as tm
from pandas import compat
from pandas._libs.interval import IntervalTree

def skipif_32bit(param):
    """
    Skip parameters in a parametrize on 32bit systems. Specifically used
    here to skip leaf_size parameters related to GH 23440.
    """
    marks = pytest.mark.skipif(compat.is_platform_32bit(),
                               reason='GH 23440: int type mismatch on 32bit')
    return pytest.param(param, marks=marks)

@pytest.fixture(
    scope='class', params=['int32', 'int64', 'float32', 'float64', 'uint64'])
def dtype(request):
    return request.param

@pytest.fixture(params=[skipif_32bit(1), skipif_32bit(2), 10])
def leaf_size(request):
    """
    Fixture to specify IntervalTree leaf_size parameter; to be used with the
    tree fixture.
    """
    return request.param

@pytest.fixture(params=[
    np.arange(5, dtype='int64'),
    np.arange(5, dtype='int32'),
    np.arange(5, dtype='uint64'),
    np.arange(5, dtype='float64'),
    np.arange(5, dtype='float32'),
    np.array([0, 1, 2, 3, 4, np.nan], dtype='float64'),
    np.array([0, 1, 2, 3, 4, np.nan], dtype='float32')])
def tree(request, leaf_size):
    left = request.param
    return IntervalTree(left, left + 2, leaf_size=leaf_size)

class TestIntervalTree(object):

    def test_get_loc(self, tree):
        tm.assert_numpy_array_equal(tree.get_loc(1),
                                    np.array([0], dtype='int64'))
        tm.assert_numpy_array_equal(np.sort(tree.get_loc(2)),
                                    np.array([0, 1], dtype='int64'))
        with pytest.raises(KeyError):
            tree.get_loc(-1)

    def test_get_indexer(self, tree):
        tm.assert_numpy_array_equal(
            tree.get_indexer(np.array([1.0, 5.5, 6.5])),
            np.array([0, 4, -1], dtype='int64'))
        with pytest.raises(KeyError):
            tree.get_indexer(np.array([3.0]))

    def test_get_indexer_non_unique(self, tree):
        indexer, missing = tree.get_indexer_non_unique(
            np.array([1.0, 2.0, 6.5]))
        tm.assert_numpy_array_equal(indexer[:1],
                                    np.array([0], dtype='int64'))
        tm.assert_numpy_array_equal(np.sort(indexer[1:3]),
                                    np.array([0, 1], dtype='int64'))
        tm.assert_numpy_array_equal(np.sort(indexer[3:]),
                                    np.array([-1], dtype='int64'))
        tm.assert_numpy_array_equal(missing, np.array([2], dtype='int64'))

    def test_duplicates(self, dtype):
        left = np.array([0, 0, 0], dtype=dtype)
        tree = IntervalTree(left, left + 1)
        tm.assert_numpy_array_equal(np.sort(tree.get_loc(0.5)),
                                    np.array([0, 1, 2], dtype='int64'))

        with pytest.raises(KeyError):
            tree.get_indexer(np.array([0.5]))

        indexer, missing = tree.get_indexer_non_unique(np.array([0.5]))
        tm.assert_numpy_array_equal(np.sort(indexer),
                                    np.array([0, 1, 2], dtype='int64'))
        tm.assert_numpy_array_equal(missing, np.array([], dtype='int64'))

    def test_get_loc_closed(self, closed):
        tree = IntervalTree([0], [1], closed=closed)
        for p, errors in [(0, tree.open_left),
                          (1, tree.open_right)]:
            if errors:
                with pytest.raises(KeyError):
                    tree.get_loc(p)
            else:
                tm.assert_numpy_array_equal(tree.get_loc(p),
                                            np.array([0], dtype='int64'))

    @pytest.mark.parametrize('leaf_size', [
        skipif_32bit(1), skipif_32bit(10), skipif_32bit(100), 10000])
    def test_get_indexer_closed(self, closed, leaf_size):
        x = np.arange(1000, dtype='float64')
        found = x.astype('intp')
        not_found = (-1 * np.ones(1000)).astype('intp')

        tree = IntervalTree(x, x + 0.5, closed=closed, leaf_size=leaf_size)
        tm.assert_numpy_array_equal(found, tree.get_indexer(x + 0.25))

        expected = found if tree.closed_left else not_found
        tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.0))

        expected = found if tree.closed_right else not_found
        tm.assert_numpy_array_equal(expected, tree.get_indexer(x + 0.5))


text:
<?php

final class BulkSelectParameterType
  extends BulkParameterType {

  private $options;

  public function setOptions(array $options) {
    $this->options = $options;
    return $this;
  }

  public function getOptions() {
    return $this->options;
  }

  public function getPHUIXControlType() {
    return 'select';
  }

  public function getPHUIXControlSpecification() {
    return array(
      'options' => $this->getOptions(),
      'order' => array_keys($this->getOptions()),
      'value' => null,
    );
  }

}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Thanks, Jimmy — The Epitome of Randomness</title>
    <link href="https://fonts.googleapis.com/css?family=Droid+Sans:400,700" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="/blog/assets/main.css">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
    <link rel="apple-touch-icon" href="/images/logo.png"/>
    <link href="/feed.xml" rel="alternate" type="application/rss+xml" title="The Epitome of Randomness" />
    <meta name="title" content="Thanks, Jimmy ">
    <link rel="canonical" href="http://danmanez.com/blog/2013/09/26/thanks-jimmy/">

    <link rel="author" href="https://plus.google.com/117745877807025725307">
    <meta property="og:title" content="Thanks, Jimmy "/>
    <meta property="og:url" content="http://danmanez.com/blog/2013/09/26/thanks-jimmy/"/>

    <meta property="og:description" content="I really had nothing to lose. I held my ground and waited for him."/>
    <meta name="description" content="I really had nothing to lose. I held my ground and waited for him."/>

    <meta property="og:site_name" content="The Epitome of Randomness">

            Blog
            Portfolio
            About

            I develop things.
            Learn More

                By <address>Dan Manez</address> —
                <time pubdate datetime="2013-26-September" title="September 26, 2013">September 26, 2013</time>

Thanks, Jimmy

Adrenaline is one hell of a drug.

Storytime. I spent my day around Malibu after an interview I had in the area. I found a hiking trail I wanted to check out and explored it for a bit and then hung out at the beach for a while to relax and clear my head. Trying to get back into drawing (I can hardly draw a straight line now and that disappoints me tremendously), I wandered around the beach sketching random things.

I came across a group of people playing beach volleyball, and I decided to hang around and watch / sketch the court and players. They finished their game and I stuck around to just draw the empty court.

One of the girls playing approached me and just wanted to check out what I was doing. We initiated some small talk and turns out she was a graphic designer.

It was nice.

Being involved in the web development world for the good part of the year, I haven't talked to anyone who designs for a living in a while. Wanting to pick her brain (not to mention she was cute), I asked her for tips and tricks, and she was happy to talk to me about it.

"I have nobody to talk to about this stuff other than my co-workers." She said excitedly. "I'm happy to talk to you about anything!"

"Hey! Is this [multiple expletives] bothering you?"

One of the guys (the biggest and buffest one) approached us yelling.

"No, sweetie. I'm the one who went over here to see what he was doing. Look! He drew our game!" The female replied. (I assume this was her boyfriend?)

He looked really angry for some reason. Worked up- He was turning red. "So this perv has been checking you out and drawing you? What the [expletive]?"

I felt the need to butt in, so I stood up and reached my hand out.

"Hi, I'm Dan."

"I was just drawing random things around the beach and I saw you guys playing." I tried to smile, but to tell the truth, I was terrified. He looked like he was going to punch my face in.

He ignored me.

"Whatever. Let's get out of here." He held out his hand to help his girlfriend up.

"Sorry. I gotta go. It was nice meeting you!" She said to me as she got up.

He seemed to get angrier at that point. "Don't talk to this [expletive]!"

As they walked away I could hear them yelling at each other. She tried to explain herself.

"He's just here drawing. I wanted to check out what he was doing. Calm down, Jimmy."

Nope. He really wasn't having any of it.

"Yeah, okay. You find the first good-looking guy you have something in common with, and you ignore me? What the hell is wrong with you?"

I smiled to myself.

Now my confidence in myself has been at an all-time low for quite some time. I'm just starting to try getting into shape because well, I don't want to be disgusting. And since I just started, I'm not in any shape. Well, I guess round is a shape.

Good-looking, Jimmy? Thanks.

They both stood there yelling at each other, but they were far enough that I couldn't hear them over the sound of the ambiance. I decided to just pack up and leave.

Now I probably shouldn't have done what comes next, but I couldn't help it. Because of Jimmy, I was on an inflated ego high.

I waved goodbye to her.

Even from how far she was, I saw that she couldn't help but smile and wave back. She had a beautiful smile. I'm not going to lie. It was totally a smile you could fall for. I just walked away. I thought I was clear of all the drama.

"Jimmy! Stop! Hey Dan!"

She remembered my name! I was probably more surprised that she remembered my name than what followed. I turned around just in time to see the boyfriend rushing at me. I'm not sure exactly what happened next because of the adrenaline rush, but this is what I remember:

I felt like a matador.

I sidestepped him as he charged me. I tried to calm him down and told him he really had no reason to lose his temper over me. Was he really threatened by me? His girlfriend was at the "sideline" yelling at him to stop while I saw his other friends running to help out. To stop this madness, I hope. Not to help him beat me into the ground.

Now I'm not sure if I just have amazing reflexes or if he was just that slow, but I ducked a couple of his swings. He did manage to grab my bag with my drawing stuff, phone and tablet in it though. He threw it off into the distance with everything flying out into some rocks.

His friends grabbed him and stopped him from tearing me apart. He did get a good shot at me. I only felt it afterwards though to be honest. Adrenaline is one hell of a drug. I walked away to get my stuff.

"Yeah, walk away like a little bitch!"

I was so sick of it. I turned around and just shook my head at him and told him to shut up and just let me go. Unfortunately, like any angry bull, he broke free from his friend and ran at me again. I'm not sure what prompted me to do this, maybe a deathwish. I really had nothing to lose. I held my ground and waited for him. Again, sidestepping his one and only predictable move, he missed me. But I surprised myself.

I swung back and hit him.

I'm no athlete, but I got his nose and mouth bleeding. He wiped his face, looked down at the blood on his hands, and walked away. I don't know what happened but I like to imagine a huge commotion behind me as I walked away for the third time, bruised ribs, still on an adrenaline high, and a hand that hurt like hell. Funny though. The first thing I thought of was, "Dang. Now how am I going to get back into drawing like this?" It actually hurts quite a bit typing, but I can't hold a pencil without a bit of shaking.

I lost a few pens, pencils and an eraser in the rocks. I found my phone, thankfully. But with a shattered screen and back cracked, I called my tablet dead. I wasn't in the mood to bitch about it, so I just picked up what I could find and walked back to my car. I looked down at the beach before getting in my car.

She looked up and we locked eyes for awhile.

Then she went back to tending to her boyfriend. Because of today, I gained quite a bit of confidence in myself. Was it right to do the things I did? Maybe. Maybe not. It felt good though. It took something like this to make me realize that if I just applied myself, I can be a threat. Today, it took some help from adrenaline, but I'm not limiting this learning experience to a physical confrontation.

I would never in my life think that I could stop a 6'something" and 200-something lb guy. But it happened. Even when I'm hardly in shape to do so. I doubt my luck will hold up next time if something like this ever happens to me again, but maybe I should start working out again just in case.

I feel good though and I'm sure this feeling will last for some time. I feel confident, my ego is going to burst, and I know that at least one person, albeit coming from a guy, finds me good-looking.

+100 experience

Dan leveled up!

+5 to CONFIDENCE, +1 to STRENGTH (through ADVERSITY), +10 to EGO (temporary buff), new passive skill: Adrenaline Rush.

Thanks, Jimmy. You've done more for me than you think.

            <address>

Written by Dan Manez

                Co-founder, Designer, Developer

            </address>

        © 2014

            danManez | Mechofor Solutions LLC ·
            Blog ·
            Portfolio ·
            About


text:
package com.gikk.twirk.types;

import java.util.HashMap;

class TagMapImpl extends HashMap<String, String> implements TagMap{
	//***********************************************************
	// 				CONSTRUCTOR
	//***********************************************************
	public TagMapImpl(String tag){
        super();
        if(tag.isEmpty()) {
            return;
        }
		//Substring the tag to remove the @ at the beginning
		String[] segments = tag.substring(1).split(";");

		int i = 0;
		String key, value;
		for(String s : segments){
			if( (i = s.indexOf('=')) != -1){
				key   = s.substring(0, i);
				value = mightBeEscaped(key)
						? replaceEscapes(s.substring(i+1))
						: s.substring(i+1);
				this.put( key, value );
			}
		}
	}

	//***********************************************************
	// 				PUBLIC
	//***********************************************************
	/**{@inheritDoc}
	 */
    @Override
	public String getAsString(String identifier){
		return this.getOrDefault(identifier, "");
	}

	/**{@inheritDoc}
	 */
    @Override
	public int getAsInt(String identifier) {
		try{
			return Integer.decode(this.getOrDefault(identifier, "-1"));
		} catch (NumberFormatException e){
			return -1;
		}
	}

    /**{@inheritDoc}
	 */
    @Override
    public long getAsLong(String identifier) {
       try{
			return Long.decode(this.getOrDefault(identifier, "-1"));
		} catch (NumberFormatException e){
			return -1;
		}
    }

	/**{@inheritDoc}
	 */
    @Override
	public boolean getAsBoolean(String identifier) {
		return this.getOrDefault(identifier, "0").equals("1");
	}

	//***********************************************************
	// 				PRIVATE
	//***********************************************************
	private boolean mightBeEscaped(String segment){
		return  segment.equals(TwitchTags.DISPLAY_NAME)  ||
				segment.equals(TwitchTags.BAN_REASON)    ||
				segment.equals(TwitchTags.SYSTEM_MESSAGE)||
                segment.equals(TwitchTags.PARAM_SUB_PLAN_NAME);
	}

	private String replaceEscapes(String segment){
		segment = segment.replace("\\s", " ");
		segment = segment.replace("\\:", ";");
		return segment;
	}
}


text:
<!DOCTYPE html>

    <title>A basic example of a Pie chart that uses the pseudo events</title>

    <meta name="robots" content="noindex,nofollow" />
    <meta name="description" content="A basic example of the Pie chart pseudo-events. It shows an example Pie chart and there is little happening on the page so the source is easy to navigate." />
    <meta name="googlebot" content="NOODP">

    <link rel="stylesheet" href="demos.css" type="text/css" media="screen" />

A basic example of a Pie chart that uses the pseudo events

    <canvas id="cvs" width="300" height="250">[No canvas support]</canvas>

        This is a basic example of the Line chart that shows you how to use the pseudo-events that RGraph has:

events.click

events.mousemove

        Here the mousemove event is used to change the mouse cursor (it's automatically changed back for you). And the click event
        is used to show an alert.

    This goes in the documents header (or you could place it just above the jQuery ready event code):

<script src="/mps/libs/jquery-1.11.3/jquery-1.11.3.js"></script>
<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.dynamic.js"></script>
<script src="RGraph.pie.js"></script>

    Put this where you want the chart to show up:

<canvas id="cvs" width="300" height="250">
    [No canvas support]
</canvas>

    This is the code that generates the chart. Because it's using the jQuery ready event you can put this at the
    bottom of the document:

<script>
    $(document).ready(function ()
    {
        /**
        * This is the function for the mousemove event. It changes the pointer to the hand.
        * When the mouse is moved away from the segment the pointer is changed back to what it was
        * automatically for you.
        *
        * @param object e       The event object
        * @param array  segment The details of the segment that was mouseover'ed
        */
        function myMousemove (e, segment)
        {
            e.target.style.cursor = 'pointer';
        }

        /**
        * This is the function for the click event.
        *
        * @param object e       The event object
        * @param array  segment The details of the segment that was clicked
        */
        function myClick (e, segment)
        {
            alert('A segment was clicked (with index: ' + segment[5] + ')');
        }

        var bar = new RGraph.Pie({
            id: 'cvs',
            data: [12,13,16,15,16],
            options: {
                eventsMousemove: myMousemove,
                eventsClick: myClick,
                labels: ['Charly','Lou','Pete','Jim','Fred']
            }
        }).draw();
    });
</script>


text:
module Keyper
  class ApiKey < ApplicationRecord
    self.table_name = :keyper_api_keys
    has_secure_password
    belongs_to :user,
      class_name: Keyper.user_class_name

    before_validation :generate_api_key_and_secret, on: :create
    validates :api_key, :user, presence: true

    def should_update_attributes?
      return last_used_at.nil? || last_used_at < Keyper.attribute_refresh_interval.ago
    end

    private

    def generate_api_key_and_secret
      self.api_key = loop do
        key = SecureRandom.hex(16)
        break key unless Keyper::ApiKey.exists?(api_key: key)
      end
      self.password = SecureRandom.hex(16)
    end
  end
end


text:
package com.android.server.job.controllers;

import android.app.job.JobInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.INetworkPolicyListener;
import android.net.NetworkInfo;
import android.net.NetworkPolicyManager;
import android.os.UserHandle;
import android.util.Slog;

import com.android.internal.annotations.GuardedBy;
import com.android.server.job.JobSchedulerService;
import com.android.server.job.StateChangedListener;

import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * Handles changes in connectivity.
 * <p>
 * Each app can have a different default networks or different connectivity
 * status due to user-requested network policies, so we need to check
 * constraints on a per-UID basis.
 */
public class ConnectivityController extends StateController implements
        ConnectivityManager.OnNetworkActiveListener {
    private static final String TAG = "JobScheduler.Conn";

    private final ConnectivityManager mConnManager;
    private final NetworkPolicyManager mNetPolicyManager;

    @GuardedBy("mLock")
    private final ArrayList<JobStatus> mTrackedJobs = new ArrayList<JobStatus>();

    /** Singleton. */
    private static ConnectivityController mSingleton;
    private static Object sCreationLock = new Object();

    public static ConnectivityController get(JobSchedulerService jms) {
        synchronized (sCreationLock) {
            if (mSingleton == null) {
                mSingleton = new ConnectivityController(jms, jms.getContext(), jms.getLock());
            }
            return mSingleton;
        }
    }

    private ConnectivityController(StateChangedListener stateChangedListener, Context context,
            Object lock) {
        super(stateChangedListener, context, lock);

        mConnManager = mContext.getSystemService(ConnectivityManager.class);
        mNetPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);

        final IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        mContext.registerReceiverAsUser(
                mConnectivityReceiver, UserHandle.SYSTEM, intentFilter, null, null);

        mNetPolicyManager.registerListener(mNetPolicyListener);
    }

    @Override
    public void maybeStartTrackingJobLocked(JobStatus jobStatus, JobStatus lastJob) {
        if (jobStatus.hasConnectivityConstraint() || jobStatus.hasUnmeteredConstraint()
                || jobStatus.hasNotRoamingConstraint()) {
            updateConstraintsSatisfied(jobStatus);
            mTrackedJobs.add(jobStatus);
        }
    }

    @Override
    public void maybeStopTrackingJobLocked(JobStatus jobStatus, JobStatus incomingJob,
            boolean forUpdate) {
        if (jobStatus.hasConnectivityConstraint() || jobStatus.hasUnmeteredConstraint()
                || jobStatus.hasNotRoamingConstraint()) {
            mTrackedJobs.remove(jobStatus);
        }
    }

    private boolean updateConstraintsSatisfied(JobStatus jobStatus) {
        final boolean ignoreBlocked = (jobStatus.getFlags() & JobInfo.FLAG_WILL_BE_FOREGROUND) != 0;
        final NetworkInfo info = mConnManager.getActiveNetworkInfoForUid(jobStatus.getSourceUid(),
                ignoreBlocked);
        final boolean connected = (info != null) && info.isConnected();
        final boolean unmetered = connected && !info.isMetered();
        final boolean notRoaming = connected && !info.isRoaming();

        boolean changed = false;
        changed |= jobStatus.setConnectivityConstraintSatisfied(connected);
        changed |= jobStatus.setUnmeteredConstraintSatisfied(unmetered);
        changed |= jobStatus.setNotRoamingConstraintSatisfied(notRoaming);
        return changed;
    }

    /**
     * Update all jobs tracked by this controller.
     *
     * @param uid only update jobs belonging to this UID, or {@code -1} to
     *            update all tracked jobs.
     */
    private void updateTrackedJobs(int uid) {
        synchronized (mLock) {
            boolean changed = false;
            for (int i = 0; i < mTrackedJobs.size(); i++) {
                final JobStatus js = mTrackedJobs.get(i);
                if (uid == -1 || uid == js.getSourceUid()) {
                    changed |= updateConstraintsSatisfied(js);
                }
            }
            if (changed) {
                mStateChangedListener.onControllerStateChanged();
            }
        }
    }

    /**
     * We know the network has just come up. We want to run any jobs that are ready.
     */
    @Override
    public synchronized void onNetworkActive() {
        synchronized (mLock) {
            for (int i = 0; i < mTrackedJobs.size(); i++) {
                final JobStatus js = mTrackedJobs.get(i);
                if (js.isReady()) {
                    if (DEBUG) {
                        Slog.d(TAG, "Running " + js + " due to network activity.");
                    }
                    mStateChangedListener.onRunJobNow(js);
                }
            }
        }
    }

    private BroadcastReceiver mConnectivityReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateTrackedJobs(-1);
        }
    };

    private INetworkPolicyListener mNetPolicyListener = new INetworkPolicyListener.Stub() {
        @Override
        public void onUidRulesChanged(int uid, int uidRules) {
            updateTrackedJobs(uid);
        }

        @Override
        public void onMeteredIfacesChanged(String[] meteredIfaces) {
            updateTrackedJobs(-1);
        }

        @Override
        public void onRestrictBackgroundChanged(boolean restrictBackground) {
            updateTrackedJobs(-1);
        }

        @Override
        public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
            updateTrackedJobs(uid);
        }

        @Override
        public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
            updateTrackedJobs(uid);
        }
    };

    @Override
    public void dumpControllerStateLocked(PrintWriter pw, int filterUid) {
        pw.println("Connectivity.");
        pw.print("Tracking ");
        pw.print(mTrackedJobs.size());
        pw.println(":");
        for (int i = 0; i < mTrackedJobs.size(); i++) {
            final JobStatus js = mTrackedJobs.get(i);
            if (js.shouldDump(filterUid)) {
                pw.print("  #");
                js.printUniqueId(pw);
                pw.print(" from ");
                UserHandle.formatUid(pw, js.getSourceUid());
                pw.print(": C="); pw.print(js.hasConnectivityConstraint());
                pw.print(": UM="); pw.print(js.hasUnmeteredConstraint());
                pw.print(": NR="); pw.println(js.hasNotRoamingConstraint());
            }
        }
    }
}


text:
/**
 * Definição de estraura para o algoritmo de Dijkstra
 */

#include "Dijkstra.hpp"

Dijkstra::Dijkstra(){}

Dijkstra::~Dijkstra(){}

/**
 * Insere caminho mínimo ao inverso
 */
vector<int> Dijkstra::shortestPath(int target)
{
    vector<int> path;

    int u = target;

    path.push_back( target );

    while( this->parent[u] != -1 )
    {
        path.push_back( this->parent[u]);
        u = this->parent[u];
    }
    reverse( path.begin(),path.end() );//inverte caminho

    // for (int i = 0; i < path.size() ; i++)
    // {
    //     cout<<" "<<path[i];
    // }
    cout<<endl;
    return path;
}

/**
 * Implementação baseada no livro The Algorithm Design Manual -- Skiena
 */
int Dijkstra::execute( Graph graph, int source, int target)
{
    Node p; 					//vetor temporário
    vector<bool> inTree;		//O nó já esta na árvore?
    vector<double> distance;	//armazena distância para source
    int v;						//nó atual
    int w;						//candidato a próximo nó
    int n;						//número de nós adjacentes
    double weight;				//peso da aresta
    double dist;				//melhor distância atual para o nó de partida

    inTree = vector<bool> ( graph.getNumberOfNodes(), false);
    distance = vector<double> ( graph.getNumberOfNodes(), std::numeric_limits<double>::max() );
    this->parent = vector<int> ( graph.getNumberOfNodes(), -1);

    v = source;
    distance[v] = 0;

    while( inTree[target] == false)
    {
        inTree[v] = true;

        p = graph.getNodeAtPosition(v);

        n = p.getDegree();

        if (n == 0)
        {
            // cout<<"Topologia com nó "<<v<<" desconexo."<<endl;

            return -std::numeric_limits<double>::max() ;
        }

        int iterator = 0;

        while( iterator < n )
        {
            w = p.getAdjacentNode(iterator);
            weight = p.getWeightEdge(iterator); //obtêm peso da aresta

            /**
             * Verificação de caminho
             */
            if ( distance[w] > ( distance[v] + weight ) && inTree[w] == false )
            {
                distance[w] = distance[v] + weight;
                this->parent[w] = v;
            }

            iterator++;
        }

        v = 0;

        dist = std::numeric_limits<double>::max();

        for (unsigned int i = 0; i < graph.getNumberOfNodes(); i++)
        {
            if ( ( inTree[i] == false ) && ( dist > distance[i] ) )
            {
                dist = distance[i];
                v = i;
            }
        }

        if (inTree[v] == true)
        {
            break;
        }
    }

    return distance[target];//retorna distância
}


text:
namespace hanabi_learning_env {

class HanabiHand {
 public:
  class ValueKnowledge {
    // Knowledge about an unknown integer variable in range 0 to value_range-1.
    // Records hints that either reveal the exact value (no longer unknown),
    // or reveal that the variable is not some particular value.
    // For example, ValueKnowledge(3) tracks a variable that can be 0, 1, or 2.
    // Initially, ValueHinted()=false, value()=-1, and ValueCouldBe(v)=true
    // for v=0, 1, and 2.
    // After recording that the value is not 1, we have
    // ValueHinted()=false, value()=-1, and ValueCouldBe(1)=false.
    // After recording that the value is 0, we have
    // ValueHinted()=true, value()=0, and ValueCouldBe(v)=false for v=1, and 2.
   public:
    explicit ValueKnowledge(int value_range);
    int Range() const { return value_plausible_.size(); }
    // Returns true if and only if the exact value was revealed.
    // Does not perform inference to get a known value from not-value hints.
    bool ValueHinted() const { return value_ >= 0; }
    int Value() const { return value_; }  // -1 if value was not hinted.
    // Returns true if we have no hint saying variable is not the given value.
    bool IsPlausible(int value) const { return value_plausible_[value]; }
    // Record a hint that gives the value of the variable.
    void ApplyIsValueHint(int value);
    // Record a hint that the variable does not have the given value.
    void ApplyIsNotValueHint(int value);

   private:
    // Value if hint directly provided the value, or -1 with no direct hint.
    int value_ = -1;
    std::vector<bool> value_plausible_;  // Knowledge from not-value hints.
  };

  class CardKnowledge {
    // Hinted knowledge about color and rank of an initially unknown card.
   public:
    CardKnowledge(int num_colors, int num_ranks);
    // Returns number of possible colors being tracked.
    int NumColors() const { return color_.Range(); }
    // Returns true if and only if the exact color was revealed.
    // Does not perform inference to get a known color from not-color hints.
    bool ColorHinted() const { return color_.ValueHinted(); }
    // Color of card if it was hinted, -1 if not hinted.
    int Color() const { return color_.Value(); }
    // Returns true if we have no hint saying card is not the given color.
    bool ColorPlausible(int color) const { return color_.IsPlausible(color); }
    void ApplyIsColorHint(int color) { color_.ApplyIsValueHint(color); }
    void ApplyIsNotColorHint(int color) { color_.ApplyIsNotValueHint(color); }
    // Returns number of possible ranks being tracked.
    int NumRanks() const { return rank_.Range(); }
    // Returns true if and only if the exact rank was revealed.
    // Does not perform inference to get a known rank from not-rank hints.
    bool RankHinted() const { return rank_.ValueHinted(); }
    // Rank of card if it was hinted, -1 if not hinted.
    int Rank() const { return rank_.Value(); }
    // Returns true if we have no hint saying card is not the given rank.
    bool RankPlausible(int rank) const { return rank_.IsPlausible(rank); }
    void ApplyIsRankHint(int rank) { rank_.ApplyIsValueHint(rank); }
    void ApplyIsNotRankHint(int rank) { rank_.ApplyIsNotValueHint(rank); }
    std::string ToString() const;

   private:
    ValueKnowledge color_;
    ValueKnowledge rank_;
  };

  HanabiHand() {}
  HanabiHand(const HanabiHand& hand)
      : cards_(hand.cards_), card_knowledge_(hand.card_knowledge_) {}
  // Copy hand. Hide cards (set to invalid) if hide_cards is true.
  // Hide card knowledge (set to unknown) if hide_knowledge is true.
  HanabiHand(const HanabiHand& hand, bool hide_cards, bool hide_knowledge);
  // Cards and corresponding card knowledge are always arranged from oldest to
  // newest, with the oldest card or knowledge at index 0.
  const std::vector<HanabiCard>& Cards() const { return cards_; }
  const std::vector<CardKnowledge>& Knowledge() const {
    return card_knowledge_;
  }
  void AddCard(HanabiCard card, const CardKnowledge& initial_knowledge);
  // Remove card_index card from hand. Put in discard_pile if not nullptr
  // (pushes the card to the back of the discard_pile vector).
  void RemoveFromHand(int card_index, std::vector<HanabiCard>* discard_pile);
  // Make cards with the given rank visible.
  // Returns new information bitmask, bit_i set if card_i color was revealed
  // and was previously unknown.
  uint8_t RevealRank(int rank);
  // Make cards with the given color visible.
  // Returns new information bitmask, bit_i set if card_i color was revealed
  // and was previously unknown.
  uint8_t RevealColor(int color);
  std::string ToString() const;

 private:
  // A set of cards and knowledge about them.
  std::vector<HanabiCard> cards_;
  std::vector<CardKnowledge> card_knowledge_;
};

}  // namespace hanabi_learning_env

#endif