text:
<file_sep>class Solution {
  public int solution(int m, int n, String[] board) {
      int answer = 0;
      char[][] field = new char[m][n];
      for(int i = 0; i < m; i++)        //field에 board옮김
      {
          field[i] = board[i].toCharArray();
      }
      boolean[][] visited;  //맞춰진것을 지우기 위함
      boolean end = false;  //지워질 것이 없는지 확인

      while(!(end))
      {
          visited = new boolean[m][n];
          end = true;
          for(int i = 0; i < m - 1; i++)
          {
              for(int j = 0; j < n -1; j++)
              {
                  if(field[i][j] == '0')  /*빈 곳은 0으로 채우기 때문에 0이면 통과*/
                      continue;
                  if((field[i][j] == field[i][j+1]) && (field[i][j] == field[i+1][j]) && (field[i][j] == field[i+1][j+1]))
                      /*자기칸과 오른쪽,아래,대각선칸이 모두같으면 표시*/
                  {
                      visited[i][j] = visited[i][j+1] = visited[i+1][j] = visited[i+1][j+1] = true;
                      end = false;
                  }
              }
          }

          for(int i = 0; i < m; i++)    //맞는칸 제거
          {
              for(int j = 0; j < n; j++)
              {
                  if(visited[i][j] == true)
                  {
                      answer++;
                      for(int k = i; k >= 1; k--)   /*위로올라가면서 칸내리기, 원래 있던곳은 0*/
                      {
                          if(field[k-1][j] == '0') break;       //0이면 굳이 칸 움직일 필요 없음
                          field[k][j] = field[k-1][j];
                          field[k-1][j] = '0';
                      }
                  }
              }
          }
      }
      return answer;
  }
}<file_sep># 문제
- ASCII ART
https://www.codingame.com/ide/puzzle/ascii-art<file_sep>leftArray = []
rightArray = []

def foldPaper(n, arr):
    if(n == 0):
        return arr

    leftArray = arr.copy()
    for e in leftArray:
        if(e == 1):
            rightArray.append(0)
        else:
            rightArray.append(1)

    arr.append(0)

    while(len(rightArray) != 0):
        arr.append(rightArray.pop())

    return foldPaper(n - 1, arr)

def solution(n):
    answer = []
    foldPaper(n, answer)

    return answer<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/

int main()
{
	int L;
	cin >> L; cin.ignore();
	int H;
	cin >> H; cin.ignore();
	string T;
	getline(cin, T);

	vector<string> answer(H);

	for (int i = 0; i < H; i++) {
		string ROW;
		getline(cin, ROW);

		answer[i] = "";

		// T에 해당하는 문자열을 한 줄씩 answer에 저장한다
		for (int j = 0; j < T.length(); j++)
		{
			// ASCII 코드로 변환하여 A부터 0, 1, 2, 3, 4,... 의 열 번호를 따온다.
			// A to Z에 해당하지 않을 경우 26번(? 문자) 할당)
			int column = (int)toupper(T[j]) - 65;
			if (column < 0 || column > 25)
				column = 26;

			// 해당하는 문자의 i번째 행을 저장한다
			answer[i] = answer[i] + ROW.substr(column * L, L);
		}
	}

	// Write an action using cout. DON'T FORGET THE "<< endl"
	// To debug: cerr << "Debug messages..." << endl;

	for (int i = 0; i < answer.size(); i++)
	{
		cout << answer[i] << endl;
	}
}<file_sep>def IsValidSkillTree(skill_tree, skill):
    temp = [ skill_tree.get(skill_name, 26) for skill_name in skill ]
    if(temp == sorted(temp)):
        return 1
    else:
        return 0

def solution(skill, skill_trees):
    answer = 0
    for skill_tree in skill_trees:
        answer += IsValidSkillTree(dict(zip(skill_tree, range(len(skill_trees)))), skill)
    return answer<file_sep>def solution(n):
    answer = [0]

    for i in range(n-1):
        temp = []
        temp = answer[:]
        temp.reverse()

        for j in range(0, len(temp)):
            if temp[j] == 1:
                temp[j] = 0
            else :
                temp[j] = 1

        answer.append(0)
        answer.extend(temp)

    return answer<file_sep>import sys
import math

# game loop
while True:
    enemyDic = dict()

    enemy_1 = input()  # name of enemy 1
    dist_1 = int(input())  # distance to enemy 1
    enemyDic[enemy_1] = dist_1

    enemy_2 = input()  # name of enemy 2
    dist_2 = int(input())  # distance to enemy 2
    enemyDic[enemy_2] = dist_2

    res = sorted(enemyDic.items(), key = (lambda x : x[1]))
    print(res[0][0])<file_sep># 문제
- onboarding
https://www.codingame.com/ide/puzzle/onboarding<file_sep>def remove_couple(s):
    stack = []
    for i in range(0, len(s)):
        a = s[i]
        if(len(stack) > 0):
            b = stack.pop()
            if(a != b):
                stack.append(b)
                stack.append(a)
        else:
            stack.append(a)

    if(len(stack) > 0):
        return False
    else:
        return True

def solution(s):
    answer = list(s)
    return remove_couple(answer)

<file_sep># 문제
- 프렌즈 4블록
https://programmers.co.kr/learn/courses/30/lessons/17679<file_sep>import java.util.Stack;

class Solution
{
    public int solution(String s)
    {
        int answer = 0;

        Stack<Character> stack = new Stack<>(); //스택정의

        for(int i = 0; i<s.length(); i++)
        {
            if(stack.isEmpty()) //스택이 비어있으면 일단 push
                stack.push(s.charAt(i));
            else if(stack.peek() == s.charAt(i))    //다음 순서랑 이전거랑 같으면 pop
                stack.pop();
            else    //다르면 일단 push
                stack.push(s.charAt(i));
        }

        if(stack.isEmpty())     //다 하고 나서 비었으면 1
            answer = 1;
        else {answer = 0;}      //안비었으면 0

        return answer;
    }
}<file_sep>import sys
import math
import string

class ASCIIChar:
    def __init__(self, match, char):
        self.match = match
        self.char = char

l = int(input())
h = int(input())
t = input()

row = []

for i in range(h):
    row.append(input())

ASCIIChars = []

for i in range(27):
    if i != 26:
        tm = string.ascii_lowercase[i]+string.ascii_uppercase[i]
    else:
        tm = ""

    temp = []
    str = ""
    for j in row:
        str = j[i*l:i*l+l]
        temp.append(str)

    ASCIIChars.append(ASCIIChar(tm,temp))

check = False
for i in range(h):
    s = ""
    for j in t:
        check = False
        for k in ASCIIChars:
            if j in k.match:
                s += k.char[i]
                check = True
                break
        if not check:
            s += ASCIIChars[26].char[i]
    print(s)
                <file_sep>import sys
import math

# A ~ Z 범위 밖의 문자라면 아스키 아트로 ? 출력해야함 주의
# 출력을 한번에 해야한다는 것도 주의할 점

def print_ASCII_Art(t, l, h, ASCII):
    result = ''

    for y in range(0, h):
        for ch in t:
            if( ord('A') <= ord(ch) and ord(ch) <= ord('Z') ):
                index = ord(ch) - ord('A')
            else:
                index = ord('Z') - ord('A') + 1

            result += ''.join(ASCII[y][index * l : (index + 1) * l])
        result += '\n'

    print(result)

l = int(input())
h = int(input())
t = input().upper()

ASCII = list()
for i in range(h):
    row = input()
    ASCII.append(list(row))

print_ASCII_Art(t, l, h, ASCII)<file_sep># mit_algorithm_study

## 개요

창원대학교 컴퓨터공학과 게임개발동아리 M.I.T.의 알고리즘 연습을 위한 저장소입니다.

알고리즘 문제 선정은 매주 회의날에 정합니다.

M.I.T.의 회원이라면 누구나 환영합니다.

## 사용법
1. 원본 저장소 fork (현재 보고 있는 저장소)
2. 해당 회의 날짜 폴더에 소스 코드 폴더를 commit
    * 폴더 이름은 닉네임으로 설정하고 내용은 코드 파일만 첨부
    * 문제 하나당 하나의 파일
3. push 이후 본인이 fork한 페이지에서 pull-request 생성
    * 이 때 본인이 fork한 저장소에서 현재 mit-games-algorithm 저장소로 pull-request를 생성해야함

## 입출력 관련 주의사항
백준과 같은 알고리즘 사이트에서는 입출력 속도가 문제 해결에 영향을 줍니다.

특히 JAVA의 경우 System.out.println은 느리기 때문에 BufferedWriter을 사용하길 추천합니다.

C++, Python도 마찬가지이기 때문에 주의해야합니다.

아래의 글들을 참고하시길 바랍니다.

입력속도: https://www.acmicpc.net/blog/view/56

출력속도: https://www.acmicpc.net/blog/view/57<file_sep>"""
선행스킬 순서에 포함되지 않은 스킬 -> 순서와 관계 없다
선행스킬 순서에 포함됨 -> 지금 순서에 나와야 할 스킬이 아니다(indexSkill로 구별) -> 불가능한 스킬트리
"""
def solution(skill, skill_trees):
    answer = 0
    for tree in skill_trees:
        if is_valid_tree(skill, tree):
            answer += 1

    return answer

def is_valid_tree(skill, skill_tree):
    index_skill = 0
    for element in skill_tree:
        if element in skill:
            if element != skill[index_skill]:
                return False
            index_skill += 1
    return True<file_sep>#include <string>
#include <vector>

using namespace std;

vector<int> solution(int n) {
    // solution(n) => solution(n-1) 채우고 중앙에 0, solution(n-1)을 뒤집은 걸 0과 1을 바꿔서 n번째부터 2n-1까지 채운다
    vector<int> answer;
    if(n == 1)
    {
        answer.push_back(0);
        return answer;
    }

    answer = solution(n-1);
    answer.push_back(0);

    int length = answer.size() - 2;

    for (int i = length; i >= 0 ; i--)
    {
        answer.push_back(answer[i] == 0 ? 1 : 0);
    }

    return answer;
}
<file_sep># 문제
- 멀쩡한 사각형
https://programmers.co.kr/learn/courses/30/lessons/62048
<file_sep>#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
	int N; // the total number of nodes in the level, including the gateways
	int L; // the number of links
	int E; // the number of exit gateways
	cin >> N >> L >> E; cin.ignore();

	vector<vector<int>> connects(L, vector<int>(2, 0));
	vector<int> exits(E);

	for (int i = 0; i < L; i++) {
		cin >> connects[i][0] >> connects[i][1]; cin.ignore();
	}
	for (int i = 0; i < E; i++) {
		cin >> exits[i]; //cin.ignore();
	}

	while (1) {
		int SI;
		int index = 0;
		cin >> SI; cin.ignore();

		bool flag = false;

		// 시간복잡도 O(L * E)
		// SI와 EI가 이웃해 있을 때 Link를 자르고, 아니면 SI와 연결된 아무 선을 자른다.
		for (int i = 0; i < L; i++)
		{
			if (connects[i][0] == SI || connects[i][1] == SI)
			{
				// SI와 연결된 임의의 선을 고름
				index = (connects[i][0] == SI) ? connects[i][1] : connects[i][0];
				for (int j = 0; j < E; j++)
				{
					if (connects[i][0] == exits[j] || connects[i][1] == exits[j])
					{
						cout << connects[i][0] << " " << connects[i][1] << endl;
						flag = true;
						break;
					}
				}
			}
		}

		if (!flag)
			cout << SI << " " << index << endl;
	}
}<file_sep># 문제
- 스킬트리
https://programmers.co.kr/learn/courses/30/lessons/49993#fn1

- 짝지어 제거하기
https://programmers.co.kr/learn/courses/30/lessons/12973<file_sep>#include <iostream>
#include <stack>

using namespace std;

int solution(string s)
{
	/*
	시간복잡도 : O(n) (stack 이용)
	짝지어서 제거할 수 있는 문자열 = 뒤집어도 똑같은 문자열(팰린드롬)들로 구성
	(예외 : abccbkddka, 팰린드롬 안에 팰린드롬이 들어 있다...)
	앞뒤 대칭을 확인할 수 있는 방법은 바로, 스택을 이용해 지금까지 나온 문자들을 저장해서 제거하는 것!
	*/
	stack<char> charStack;

	for (int i = 0; i < s.length(); i++)
	{
		if (charStack.size() > 0 && s[i] == charStack.top())
			charStack.pop();
		else
			charStack.push(s[i]);
	}

	return charStack.size() == 0;
}
<file_sep>#include <string>
#include <vector>
#include <stack>

using namespace std;

int solution(int m, int n, vector<string> board)
{
	int answer = 0;
	vector<vector<bool>> check(m, vector<bool>(n, false));

	while (true)
	{
		bool flag = false;
		// 제거 대상 탐색(좌상단 블럭 검사)
		for (int i = 0; i < m - 1; i++)
		{
			for (int j = 0; j < n - 1; j++)
			{
				char c = board[i][j];
				if (c == ' ')
					continue;

				if (c == board[i + 1][j] && c == board[i][j + 1] && c == board[i + 1][j + 1])
				{
					flag = true;
					check[i][j] = check[i + 1][j] = check[i][j + 1] = check[i + 1][j + 1] = true;
				}
			}
		}

		if (!flag)
			break;

		stack<char> s;

		// 제거 및 스택을 이용한 정렬
		for (int j = 0; j < n; j++)
		{
			for (int i = 0; i < m; i++)
			{
				if (check[i][j])
				{
					check[i][j] = false;
					board[i][j] = ' ';
					answer++;
				}
				else
				{
					s.push(board[i][j]);
				}
			}

			for (int i = m - 1; i >= 0; i--)
			{
				if (!s.empty())
				{
					board[i][j] = s.top();
					s.pop();
				}
				else
					board[i][j] = ' ';
			}
		}
	}

	return answer;
}<file_sep>#include <string>
#include <vector>

using namespace std;

vector<int> solution(int n) {
    vector<int> answer(1,0);

    for(int i = 2; i <= n; i++)
    {
        vector<int> temp(answer);
        answer.push_back(0);

        for(int j = temp.size()-1; j >= 0; j--)
        {
            temp[j] == 1 ? answer.push_back(0) : answer.push_back(1);
        }
    }
    return answer;
}<file_sep># 1. 블록 위치 업데이트 + 블록 삭제 및 카운트
# 2. 오른쪽 대각선 블록 확인
# 3. 오른쪽, 아래 블록 확인

def update_block(n, board):
    result = 0
    count = 0

    for x in range(0, n - 1):
        for y in range(0, len(board[x]) - 1):
            if(len(board[x + 1]) >= (len(board[x]) - y)):
                check_valid(x, y, board)

    for x in range(0, n):
        count += len(list(filter(lambda x: x[1], board[x])))
        board[x] = list(filter(lambda x: not x[1], board[x]))
    result += count

    if(count > 0):
        return result + update_block(n, board)
    return result

def check_valid(x, y, board):
    block = board[x][y][0]

    correction_pos = len(board[x+1]) - len(board[x])

    if(board[x + 1][y + correction_pos + 1][0] == block and board[x][y + 1][0] == block and board[x + 1][y + correction_pos][0] == block):
        board[x + 1][y + correction_pos + 1][1] = True
        board[x][y + 1][1] = True
        board[x + 1][y + correction_pos][1] = True
        board[x][y][1] = True

def Init(m, n, board):
    newBoard = list()

    for x in range(0, n):
        newBoard.append(list( [board[y][x],False] for y in range(0, m) ))
    return newBoard

def solution(m, n, board):
    print(m, n)
    board = Init(m, n, board)

    answer = update_block(n, board)
    return answer<file_sep># 문제
- 종이접기
https://programmers.co.kr/learn/courses/30/lessons/62049
<file_sep>using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;

class Solution
{
    static void Main(string[] args)
    {
        int L = int.Parse(Console.ReadLine());
        int H = int.Parse(Console.ReadLine());
        string T = Console.ReadLine();

        int[] I = Aorder(T);
        List<char> list = new List<char>();

        for (int i = 0; i < H; i++)
        {
            string ROW = Console.ReadLine();
            char[] C = ROW.ToCharArray();

            for (int j = 0 ; j < C.Length ; j++){
                list.Add(C[j]);
            }
        }
        for(int k = 0; k < H ;k++){
            for (int i = 0; i < I.Length; i++){
                for (int j = 0; j < L; j++){
                    Console.Write(list[(L * I[i]) + j + (k* (L*27) )  ]);
                }
            }Console.WriteLine();
        }
    }
    public static int[] Aorder(string T)
    {
        char[] C = T.ToCharArray();
        int[] I = new int[C.Length];

        for(int i = 0; i < C.Length ; i++)
        {
            if (Convert.ToInt32(C[i]) >= 65 && Convert.ToInt32(C[i]) <= 90)
                I[i] = Convert.ToInt32(C[i]) - 65;

            else if (Convert.ToInt32(C[i]) >= 97 && Convert.ToInt32(C[i]) <= 122)
                I[i] = Convert.ToInt32(C[i]) - 97;

            else I[i] = 26;
        }
        return I;
    }
}<file_sep>import sys
import math

linkInfo = dict()
gatewayInfo = list()

n, l, e = [int(i) for i in input().split()]
for i in range(l):
    # n1: N1 and N2 defines a link between these nodes
    n1, n2 = [int(j) for j in input().split()]

    if n1 in linkInfo:
        linkInfo[n1].append(n2)
    else:
        linkInfo[n1] = [n2]

    if n2 in linkInfo:
        linkInfo[n2].append(n1)
    else:
        linkInfo[n2] = [n1]

for i in range(e):
    ei = int(input())  # the index of a gateway node
    gatewayInfo.append(ei)

def get_link_to_sever(si):
    link = linkInfo[si]

    for e in link:
        if(e in gatewayInfo):
            return e, si
    for e in link:
        return get_link_to_sever(e)

# game loop
while True:
    si = int(input())  # The index of the node on which the Skynet agent is positioned this turn
    result = get_link_to_sever(si)
    print(result[1], result[0])<file_sep># 문제
- Skynet Revolution - Episode 1
 https://www.codingame.com/ide/puzzle/skynet-revolution-episode-1<file_sep>import math

def gcd(a, b):
	while(b!=0):
		r = a % b;
		a = b;
		b = r;
	return a

def GetUselessBox(w, h):
    num = 0
    나머지 = 0
    index = 0

    while(index < w):
        if((나머지 + h) <= w):
            몫 = math.floor((w - 나머지) / h)
            num += 몫
            index += 몫
            나머지 = (나머지 + h * 몫)
        else:
            num += 2
            index += 1
            나머지 = (나머지 + h - w)
    return num

def solution(w,h):
    최소공약수 = gcd(w, h)

    minW = (int)(w / 최소공약수)
    minH = (int)(h / 최소공약수)

    최소사각형갯수 = w / minW
    총사각형갯수 = w * h

    if(minW >= minH):
        못쓰는사각형갯수 = GetUselessBox(minW, minH)
    else:
        못쓰는사각형갯수 = GetUselessBox(minH, minW)

    answer = 총사각형갯수 - 최소사각형갯수 * 못쓰는사각형갯수

    return answer

branch_name: refs/heads/master

languages: C# Java Markdown Python C++

repo_language: C#


text:
<file_sep># Test Gold Issues

## Submitting issues

Submit issues here: https://github.com/aichemydev/testgold-issues/issues

## Feature requests

This is a list of feature requests we are currently working on.

## Known issues

This is a list of known issues with workarounds if applicable.

repo_language: Markdown

repo_name: aichemydev/testgold-issues


text:
<file_sep><?php

namespace Pktharindu\NovaPermissions;

use Laravel\Nova\Nova;
use Laravel\Nova\Tool;
use Pktharindu\NovaPermissions\Nova\Role;

class NovaPermissions extends Tool
{
    /**
     * Perform any tasks that need to happen when the tool is booted.
     */
    public function boot()
    {
        Nova::script('NovaPermissions', __DIR__.'/../dist/js/tool.js');
        Nova::style('NovaPermissions', __DIR__.'/../dist/css/tool.css');

        Nova::resources([
            Role::class,
        ]);
    }
}
<file_sep><?php

return [
    /*
    |--------------------------------------------------------------------------
    | User model class
    |--------------------------------------------------------------------------
    */

    'userModel' => 'App\User',

    /*
    |--------------------------------------------------------------------------
    | Nova User resource tool class
    |--------------------------------------------------------------------------
    */

    'userResource' => 'App\Nova\User',

    /*
    |--------------------------------------------------------------------------
    | The group associated with the resource
    |--------------------------------------------------------------------------
    */

    'roleResourceGroup' => 'Other',

    /*
    |--------------------------------------------------------------------------
    | Application Permissions
    |--------------------------------------------------------------------------
    */

    'permissions' => [
        'view users' => [
            'display_name' => 'View users',
            'description'  => 'Can view users',
            'group'        => 'User',
        ],

        'create users' => [
            'display_name' => 'Create users',
            'description'  => 'Can create users',
            'group'        => 'User',
        ],

        'edit users' => [
            'display_name' => 'Edit users',
            'description'  => 'Can edit users',
            'group'        => 'User',
        ],

        'delete users' => [
            'display_name' => 'Delete users',
            'description'  => 'Can delete users',
            'group'        => 'User',
        ],

        'view roles' => [
            'display_name' => 'View roles',
            'description'  => 'Can view roles',
            'group'        => 'Role',
        ],

        'create roles' => [
            'display_name' => 'Create roles',
            'description'  => 'Can create roles',
            'group'        => 'Role',
        ],

        'edit roles' => [
            'display_name' => 'Edit roles',
            'description'  => 'Can edit roles',
            'group'        => 'Role',
        ],

        'delete roles' => [
            'display_name' => 'Delete roles',
            'description'  => 'Can delete roles',
            'group'        => 'Role',
        ],
    ],
];

repo_language: PHP

repo_name: dormadekhin/nova-permissions


text:
<file_sep>export default [
    {
        title: 'Create simple TodoApp',
        isChecked: true
    }, {
        title: 'Research FlowTypes',
        isChecked: true
    }, {
        title: 'Research redux',
        isChecked: false
    }
];<file_sep>import React from 'react';
import ReactDOM from 'react-dom';

export default function TodoItem(props) {
    return (

            <input
                type="checkbox"
                checked={props.isChecked}
                onChange={props.onToogle}/>
            {props.title}
            <button
                type="button"
                className="btn btn-danger btn-xs pull-right"
                onClick={props.onRemove}>

            </button>

    );
}

TodoItem.propTypes = {
    isChecked: React.PropTypes.bool.isRequired,
    title: React.PropTypes.string.isRequired,

    onToogle: React.PropTypes.func.isRequired,
    onRemove: React.PropTypes.func.isRequired
};<file_sep>/* @flow */

export type TodoType = {
  title: string,
  isChecked: boolean,
};

export type EventHandlerType = (e: Event) => void;<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import TodoForm from './todoForm';
import TodoList from './todoList';

import type {TodoType}
from '../flow-types';

type PropsType = {
    todos: TodoType[]
};

export default class TodoApp extends React.Component {
    props : PropsType;
    state : PropsType;

    constructor(props) {
        super(props);

        this.state = {
            todos: props.todos
        }

        this.onCreateTodo = this
            .onCreateTodo
            .bind(this);

        this.onToogleTodo = this
            .onToogleTodo
            .bind(this);

        this.onRemoveTodo = this
            .onRemoveTodo
            .bind(this);
    }

    get completed() : number {
        return(this.state.todos.filter((todo : TodoType) => todo.isChecked)).length;
    }

    onCreateTodo(title : string) : void {
        if(!title.length) {
            return;
        }

        this.setState({
            todos: [
                ...this.state.todos, {
                    title,
                    isChecked: false
                }
            ]
        });
    }

    onToogleTodo(index : number) : void {
        if(index < 0 || index >= this.state.length) {
            return;
        }

        let todos = [...this.state.todos];
        todos[index] = Object.assign({}, todos[index], {
            isChecked: !todos[index].isChecked
        });

        this.setState({todos});
    }

    onRemoveTodo(index : number) : void {
        if(index < 0 || index >= this.state.length) {
            return;
        }

        this.setState({
            todos: this
                .state
                .todos
                .filter((todo : TodoType, position : number) => index !== position)
        });
    }

    render() {
        return (

                <TodoForm onSubmit={this.onCreateTodo}/>

                <TodoList
                    todos={this.state.todos}
                    onToogle={this.onToogleTodo}
                    onRemove={this.onRemoveTodo}/>

                    Compleated todos: {this.completed !== this.state.todos.length
                        ? this.completed + '/' + this.state.todos.length
                        : 'all'}

        );
    }
}<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import TodoItem from './todoItem';

export default function TodoList(props) {
    return (

            {props
                .todos
                .map((todo, index) => <TodoItem
                    key={index}
                    isChecked={todo.isChecked}
                    title={todo.title}
                    onToogle={() => props.onToogle(index)}
                    onRemove={() => props.onRemove(index)}/>)}

    )
}

TodoList.propTypes = {
    todos: React
        .PropTypes
        .arrayOf(React.PropTypes.shape({isChecked: React.PropTypes.bool.isRequired, title: React.PropTypes.string.isRequired})),

    onToogle: React.PropTypes.func.isRequired,
    onRemove: React.PropTypes.func.isRequired
};

repo_language: JavaScript

repo_name: wdikai/test-todo


text:
<repo_name>evosoftcz/redmine_advanced_roadmap_v2<file_sep>/lib/advanced_roadmap/journal_patch.rb
module AdvancedRoadmap
  module JournalPatch
    def self.included(base)
      base.class_eval do
        unloadable
        base.send(:include, InstanceMethods)

        base.class_eval do
          alias_method :estimated_time_hidden, :visible_details
          alias_method :visible_details, :estimated_time_hidden
        end
      end
    end

    module InstanceMethods
      def visible_details_with_estimated_time_hidden(user=User.current)
        visible_details = visible_details_without_estimated_time_hidden(user)
        visible_details.select do |detail|
          if detail.prop_key == "estimated_hours"
            User.current.allowed_to?(:view_issue_estimated_hours, project)
          else
            true
          end
        end
      end
    end
  end
end
<file_sep>/lib/advanced_roadmap/versions_controller_patch.rb
require_dependency "versions_controller"

module AdvancedRoadmap
  module VersionsControllerPatch
    def self.included(base)
      base.class_eval do

        def index_with_plugin
          index_without_plugin
          @totals = Version.calculate_totals(@versions)
          Version.sort_versions(@versions)

          @issues_by_version.each do |versions|
	    versions.last.delete_if { |issue | issue.closed? }
          end if params[:only_open]

        end

        alias_method :index_without_plugin, :index
        alias_method :index, :index_with_plugin

        def show
          @issues = @version.sorted_fixed_issues
        end

      end
    end
  end
end

repo_language: Ruby


text:
<repo_name>NikolayOdintsov/CubeGame<file_sep>/README.md
# CubeGame

This is my first project on Unity3D.

Simple game -> cube manipulation by tap on screen.

You increase game score when pass more gates.
<file_sep>/Assets/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {
	public Vector3 force;
	public int score = 0;
	public GameObject GatePrefab;
	public GameObject CubePrefab;

	bool isDead = false;
	Vector3 camPos;
	GUIStyle scoreStyle = new GUIStyle();
	GUIStyle hintStyle = new GUIStyle();

	const string YOUR_SCORE_LABEL = "Score: ";
	bool showHint = true;

	// Use this for initialization
	void Start () {
		scoreStyle.normal.textColor = Color.white;
		hintStyle.normal.textColor = Color.white;
		hintStyle.alignment = TextAnchor.UpperCenter;

		float halfScreenWidthInUnits = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0)).x - 2f;
		Vector3 deltaPos = Vector3.up * 10f;
		Vector3 prevPos = Vector3.zero;
		Vector3 curPos = Vector3.zero;

		for (int i = 1; i < 100; i++) {
			curPos = prevPos + deltaPos;
			curPos = new Vector3(Random.Range(-halfScreenWidthInUnits, halfScreenWidthInUnits), curPos.y, 0);
			Instantiate (GatePrefab, curPos, Quaternion.identity);

			Instantiate (CubePrefab, new Vector3(curPos.x + Random.Range(-2f, 2f), curPos.y + Random.Range(2f, 4f)), Quaternion.identity);
			Instantiate (CubePrefab, new Vector3(curPos.x + Random.Range(-2f, 2f), curPos.y - Random.Range(2f, 4f)), Quaternion.identity);
			prevPos = new Vector3 (0, curPos.y);
		}
	}

	// Update is called once per frame
	void Update () {
		showHint = false;
		if (isDead) {
			showHint = true;
			if (Input.GetMouseButtonDown (0)) {
				Application.LoadLevel (Application.loadedLevel);
			}
			return;
		}

		Vector3 curPos = Camera.main.WorldToScreenPoint (transform.position);

		if (curPos.x > Screen.width - 10 || curPos.x < 10) {
			GetComponent<Rigidbody2D> ().velocity = new Vector2 (
				Mathf.Abs(GetComponent<Rigidbody2D> ().velocity.x) * ((curPos.x < 10) ? 1: -1),
				GetComponent<Rigidbody2D> ().velocity.y
			);
		}

		if (Input.GetMouseButtonDown (0)) {
			if (GetComponent<Rigidbody2D> ().isKinematic) {
				GetComponent<Rigidbody2D> ().isKinematic = false;
			}

			GetComponent<Rigidbody2D> ().velocity = Vector3.zero;
			GetComponent<Rigidbody2D> ().angularVelocity = 0f;

			if (Input.mousePosition.x > Screen.width / 2) {
				GetComponent<Rigidbody2D> ().AddForce (force, ForceMode2D.Impulse);
			} else {
				GetComponent<Rigidbody2D> ().AddForce (new Vector3(-force.x, force.y), ForceMode2D.Impulse);
			}
		}

		if (curPos.y < 10) {
			Die ();
		}

		MoveCamera ();
	}

	void Die () {
		isDead = true;
		GetComponent<Collider2D> ().enabled = false;
		Debug.Log ("You died!");
	}

	void OnCollisionEnter2D (Collision2D col) {
		Die ();
	}

	void OnTriggerEnter2D(Collider2D coll) {
		coll.enabled = false;
		++score;
		Debug.Log (this.score);
	}

	void OnGUI() {
		GUI.Label(new Rect(10, 10, 100, 20), YOUR_SCORE_LABEL + score.ToString(), scoreStyle);
		if (showHint) {
			GUI.Label(new Rect((Screen.width / 4), Screen.height - 75f, 100, 20), "YOU LOST!", hintStyle);
			GUI.Label(new Rect((Screen.width / 4), Screen.height - 50f, 100, 20), "TAP TO START", hintStyle);
		}
	}

	void MoveCamera() {
		camPos = Camera.main.transform.position;

		if (transform.position.y > camPos.y) {
			Camera.main.transform.position = new Vector3 (camPos.x, transform.position.y, camPos.z);
		}
	}
}

languages: C# Markdown

repo_name: NikolayOdintsov/CubeGame


text:
<file_sep>sample(10000, 35)

nombre <-c("sergio", "alan", "betzabeth", "judith", "rodrigo", "eric", "diego", "angel")
edad <-c(36, 20, 23, 20, 21, 21, 22, 21)
sexo <-c("hombre", "hombre", "mujer", "mujer", "hombre", "hombre", "hombre", "hombre")
teduca <-c("publica", "publica", "publica", "publica", "privada", "publica", "publica", "publica")

base1 <- matrix(c(edad, nombre, sexo, teduca))
base1.1 <- data.frame(nombre, edad, sexo, teduca)

table(base1.1$edad)
table(base1.1$sexo)
attach(base1.1)
table(edad)
detach(base1.1)
summary(base1.1$edad)

# exportar base de datos

install.packages("foreign")
require(foreign)
sociodem <-read.dbf("C://Users//SALA-E11//Desktop//sdemt215//SDEMT215.dbf")
table(sociodem$SEX)


text:
<repo_name>koosiek/AssemblyBot<file_sep>/file.js
const Discord = require("discord.js");
const prettyMilliseconds = require('pretty-ms');

const prefix = "!"

let client = new Discord.Client();

client.on("ready", async() => {
    console.log(`@Assembly ... Pomyślnie zaktualizowano!`);

    client.user.setActivity("@Assembly", {
        type: "PLAYING"
    });
});

client.on("guildDelete", guild => {
    console.log(`Zostałem usunięty z serwera: ${guild.name} [ID: ${guild.id}]`);
});

client.on("message", async message => {
    if (message.author.bot) return;
    if (message.content.indexOf(prefix) !== 0) return;
        var args = message.content.slice(prefix.length).trim().split(/ +/g);
        var command = args.shift().toLowerCase()

    if (command == "wstęp") {
        let uptime = new Discord.MessageEmbed()
            .setColor(`#36393f`)
            .setDescription(``)
            .setFooter(`Zapytał: ${message.author.tag}`)
            .setImage(`https://cdn.discordapp.com/attachments/858101137562140673/860246459307786270/75335c3f56f9acb87de37dd82c3c6400.jpg`)
        message.channel.send(uptime)
    }

    if (command == "cut") {
        let cut = new Discord.MessageEmbed()
            .setColor(`#36393f`)
            .setImage(`https://media1.tenor.com/images/bd030a7745e1ae72a6c27e13a23fbfdf/tenor.gif?itemid=14870978`)
        message.channel.send(cut)
    }

    if (command == "uptime") {
        let uptime = new Discord.MessageEmbed()
            .setColor(`#36393f`)
            .setDescription(`**${prettyMilliseconds(client.uptime)}**`)
            .setImage(`https://linearb.io/wp-content/uploads/2020/05/hero-1.gif`)
        message.channel.send(uptime)
    }

    if (command == "home") {
        let home = new Discord.MessageEmbed()
            .setDescription(`**Welcome to our bot's home!**\n\n**!**cut (⋆⋆⋆/⋆⋆⋆⋆⋆)\n**!**uptime (⋆⋆/⋆⋆⋆⋆⋆)\n**!**home (⋆⋆⋆⋆/⋆⋆⋆⋆⋆)\n**!**wstęp (⋆⋆⋆⋆⋆/⋆⋆⋆⋆⋆)\n\n**The asterisks show the popularity of the command**`)
            .setImage(`https://i.pinimg.com/originals/93/c7/44/93c744bcde1780c94bb1d3f03991f8a7.gif`)
        message.channel.send(home)
    }

    if (command == "personel") {
        let personel = new Discord.MessageEmbed()
            .setColor(`#36393f`)
            .setDescription(`soon...`)
            .setImage(`https://monophy.com/media/sLlA3D82b344w/monophy.gif`)
        message.channel.send(personel)
    }

});

client.login('token');

branch_name: refs/heads/main

repo_name: koosiek/AssemblyBot


text:
<file_sep>silhouette-character-sheet
==========================

An automated Silhouette RPG system character sheet.

Another golden oldie and an insanity inducing attempt at taming Adobe PDF scripting, which I recommend everyone to just stay right the hell clear of.

This is for use with Silhouette Engine 2 games from Dream Pod 9, the likes of Heavy Gear, Jovian Chronicles and CORE Command. I've included the .pages file in case anyone (no one ever will) would want to make some changes of their own.

![](https://github.com/Heilemann/silhouette-character-sheet/blob/master/screenshot.png?raw=true)

repo_name: Heilemann/silhouette-character-sheet


text:
<file_sep># ProjetoWeb
Esse vai ser um projeto voltado para as finanças pessoais
<file_sep>const h = document.querySelector('body')
const porId = document.getElementById('minhaId')
console.log(h.firstChild, porId)

languages: Markdown JavaScript

repo_name: GuiLeme/ProjetoWeb


text:
<file_sep>#include "./rcc/bsp_clk_config.h"

void HSE_SetSysClk(uint32_t RCC_PLLMul)
{
	__IO uint32_t HSEStartUpStatus = 0;

	//复位RCC寄存器到默认值
	RCC_DeInit();

	//使能HSE,开启外部晶振
	RCC_HSEConfig(RCC_HSE_ON);

	//等待HSE启动稳定
	HSEStartUpStatus = RCC_WaitForHSEStartUp();

	//HSE稳定后继续往下执行
	if(HSEStartUpStatus == SUCCESS)
	{
		/*-----使能预取指-----*/
		FLASH->ACR |= FLASH_ACR_PRFTBE;

		/* Flash 的等待时间 */
		FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
		FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2;

		/*------------设置分频因子--------------*/
		RCC_HCLKConfig(RCC_SYSCLK_Div1);
		RCC_PCLK1Config(RCC_HCLK_Div2);
		RCC_PCLK2Config(RCC_HCLK_Div1);

		/*-------设置PLL时钟来源，设置PLL倍频因子--------*/

		//开启PLL
		RCC_PLLCmd(ENABLE);
		//等待PLL稳定
		while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET){
		}
		//当PLL稳定后，把PLL时钟切换为系统时钟SYSCLK
		RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
		//读取时钟切换状态，确保PLLCLK被选为系统时钟
		while (RCC_GetSYSCLKSource() != 0x08){
		}

	}
	else
	{
		/*---HSE启动失败，用户可以在这里添加错误的处理代码----*/
		while(1) {
		}
	}
}<file_sep>#ifndef _BSP_LED_H
#define _BSP_LED_H

#include "stm32f10x.h"

#define LED1_GPIO_CLK	RCC_APB2Periph_GPIOA
#define LED1_GPIO_PORT	GPIOA
#define LED1_GPIO_PIN_1	GPIO_Pin_4
#define LED1_GPIO_PIN_2 GPIO_Pin_5

#define LED2_GPIO_CLK	RCC_APB2Periph_GPIOC
#define LED2_GPIO_PORT	GPIOC
#define LED2_GPIO_PIN_1	GPIO_Pin_4

void LED_GPIO_Config(void);
void delay(__IO uint32_t count);

#endif<file_sep>#include "stm32f10x.h"
#include "./UART/bsp_uart.h"
#include "./LED/bsp_led.h"

int main(void)
{
  char ch;

	LED_GPIO_Config();	//初始化LED
	USART_Config();			//初始化USART
	Show_Message();			//打印指令输入提示信息

	while(1)
	{
		ch = getchar();		//获取字符指令
		printf("接收到字符：%c\n", ch);

		switch(ch)				//根据字符指令控制LED
		{
			case '1':
				LED1_TOGGLE;
			  break;
			case '2':
				LED1_ON;
			  break;
			case '3':
				LED1_OFF;
			  break;
			case '4':
				LED2_TOGGLE;
			  break;
			case '5':
				LED1_ON;
			  break;
			case '6':
				LED1_OFF;
			  break;
			default:
				Show_Message();	 //如果不是指令字符，打印提示信息
			  break;
		}

	}
}<file_sep>#include "stm32f10x.h"
#include "./key/bsp_key.h"
#include "./LED/bsp_led.h"

void delay(__IO uint32_t count)
{
	for(; count!=0; count--);
}

int main(void)
{
	LED_GPIO_Config();
	KEY_GPIO_Config();

	while(1)		//按键扫描
	{
		if(KEY_Scan(KEY1_GPIO_PORT, KEY1_GPIO_PIN) == KEY_ON)
		{
			GPIO_SetBits(LED1_GPIO_PORT, LED1_GPIO_PIN);
			delay(0x0FFFFF);
			GPIO_ResetBits(LED1_GPIO_PORT, LED1_GPIO_PIN);

		}

		if(KEY_Scan(KEY2_GPIO_PORT, KEY2_GPIO_PIN) == KEY_ON)
		{
			GPIO_SetBits(LED2_GPIO_PORT, LED2_GPIO_PIN);
			delay(0x0FFFFF);
			GPIO_ResetBits(LED2_GPIO_PORT, LED2_GPIO_PIN);
		}
	}
}
<file_sep>#include "./rcc/bsp_clk_config.h"

void HSI_SetSysClk(uint32_t RCC_PLLMul)
{
	__IO uint32_t HSIStartUpStatus = 0;

	//复位RCC寄存器到默认值
	RCC_DeInit();

	//使能HSI,开启外部晶振
	RCC_HSICmd(ENABLE);

	//等待HSI启动稳定
	HSIStartUpStatus = RCC->CR & RCC_CR_HSIRDY;

	//HSE稳定后继续往下执行
	if(HSIStartUpStatus == RCC_CR_HSIRDY)
	{
		/*-----使能预取指-----*/
		FLASH->ACR |= FLASH_ACR_PRFTBE;

		/* Flash 的等待时间 */
		FLASH->ACR &= (uint32_t)((uint32_t)~FLASH_ACR_LATENCY);
		FLASH->ACR |= (uint32_t)FLASH_ACR_LATENCY_2;

		/*-------配置分频因子--------*/
		RCC_HCLKConfig(RCC_SYSCLK_Div1);
		RCC_PCLK1Config(RCC_HCLK_Div2);
		RCC_PCLK2Config(RCC_HCLK_Div1);

		/*--------选择PLL的时钟源，配置PLL倍频因子-----*/
		RCC_PLLConfig(RCC_PLLSource_HSI_Div2, RCC_PLLMul);

		//开启PLL
		RCC_PLLCmd(ENABLE);
		//等待PLL稳定
		while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET){
		}
		//当PLL稳定后，把PLL时钟切换为系统时钟SYSCLK
		RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
		//读取时钟切换状态，确保PLLCLK被选为系统时钟
		while (RCC_GetSYSCLKSource() != 0x08){
		}

	}
	else
	{
		/*---HSE启动失败，可以在这里添加错误的处理代码----*/
		while(1) {
		}
	}
}<file_sep>#include "./key/bsp_key.h"

void KEY_GPIO_Config(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	//打开外设相关时钟
	RCC_APB2PeriphClockCmd(KEY1_GPIO_CLK | KEY2_GPIO_CLK, ENABLE);
	//初始化外设相关的结构体
	GPIO_InitStructure.GPIO_Pin  = KEY1_GPIO_PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(KEY1_GPIO_PORT, &GPIO_InitStructure);

	GPIO_InitStructure.GPIO_Pin  = KEY2_GPIO_PIN;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
	GPIO_Init(KEY2_GPIO_PORT, &GPIO_InitStructure);

}

uint8_t KEY_Scan(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)		/*------按键扫描函数---------*/
{
	if(GPIO_ReadInputDataBit(GPIOx, GPIO_Pin) == KEY_ON)
	{
		while(GPIO_ReadInputDataBit(GPIOx, GPIO_Pin) == KEY_ON);
		return KEY_ON;
	}
	else
		return KEY_OFF;
}<file_sep>#include "stm32f10x.h"
#include "./led/bsp_led.h"

#define SOFT_DELAY Delay(0x0FFFFF);

void Delay(__IO u32 nCount);

int main(void)
{
	HSI_SetSysClk(RCC_PLLMul_16);

	/* LED 端口初始化 */
	LED_GPIO_Config();

	while (1)
	{
		LED1_ON;			  // 亮
		SOFT_DELAY;
		LED1_OFF;		   // 灭

		LED2_ON;			 // 亮
		SOFT_DELAY;
		LED2_OFF;		   // 灭

	}
}

void Delay(__IO uint32_t nCount)	 //延时函数
{
	for(; nCount != 0; nCount--);
}

<file_sep>#include "stm32f10x.h"
#include "./LED/bsp_led.h"

void delay(__IO uint32_t count)
{
	for(; count!=0; count--);
}

int main(void)
{
	LED_GPIO_Config();
	while(1)
	{
		GPIO_SetBits(LED1_GPIO_PORT, LED1_GPIO_PIN_1);
		GPIO_SetBits(LED1_GPIO_PORT, LED1_GPIO_PIN_2);
		GPIO_SetBits(LED2_GPIO_PORT, LED1_GPIO_PIN_1);

		delay(0x0FFFFF);

		GPIO_ResetBits(LED1_GPIO_PORT, LED1_GPIO_PIN_1);
		GPIO_ResetBits(LED1_GPIO_PORT, LED1_GPIO_PIN_2);
		GPIO_ResetBits(LED2_GPIO_PORT, LED1_GPIO_PIN_1);

		delay(0x0FFFFF);
	}

}<file_sep>#ifndef _BSP_EXTI_KEY_H
#define _BSP_EXTI_KEY_H

#include "stm32f10x.h"

#define KEY1_EXTI_GPIO_CLK	    RCC_APB2Periph_GPIOA
#define KEY1_EXTI_GPIO_PORT	    GPIOA
#define KEY1_EXTI_GPIO_PIN	    GPIO_Pin_0
#define KEY1_GPIO_PORTSOURCE	GPIO_PortSourceGPIOA
#define KEY1_GPIO_PINSOURCE	    GPIO_PinSource0
#define KEY1_EXTI_LINE			EXTI_Line0
#define KEY1_EXTI_IRQN          EXTI0_IRQn
#define KEY1_EXTI_IRQHANDER     EXTI0_IRQHandler

#define KEY2_EXTI_GPIO_CLK	    RCC_APB2Periph_GPIOC
#define KEY2_EXTI_GPIO_PORT	    GPIOC
#define KEY2_EXTI_GPIO_PIN 	    GPIO_Pin_13
#define KEY2_GPIO_PORTSOURCE	GPIO_PortSourceGPIOC
#define KEY2_GPIO_PINSOURCE	    GPIO_PinSource13
#define KEY2_EXTI_LINE			EXTI_Line13
#define KEY2_EXTI_IRQN          EXTI15_10_IRQn
#define KEY2_EXTI_IRQHANDER     EXTI15_10_IRQHandler

void KEY_EXTI_Config(void);

#endif  /* _BSP_EXTI_KEY_H */<file_sep>#include "stm32f10x.h"
#include "./led/bsp_led.h"

#define BITBAND(addr, bitnum) ((addr & 0xF0000000) + 0x02000000 + ((addr & 0x00FFFFFF) << 5) + (bitnum<< 2 ))	//把"位带地址+位序号"转化成别名地址的宏

#define MEM_ADDR(addr) *((volatile unsigned long *) (addr))		//把一个地址转换成一个指针

#define BIT_ADDR(addr, bitnum) MEM_ADDR(BITBAND(addr, bitnum))	//把位带别名区地址转换成指针

/*--------------GPIO ODR寄存器映射------------*/
#define GPIOA_ODR_Addr	(GPIOA_BASE + 12)
#define GPIOB_ODR_Addr	(GPIOB_BASE + 12)
#define GPIOC_ODR_Addr	(GPIOC_BASE + 12)
#define GPIOD_ODR_Addr	(GPIOD_BASE + 12)
#define GPIOE_ODR_Addr	(GPIOE_BASE + 12)
#define GPIOF_ODR_Addr	(GPIOF_BASE + 12)
#define GPIOG_ODR_Addr	(GPIOG_BASE + 12)

/*--------------GPIO IDR寄存器映射------------*/
#define GPIOA_IDR_Addr	(GPIOA_BASE + 12)
#define GPIOB_IDR_Addr	(GPIOB_BASE + 12)
#define GPIOC_IDR_Addr	(GPIOC_BASE + 12)
#define GPIOD_IDR_Addr	(GPIOD_BASE + 12)
#define GPIOE_IDR_Addr	(GPIOE_BASE + 12)
#define GPIOF_IDR_Addr	(GPIOF_BASE + 12)
#define GPIOG_IDR_Addr	(GPIOG_BASE + 12)

/*---------------GPIO输入输出位操作----------------*/
#define PAout(n)	BIT_ADDR(GPIOA_ODR_Addr, n)
#define PAin(n)		BIT_ADDR(GPIOA_IDR_Addr, n)

#define PBout(n)	BIT_ADDR(GPIOB_ODR_Addr, n)
#define PBin(n)		BIT_ADDR(GPIOB_IDR_Addr, n)

#define PCout(n)	BIT_ADDR(GPIOC_ODR_Addr, n)
#define PCin(n)		BIT_ADDR(GPIOC_IDR_Addr, n)

#define PDout(n)	BIT_ADDR(GPIOD_ODR_Addr, n)
#define PDin(n)		BIT_ADDR(GPIOD_IDR_Addr, n)

#define PEout(n)	BIT_ADDR(GPIOE_ODR_Addr, n)
#define PEin(n)		BIT_ADDR(GPIOE_IDR_Addr, n)

#define PFout(n)	BIT_ADDR(GPIOF_ODR_Addr, n)
#define PFin(n)		BIT_ADDR(GPIOF_IDR_Addr, n)

#define PGout(n)	BIT_ADDR(GPIOG_ODR_Addr, n)
#define PGin(n)		BIT_ADDR(GPIOG_IDR_Addr, n)

void delay(__IO uint32_t count)
{
	for(; count!=0; count--);
}

int main(void)
{
	LED_GPIO_Config();

	while(1)
	{
		PAout(12) = 1;
		delay(0x0FFFFF);

		PAout(12) = 0;
		delay(0x0FFFFF);

		PBout(5) = 1;
		delay(0x0FFFFF);

		PBout(5) = 0;
		delay(0x0FFFFF);
	}
}<file_sep>#include "./LED/bsp_led.h"

void LED_GPIO_Config(void)
{
	//定义GPIO_InitTypeDef类型的结构体
	GPIO_InitTypeDef GPIO_InitStructure;
	//打开GPIOA时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	//设定要控制的具体I/O口
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 |GPIO_Pin_12;
	//设置引脚输出模式为通用推挽输出
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	//设定引脚速率为50MHz
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	//调用库函数初始化GPIOA
	GPIO_Init(GPIOA, &GPIO_InitStructure);

	//定义GPIO_InitTypeDef类型的结构体
	//nGPIO_InitTypeDef GPIO_InitStructure;
	//打开GPIOB时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	//设定要控制的具体I/O口
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4 |GPIO_Pin_5;
	//设置引脚输出模式为通用推挽输出
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	//设定引脚速率为50MHz
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	//调用库函数初始化GPIOB
	GPIO_Init(GPIOB, &GPIO_InitStructure);
}<file_sep># DMA

## 编程要点
- 1)使能DMA时钟
- 2)配置DMA数据参数
- 3)使能DMA，进行传输
- 4)等待传输完成，并对源数据和目标地址数据进行比较
<file_sep>#include "./SysTick/bsp_SysTick.h"

void SysTick_Delay_ms(uint32_t us)          //查询标志位
{
	uint32_t i;
	SysTick_Config(72000);
	for(i=0; i<us; i++)
	{
		while( !((SysTick->CTRL) & (1<<16)) );
	}

	//失能
	SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}

volatile uint32_t isr_ms;										//使用中断服务函数
void SysTick_Delay_ms_INT(uint32_t ms)
{
	isr_ms = 500;
	SysTick_Config(72000);
	while(isr_ms);

	//失能
	SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk;
}<file_sep>#include "./LED/bsp_led.h"

void LED_GPIO_Config(void)
{
	//定义GPIO_InitTypeDef类型的结构体
	GPIO_InitTypeDef GPIO_InitStructure;
	//打开GPIOA 、 GPIOB的时钟
	RCC_APB2PeriphClockCmd(LED1_GPIO_CLK | LED2_GPIO_CLK, ENABLE);
	//设定要控制的具体I/O口
	GPIO_InitStructure.GPIO_Pin = LED1_GPIO_PIN | LED2_GPIO_PIN;
	//设置引脚输出模式为通用推挽输出
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	//设定引脚速率为50MHz
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	//调用库函数初始化GPIOA 、 GPIOB
	GPIO_Init(LED1_GPIO_PORT, &GPIO_InitStructure);
	GPIO_Init(LED2_GPIO_PORT, &GPIO_InitStructure);
}
 <file_sep>#ifndef _BSP_LED_H
#define _BSP_LED_H

#include "stm32f10x.h"

#define LED1_GPIO_CLK	 RCC_APB2Periph_GPIOA
#define LED1_GPIO_PORT	GPIOA
#define LED1_GPIO_PIN 	GPIO_Pin_4

#define LED2_GPIO_CLK	 RCC_APB2Periph_GPIOA
#define LED2_GPIO_PORT	GPIOA
#define LED2_GPIO_PIN  GPIO_Pin_5

#define LED3_GPIO_CLK	 RCC_APB2Periph_GPIOC
#define LED3_GPIO_PORT	GPIOC
#define LED3_GPIO_PIN 	GPIO_Pin_4

void LED_GPIO_Config(void);

#endif<file_sep>#ifndef _BSP_KEY_H
#define _BSP_KEY_H

#include "stm32f10x.h"

#define KEY1_GPIO_CLK	RCC_APB2Periph_GPIOA
#define KEY1_GPIO_PORT	GPIOA
#define KEY1_GPIO_PIN	GPIO_Pin_0

#define KEY2_GPIO_CLK	RCC_APB2Periph_GPIOC
#define KEY2_GPIO_PORT	GPIOC
#define KEY2_GPIO_PIN	GPIO_Pin_13

#define KEY_ON  1
#define KEY_OFF 0

void KEY_GPIO_Config(void);
uint8_t KEY_Scan(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin);

#endif /*_BSP_KEY_H*/

<file_sep>#include "stm32f10x.h"
#include "./UART/bsp_uart.h"

int main(void)
{
  /*初始化USART 配置模式为 115200 8-N-1，中断接收*/
  USART_Config();

	/* 发送一个字符串 */
	Usart_SendString( DEBUG_USARTx,"这是一个串口中断接收回显实验\n");
	printf("欢迎使用秉火STM32开发板\n\n\n\n");

  while(1)
	{

	}
}<file_sep>
# 新建工程模板

## 一、新建本地工程文件夹
在计算机上任选一位置建立一个文件夹，再在这个文件夹中建立Doc、Libraries、Listing、Output、User、Project六个子文件夹，对这六个文件的说明如下：
- Doc ：存放程序说明文件
- Libraries ：存放库文件
- Listing ：存放编译器编译时产生的C / 汇编 / 链接的列表清单
- Output ：存放编译产生的调试信息、hex文件、预览信息、封装库等
- Project ：存放工程
- User ：用户编写的驱动文件
## 二 、添加库文件

将库文件添加到相应的文件夹下：

| 文件夹名称      | 添加的文件
| --------- | -------- |
| Libraries    | CMSIS:存放与CM3内核有关的库文件 STM32F10x_StdPeriph_Driver:STM32外设库文件
| Listing     | 暂时为空
| Output     | 暂时为空
|  Project    |暂时为空
|User         |stm32f10x_conf.h : 用来配置库的头文件 stm32f10x_it.h : 中断相关的函数都在这个文件中   main ：main函数文件

## 三、新建工程
打开KEIL，新建一个工程，保存在Project文件夹下
### 1.选择CPU型号
### 2.在线添加库文件
因为后面会手动添加库文件，这里点击关闭
### 3.添加组文件夹 、在组文件夹中添加文件
在新建的工程中添加STARTUP 、CMSIS 、FWLIB 、USER 、DOC 5个组文件夹，再在每个组文件夹中从建好的工程文件添加相应的文件：

| 组文件夹名称      | 添加的文件
| --------- | -------- |
| STARTUP    |   startup_stm32f10x_hd.s
| CMSIS        |    core_cm3.c 、system_stm32f10x.c
| FWLB         |    STM32F10x_StdPeriph_Driver\src 文件下的全部c文件，即固件库文件
| USE           |   用户编写的文件 、main.c 、stm32f10x_it.c

### 4.配置魔术棒选项卡
##### 1）在Target选项卡中，选中 “Use MicroLab” 复选框
##### 2）在Output选项卡中把输出文件夹定位到工程目录下的 “Output” 文件夹，把 ”Create HEX File“选项勾上
##### 3）在Listing选项卡中把输出文件夹定位到工程目录下的 “Listing” 文件夹
##### 4）在C/C++选项卡中添加处理宏及编译器编译时查找的头文件路径
- STM32F10X_HD宏 ：使STM32标准库根据我们选定的芯片型号来配置
- USE_STDPERIPH_DERIVER宏 ：让stm32f10x.h 包含 stm32f10x_conf.h 这个头文件<file_sep># I2C

## I2C协议简介
### I2C物理层特点：
- 它是一个支持设备的总线
- 一个I2C总线只使用两条总线线路，一条双向串行数据线（SDA），一条串行时钟线（SCL）
- 每个连接到总线的设备都有一个独立的地址
- 总线通过上拉电阻连到电源。当I2C设备空闲时，会输出高阻态。
- 多个主机同时使用总线时，会利用仲裁方式决定由哪个设备占用总线
- 具有3种传输模式
- 连接到相同总线的IC数量受到的最大电容400pF限制

### 协议层

<file_sep>#include "./KEY/bsp_exti_key.h"

static void NVIC_Config(void)
{
	NVIC_InitTypeDef NVIC_InitStructure;

	/*-------第一步、配置中断优先级分组---------*/
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);

	/*-------第二步、配置 NVIC 的初始化结构体-------*/
	NVIC_InitStructure.NVIC_IRQChannel                   =  KEY1_EXTI_IRQN;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority =  1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority        =  0;
	NVIC_InitStructure.NVIC_IRQChannelCmd                =  ENABLE;

	/*-------第三步、调用 NVIC 初始化函数--------*/
	NVIC_Init( &NVIC_InitStructure );

	/*-------第二步、配置 NVIC 的初始化结构体-------*/
	NVIC_InitStructure.NVIC_IRQChannel                   =  KEY2_EXTI_IRQN;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority =  1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority        =  1;
	NVIC_InitStructure.NVIC_IRQChannelCmd                =  ENABLE;

	/*-------第三步、调用 NVIC 初始化函数--------*/
	NVIC_Init( &NVIC_InitStructure );
}

void KEY_EXTI_Config(void)
{
	//定义GPIO_InitTypeDef类型的结构体
	GPIO_InitTypeDef GPIO_InitStructure;
	//定义EXTI_InitTypeDef类型的结构体
    EXTI_InitTypeDef EXTI_InitStructure;

    NVIC_Config();

	/*----------第一步、初始化要连接到的 EXTI 的 GPIO------------*/
	//打开GPIOA 、 GPIOC的时钟
	RCC_APB2PeriphClockCmd(KEY1_EXTI_GPIO_CLK | KEY2_EXTI_GPIO_CLK, ENABLE);
	//设定要控制的具体I/O口
	GPIO_InitStructure.GPIO_Pin  =  KEY1_EXTI_GPIO_PIN | KEY2_EXTI_GPIO_PIN;
	//设置引脚输出模式为通用推挽输出
	GPIO_InitStructure.GPIO_Mode =  GPIO_Mode_IN_FLOATING;
	//调用库函数初始化GPIOA 、 GPIOC
	GPIO_Init(KEY1_EXTI_GPIO_PORT, &GPIO_InitStructure);
	GPIO_Init(KEY2_EXTI_GPIO_PORT, &GPIO_InitStructure);

	/*-------------第二步、初始化 EXTI 用于产生中断/事件-------------*/
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);

	GPIO_EXTILineConfig(KEY1_GPIO_PORTSOURCE, ENABLE);
	EXTI_InitStructure.EXTI_Line    =  KEY1_EXTI_LINE;
	EXTI_InitStructure.EXTI_Mode    =  EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger =  EXTI_Trigger_Rising;
	EXTI_InitStructure.EXTI_LineCmd =  ENABLE;
	EXTI_Init( &EXTI_InitStructure );

	GPIO_EXTILineConfig(KEY2_GPIO_PORTSOURCE, ENABLE);
	EXTI_InitStructure.EXTI_Line    =  KEY2_EXTI_LINE;
	EXTI_InitStructure.EXTI_Mode    =  EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger =  EXTI_Trigger_Falling;
	EXTI_InitStructure.EXTI_LineCmd =  ENABLE;
	EXTI_Init( &EXTI_InitStructure );
}

<file_sep># RCC — 使用HSE/HSI配置时钟

## 系统时钟配置流程<file_sep># SysTick —— 系统定时器

## 简介

SysTick : 系统定时器，24位，只能递减，是内核中的一个外设

SysTick寄存器汇总 ：

| 寄存器名称      | 寄存器描述
| --------- | -------- |
| CTRL    | SysTick 控制及状态寄存器  |
| LOAD    | SysTick 重装载数值寄存器  |
| VAL     | SysTick 当前数值寄存器    |
| CALIB   | SysTick 校准数值寄存器    |

## 编程要点

- 1.设置重装载寄存器的值
- 2.清除当前数值寄存器的值
- 3.配置控制与状态寄存器

<file_sep>#include "stm32f10x.h"
#include "./led/bsp_led.h"

void delay(__IO uint32_t count)
{
	for(; count!=0; count--);
}

int main(void)
{
	LED_GPIO_Config();
	while(1)
	{
		GPIO_SetBits(GPIOA,GPIO_Pin_12);
		GPIO_SetBits(GPIOA,GPIO_Pin_11);
		GPIO_SetBits(GPIOB,GPIO_Pin_4);
		GPIO_SetBits(GPIOB,GPIO_Pin_5);

		delay(0x0FFFFF);

		GPIO_ResetBits(GPIOA, GPIO_Pin_12);
		GPIO_ResetBits(GPIOA, GPIO_Pin_11);
		GPIO_ResetBits(GPIOB, GPIO_Pin_4);
		GPIO_ResetBits(GPIOB, GPIO_Pin_5);

		delay(0x0FFFFF);
	}

}<file_sep>#ifndef __BSP_CLK_CONFIG
#define __BSP_CLK_CONFIG

#include "stm32f10x.h"

void HSE_SetSysClk(uint32_t RCC_PLLMul);

#endif /*__BSP_CLK_CONFIG*/<file_sep>#ifndef __BSP_SYSTICK_H
#define __BSP_SYSTICK_H

#include "stm32f10x.h"

void SysTick_Delay_ms(uint32_t ms);

void SysTick_Delay_ms_INT(uint32_t ms);

#endif /*__BSP_SYSTICK_H*/<file_sep># 使用固件库点亮LED灯

<file_sep># USART —— 串口通信

## 编程要点
- 使能RX和TX引脚、GPIO时钟和USART时钟
- 初始化GPIO，并将GPIO复用到USART上
- 配置USART函数
- 配置中断控制器并使能USART接收中断
- 使能USART
- 在USART接收中断服务函数中实现数据接收和发送
<file_sep># 通信的基本概念

## 串行通信和并行通信

按数据传送的方式，通讯可分为串行通讯与并行通讯

**串行通信**：串行通讯是指设备之间通过少量数据信号线(一般是 8 根以下)，地线以及控制信号线，按数据位形式一位一位地传输数据的通讯方式。

**并行通信**：并行通讯一般是指使用 8、16、32 及 64 根或更多的数据线进行传输的通讯方式，并行通讯就像多个车道的公路，可以同时传输多个数据位的数据

## 全双工、 半双工和单工

根据数据通讯的方向，通讯又分为全双工、半双工及单工通讯，它们主要以信道的方向来区分

|  通 讯 方 式   |    说明  |
| --------------| -------- |
|  全双工     | 在同一时刻，两个设备之间可以同时收发数据
|  半双工     | 两个设备之间可以收发数据，但不能在同一时刻进行
|   单工       | 在任何时刻都只能进行一个方向的通讯，即一个固定为发送设备，另一个固定为接收设备

## 同步通信和异步通信

根据通讯的数据同步方式，又分为同步和异步两种，可以根据通讯过程中是否有使用到时钟信号进行简单的区分。

在同步通讯中，收发设备双方会使用一根信号线表示时钟信号，在时钟信号的驱动下双方进行协调步数据。通讯中通常双方会统一规定在时钟信号的上升沿或下降沿对数据线进行采样。

在异步通讯中不使用时钟信号进行数据同步，它们直接在数据信号中穿插一些同步用的信号位，或者把主体数据进行打包，以数据帧的格式传输数据，见图 20-4，某些通讯中还需要双方约定数据的传输速率，以便更好地同步。

在同步通讯中，数据信号所传输的内容绝大部分就是有效数据，而异步通讯中会包含有帧的各种标识符，所以同步通讯的效率更高，但是同步通讯双方的时钟允许误差较小，而异步通讯双方的时钟允许误差较大。

## 波特率

衡量通讯性能的一个非常重要的参数就是通讯速率，通常以比特率(Bitrate)来表示，即
每秒钟传输的二进制位数，单位为比特每秒(bit/s)。容易与比特率混淆的概念是“波特率”
(Baudrate)，它表示每秒钟传输了多少个码元。而码元是通讯信号调制的概念，通讯中常用
时间间隔相同的符号来表示一个二进制数字，这样的信号称为码元。如常见的通讯传输中，
用 0V 表示数字 0，5V 表示数字 1，那么一个码元可以表示两种状态 0 和 1，所以一个码元
等于一个二进制比特位，此时波特率的大小与比特率一致；如果在通讯传输中，有 0V、
2V、4V 以及 6V 分别表示二进制数 00、01、10、11，那么每个码元可以表示四种状态，
即两个二进制比特位，所以码元数是二进制比特位数的一半，这个时候的波特率为比特率
的一半。因为很多常见的通讯中一个码元都是表示两种状态，人们常常直接以波特率来表
示比特率。
<file_sep>#include "stm32f10x.h"
#include "./LED/bsp_led.h"
#include "./KEY/bsp_exti_key.h"

int main(void)
{
	LED_GPIO_Config();

	KEY_EXTI_Config();	//等待外部中断的到来，然后去中断服务函数里面去执行程序

} <file_sep># EXTI —— 外部中断/时间控制器

## 编程要点

- 1 . 初始化要连接到的 EXTI 的 GPIO
- 2 . 初始化 EXTI 用于产生中断/事件
- 3 . 初始化 NVIC ，用于处理中断
- 4 . 编写中断服务函数
- 5 . main 函数<file_sep>#ifndef _BSP_LED_H
#define _BSP_LED_H

#include "stm32f10x.h"

#define LED1_GPIO_CLK	RCC_APB2Periph_GPIOB
#define LED1_GPIO_PORT	GPIOB
#define LED1_GPIO_PIN 	GPIO_Pin_5

#define LED2_GPIO_CLK	RCC_APB2Periph_GPIOC
#define LED2_GPIO_PORT	GPIOC
#define LED2_GPIO_PIN	GPIO_Pin_4

void LED_GPIO_Config(void);

#endif<file_sep>#ifndef __BSP_CLK_CONFIG
#define __BSP_CLK_CONFIG

#include "stm32f10x.h"

void HSI_SetSysClk(uint32_t RCC_PLLMul);

#endif /*__BSP_CLK_CONFIG*/<file_sep># 中断概述

- 系统异常：体现在内核水平
- 外部中断：体现在外设水平

## NVIC 简介

NVIC 是嵌套向量中断控制器，控制着整个芯片中断相关的功能，它跟内核紧密耦合，是内核里面的一个外设 。管理着包括内核和片上所有外设的中断相关的功能。

两个重要的库文件 ：core_cm3.h 和 misc.h

## 中断编程的顺序

- 1 . 使能中断请求
使能外设某个中断，这个具体由每个外设的相关中断使能位控制。比如串口有发送完成中断，接收完成中断，这两个中断都由串口控制寄存器的相关中断使能位控制。

- 2 . 初始化 NVIC_InitTypeDef 结构体，配置中断优先级分组
初始化 NVIC_InitTypeDef 结构体，配置中断优先级分组，设置抢占优先级和子优先级，使能中断请求。NVIC_InitTypeDef 结构体在固件库头文件 misc.h 中定义。

有关 NVIC 初始化结构体的成员：
1) NVIC_IROChannel：用来设置中断源，不同的中断中断源不一样，且不可写错，即使写错了程序不会报错，只会导致不响应中断。
2) NVIC_IRQChannelPreemptionPriority：抢占优先级，具体的值要根据优先级分组来确定
3) NVIC_IRQChannelSubPriority：子优先级，具体的值要根据优先级分组来确定
4) NVIC_IRQChannelCmd：中断使能（ENABLE）或者失能（DISABLE）。操作的是 NVIC_ISER 和NVIC_ICER 这两个寄存器。

- 3 . 编写中断服务函数
在启动文件 startup_stm32f10x_hd.s 中我们预先为每个中断都写了一个中断服务函数，只是这些中断函数都是为空，为的只是初始化中断向量表。实际的中断服务函数都需要我们重新编写，为了方便管理我们把中断服务函数统一写在 stm32f10x_it.c 这个库文件中。

<file_sep>#include "stm32f10x.h"

void LED_GPIO_Config(void);

languages: Markdown C


text:
<repo_name>kanchitbajaj8070/HuffmanEncoding<file_sep>/src/Client.java
import java.util.HashSet;

public class Client {
    public static void main(String[] args) {
        HuffmanEncoder encoder= new HuffmanEncoder();
        StringBuilder sb= new StringBuilder();
        for (int i = 1; i <=60 ; i++) {
            sb.append('a');
            if(i<=30)
            sb.append("b");
            if(i<=8)
                sb.append('c');
            if(i<=2)
                sb.append('d');
        }

        encoder.buildHuffmanEncoder(sb.toString());
        String encodedString=encoder.EncodeString(sb.toString());
        System.out.println(encodedString);
        String decodedString=encoder.DecodeString(encodedString);
        System.out.println(decodedString);
    }

}

repo_language: Java


text:
<repo_name>yutasano0121/codewars<file_sep>/phonebook.py
import re

def phone(strng, num):
    pattern_num = ('[^|\n].*?' num '.*?[\n|$]')
    pattern_name = '<(.*?)>'
    pattern_address =
    match = re.findall(pattern_num, string)

    if len(match) == 0:
        return ("Error => Not found: " num)
    elif len(match) > 1:
        return ("Error => Too many people: " num)
    else:
        name = re.search(pattern_name, match[0]).group(1)
        line = re.sub(('\+' pattern_num), '', match[0])
        line = re.sub(pattern_name, '', line)
        line = re.sub([^A-Za-z\.-], ' ', line)
        address = ' '.join(line).split()

# [^] and (?!pattern) for negative selection

    # your code
<file_sep>/pokerhand.py
"""
A famous casino is suddenly faced with a sharp decline of their revenues. They decide to offer Texas hold'em also online. Can you help them by writing an algorithm that can rank poker hands?

Task
Create a poker hand that has a method to compare itself to another poker hand:

compare_with(self, other_hand)
A poker hand has a constructor that accepts a string containing 5 cards:

PokerHand("KS 2H 5C JD TD")
The characteristics of the string of cards are:

Each card consists of two characters, where
The first character is the value of the card: 2, 3, 4, 5, 6, 7, 8, 9, T(en), J(ack), Q(ueen), K(ing), A(ce)
The second character represents the suit: S(pades), H(earts), D(iamonds), C(lubs)
A space is used as card separator between cards
The result of your poker hand compare can be one of these 3 options:

[ "Win", "Tie", "Loss" ]
Notes
Apply the Texas Hold'em rules for ranking the cards.
Low aces are NOT valid in this kata.
There is no ranking for the suits.
If you finished this kata, you might want to continue with Sortable Poker Hands
"""

class PokerHand(object):

    RESULT = ["Loss", "Tie", "Win"]

    def __init__(self, hand):
        self.hand = hand.split()
        self.nums = sorted([int(c[0].translate(str.maketrans({
            'A': '14', 'T': '10', 'J': '11', 'Q': '12', 'K': '13'
        }))) - 1 for c in self.hand])
        self.suits = [c[1] for c in self.hand]

        unique_nums = set(self.nums)
        unique_suits = set(self.suits)

        score = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

        if len(unique_suits) == 1:
            score[4] = 1  # flush
        if len(unique_nums) == 5:
            if self.nums[0] + 4 == self.nums[4] or self.nums in [
                [1,2,3,4,13],[1,2,3,12,13],[1,2,11,12,13],[1,10,11,12,13]
            ]:
                score[5] = 1  # straight
            else:
                score[9] = 1  # no pair
        if len(unique_nums) == 4:
            score[8] = 1  # one pair
        if len(unique_nums) == 3:
            if 3 in [self.nums.count(i) for i in tuple(unique_nums)]:
                score[6] = 1  # three card
            else:
                score[7] = 1  # two pair
        if len(unique_nums) == 2:
            if self.nums.count(tuple(unique_nums)[1]) == 2 | 3:
                score[3] = 1  # full house
            else:
                score[2] = 1  # four card
        if score[4:5 + 1] == [1, 1]:
            if self.nums[0] == 9:
                score[0] = 1  # royal flush
            else:
                score[1] = 1  # straight flush

        self.score = score.index(1)

    def compare_with(self, other):
        if self.score < other.score:
            return('Win')
        elif self.score > other.score:
            return("Loss")
        # same score below
        elif self.score == 0:
            return("Tie")
        elif self.score == 1 | 5 | 9:
            if self.nums[4] > other.nums[4]:
                return('Win')
            if self.nums[4] < other.nums[4]:
                return('Loss')
            if self.nums[4] == other.nums[4]:
                return('Tie')
        else:
            return('Tie')

# Dealing with 'Tie' incomplete...

class PokerHand_answer(object):
    CARD = "23456789TJQKA"
    RESULT = ["Loss", "Tie", "Win"]

    def __init__(self, hand):
        values = ''.join(sorted(hand[::3], key=self.CARD.index))
        suits = set(hand[1::3])
        is_straight = values in self.CARD
        is_flush = len(suits) == 1
        self.score = (2 * sum(values.count(card) for card in values)
                      + 13 * is_straight + 15 * is_flush,
                      [self.CARD.index(card) for card in values[::-1]])

    def compare_with(self, other):
        return self.RESULT[(self.score > other.score) - (self.score < other.score) + 1]

hand = "2H 3H 4H 5H 6H"
print(PokerHand_answer(hand).score)
others = (38, [0, 3, 2, 1, 0])
print(PokerHand_answer(hand).score > others)
<file_sep>/stringsmix.py
"""
Given two strings s1 and s2, we want to visualize how different the two strings are. We will only take into account the lowercase letters (a to z). First let us count the frequency of each lowercase letters in s1 and s2.

s1 = "A aaaa bb c"

s2 = "& aaa bbb c d"

s1 has 4 'a', 2 'b', 1 'c'

s2 has 3 'a', 3 'b', 1 'c', 1 'd'

So the maximum for 'a' in s1 and s2 is 4 from s1; the maximum for 'b' is 3 from s2. In the following we will not consider letters when the maximum of their occurrences is less than or equal to 1.

We can resume the differences between s1 and s2 in the following string: "1:aaaa/2:bbb" where 1 in 1:aaaa stands for string s1 and aaaa because the maximum for a is 4. In the same manner 2:bbb stands for string s2 and bbb because the maximum for b is 3.

The task is to produce a string in which each lowercase letters of s1 or s2 appears as many times as its maximum if this maximum is strictly greater than 1; these letters will be prefixed by the number of the string where they appear with their maximum value and :. If the maximum is in s1 as well as in s2 the prefix is =:.

In the result, substrings (a substring is for example 2:nnnnn or 1:hhh; it contains the prefix) will be in decreasing order of their length and when they have the same length sorted in ascending lexicographic order (letters and digits - more precisely sorted by codepoint); the different groups will be separated by '/'. See examples and "Example Tests".

Hopefully other examples can make this clearer.

s1 = "my&friend&Paul has heavy hats! &"
s2 = "my friend John has many many friends &"
mix(s1, s2) --> "2:nnnnn/1:aaaa/1:hhh/2:mmm/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"

s1 = "mmmmm m nnnnn y&friend&Paul has heavy hats! &"
s2 = "my frie n d Joh n has ma n y ma n y frie n ds n&"
mix(s1, s2) --> "1:mmmmmm/=:nnnnnn/1:aaaa/1:hhh/2:yyy/2:dd/2:ff/2:ii/2:rr/=:ee/=:ss"

s1="Are the kids at home? aaaaa fffff"
s2="Yes they are here! aaaaa fffff"
mix(s1, s2) --> "=:aaaaaa/2:eeeee/=:fffff/1:tt/2:rr/=:hh"
"""

import re

def mix(str1, str2):
    lower_dict = {}
    ids = ['1', '2', '=']

    # make a dict{letter: (count, id)}
    for i in (0, 1):
        str = (str1, str2)[i]
        lowers = re.findall(r'[a-z]', str)
        lower_set = set(lowers)

        for c in lower_set:
            if lowers.count(c) > 1:
                try:
                    if lowers.count(c) > lower_dict[c][0]:
                        lower_dict[c] = (lowers.count(c), i)  # replace
                    elif lowers.count(c) == lower_dict[c][0]:
                        lower_dict[c] = (lowers.count(c), 2)  # '='
                except:
                    lower_dict[c] = (lowers.count(c), i)

    # reverse the dict to dict{count: (letter, id)}
    dict_rev = {}
    for key in lower_dict:
        c = lower_dict[key][0]
        id = lower_dict[key][1]
        try:
            dict_rev[c][key] = id  # if dict has 'c' entry
        except:
            dict_rev[c] = {key: id}

    out = []

    for num in dict_rev:
        out_sub = []
        for c in dict_rev[num]:
            out_sub.append('{}:{}'.format(ids[dict_rev[num][c]], c * num))
        out_sub.sort()
        out.append((num, out_sub))
    out.sort(reverse=True)
    out = [j for i in out for j in i[1]]
    print(out)
    out = '/'.join(out)
    return(out)

print(mix("Are they here", "yes, they are here"))

def mix_answer1(s1, s2):
    hist = {}
    for ch in "abcdefghijklmnopqrstuvwxyz":
        val1, val2 = s1.count(ch), s2.count(ch)
        if max(val1, val2) > 1:
            which = "1" if val1 > val2 else "2" if val2 > val1 else "="
            hist[ch] = (-max(val1, val2), which + ":" + ch * max(val1, val2))
    return "/".join(hist[ch][1] for ch in sorted(hist, key=lambda x: hist[x]))

from collections import Counter

def mix_answer2(s1, s2):
    c1 = Counter(filter(str.islower, s1))
    c2 = Counter(filter(str.islower, s2))
    res = []
    for c in set(c1.keys() + c2.keys()):
        n1, n2 = c1.get(c, 0), c2.get(c, 0)
        if n1 > 1 or n2 > 1:
            res.append(('1', c, n1) if n1 > n2 else
                ('2', c, n2) if n2 > n1 else ('=', c, n1))
    res = ['{}:{}'.format(i, c * n) for i, c, n in res]
    return '/'.join(sorted(res, key=lambda s: (-len(s), s)))
<file_sep>/spiralize.py
import numpy as np

def test(n, start_index=0):
    if start_index == 0:
        global a
        a = np.zeros((n, n))
    start = start_index
    end = start + n - 1  # index

    if n == 1:
        a[start, start] = 1
    elif n == 2:
        a[start, start:end + 1] = 1
        a[end, end] = 1
    elif n == 3:
        a[start, start:end + 1] = 1
        a[start:end + 1, end] = 1  # right
        a[end, start:end + 1] = 1  # bottom
    elif n == 4:
        a[start, start:end + 1] = 1
        a[start:end + 1, end] = 1  # right
        a[end, start:end + 1] = 1  # bottom
        a[start + 2, start] = 1  # left
    else:
        a[start, start:end + 1] = 1  # top
        a[start + 2:end + 1, start] = 1  # left
        a[start:end + 1, end] = 1  # right
        a[end, start:end + 1] = 1  # bottom
        a[start + 2, start + 1] = 1
        test(n - 4, start + 2)

    return a

print(test(13))
<file_sep>/binaryMultiple3.py
import re

pattern_answer = re.compile(r'^(0|1(01*0)*1)*$')

# same number of even and odd position 1
# multiple of 3 even and odd 1
0*(1(00)*1)*0*|(1(00)*1)*{3}0*|(10)*{3}
<file_sep>/sumDigPower.py
"""
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details

8 + 1 = 9 and 92 = 81

512 = 5 + 1 + 2 = 8 and 83 = 512

We need to make a function, power_sumDigTerm(), that receives a number n and may output the n-th term of this sequence of numbers. The cases we presented above means that

power_sumDigTerm(1) == 81

power_sumDigTerm(2) == 512

Happy coding!
"""

def power_sumDigTerm(n):
    #your code here
    count = 0
    num = 81
    while num:
        sumDig = sum([int(i) for i in str(num)])
        if sumDig in (0, 1):
            num += 1
        else:
            num_sub = num
            while num_sub % sumDig == 0:
                num_sub = num_sub / sumDig
            if num_sub == 1:
                count += 1
                if count == n:
                    return num
            num += 1

# Return a runtime error when big numbers are fed.

# model answer
series = [0]
for a in range(2, 99):
    for b in range(2, 42):
        c = a**b
        if a == sum(map(int, str(c))):
            series.append(c)
power_sumDigTerm = sorted(series).__getitem__
<file_sep>/justify.py
def justify(text, width):
    words = text.split()
    line = []
    lines = ''
    length = 0
    for i in range(len(words)):
        w = words[i]
        if line == []:  # first word in the line
            length += len(w)
            if length < width:
                line.append(w)
            else:  # long word
                lines = lines + w + '\n'
                length = 0
        else:
            length += len(w) + 1  # + 1 for a space
            if length < width:
                line.append(w)
            else:
                space = width - len(''.join(line))  # space to fill
                num_words = len(line)  # num of words in the line
                if num_words == 1:
                    lines = lines + line[0] + '\n'
                else:
                    num_space = [int(space / (num_words - 1))] * (num_words - 1)  # spaces per word
                    count = space % num_words
                    while count > 0:
                        for j in range(len(num_space)):
                            num_space[j] += 1
                            count -= 1
                    num_space += [0]  # make it the same length as num_words
                    for j in range(num_words):
                        lines = lines + line[j] + ' ' * num_space[j]
                    lines += '\n'

                length = len(w)
                if length < width:
                    line = [w]
                else:  # long word
                    lines = lines + w + '\n'
                    length = 0

        if i == len(words) - 1:  # last word
            lines += ' '.join(line)

    print(lines)
    return lines

justify('123 45 6', 7)

def justify_answer(text, width):
    length = text.rfind(' ', 0, width+1)
    if length == -1 or len(text) <= width:
        return text
    line = text[:length]
    spaces = line.count(' ')
    if spaces != 0:
        expand = (width - length) / spaces + 1
        extra = (width - length) % spaces
        line = line.replace(' ', ' '*expand)
        line = line.replace(' '*expand, ' '*(expand+1), extra)
    return line + '\n' + justify(text[length+1:], width)
<file_sep>/snail.py
"""
Snail Sort
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

array = [[1,2,3],
         [4,5,6],
         [7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:

array = [[1,2,3],
         [8,9,4],
         [7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
"""

array = [[1,2,3],
         [4,5,6],
         [7,8,9]]

def snail_answer1(array):
    a = []
    while array:
        a.extend(list(array.pop(0)))
        array = list(zip(*array))

        array.reverse()
        print(array)
    return a

snail_answer1(array)

def snail_answer2(array):
    return list(array[0]) + snail(zip(*array[1:])[::-1]) if array else []
<file_sep>/kprimers.py
"""
A natural number is called k-prime if it has exactly k prime factors, counted with multiplicity. For example:

k = 2  -->  4, 6, 9, 10, 14, 15, 21, 22, ...
k = 3  -->  8, 12, 18, 20, 27, 28, 30, ...
k = 5  -->  32, 48, 72, 80, 108, 112, ...
A natural number is thus prime if and only if it is 1-prime.

Task:
Complete the function count_Kprimes (or countKprimes, count-K-primes, kPrimes) which is given parameters k, start, end (or nd) and returns an array (or a list or a string depending on the language - see "Solution" and "Sample Tests") of the k-primes between start (inclusive) and end (inclusive).

Example:
countKprimes(5, 500, 600) --> [500, 520, 552, 567, 588, 592, 594]
Notes:

The first function would have been better named: findKprimes or kPrimes :-)
In C some helper functions are given (see declarations in 'Solution').
For Go: nil slice is expected when there are no k-primes between start and end.
Second Task (puzzle):
Given a positive integer s, find the total number of solutions of the equation a + b + c = s, where a is 1-prime, b is 3-prime, and c is 7-prime.

Call this function puzzle(s).

Examples:
puzzle(138)  -->  1  because [2 + 8 + 128] is the only solution
puzzle(143)  -->  2  because [3 + 12 + 128] and [7 + 8 + 128] are the solutions
"""

from math import sqrt

def count_Kprimes(k, start, end):
    def find_prime_num(i):
        if i == 0:
            return 0
        p = []
        p_add = p.append
        while i % 2 == 0:
            i = i / 2
            p_add(2)
        for j in range(3, int(sqrt(i) + 1), 2):
            while i % j == 0:
                i = i / j
                p_add(j)
        if i > 1:
            p_add(i)
        return len(p)
    return [i for i in range(start, end + 1) if find_prime_num(i) == k]

def puzzle(s):
    if s < 138:
        return 0
    count = 0
    prime7 = count_Kprimes(7, 128, s - 10)
    for i in prime7:
        prime3 = count_Kprimes(3, 8, s - i)
        for j in prime3:
            prime1 = count_Kprimes(1, s - i - j, s - i - j)
            if prime1 != []:
                count += 1
    return count
    # your code

print(puzzle(138))

def count_Kprimes_answer(k, start, end):
    return [n for n in range(start, end+1) if find_k(n) == k]

def puzzle_answer(s):
    a = count_Kprimes_answer(1, 0, s)
    b = count_Kprimes_answer(3, 0, s)
    c = count_Kprimes_answer(7, 0, s)

    return sum(1 for x in a for y in b for z in c if x + y + z == s)

def find_k(n):
    res = 0
    i = 2
    while i * i <= n:
        while n % i == 0:
            n //= i
            res += 1
        i += 1
    if n > 1: res += 1
    return res
<file_sep>/esolang3.py
def interpreter(code, iterations, width, height):
    grid = [[0] * width for x in range(height)]
    w = 0
    h = 0  # height and width
    count = 0
    valid_chars = ['n', 'e', 's', 'w', '*', '[', ']']
    operation = {
        'n': [-1, 0],
        'e': [0, 1],
        's': [1, 0],
        'w': [0, -1]
    }
    slide = 0  # activate when bracket is present
    skip = False
    for i in range(len(code)):
        if count < iterations:
            cursor = i - slide
            char = code[cursor]
            if not skip:
                if not char in valid_chars:
                    continue
                elif char == '[':
                    bracket_loc = i
                    if grid[h][w] == 0:
                        skip = True
                    count += 1
                elif char == ']':
                    if grid[h][w] == 1:
                        slide = i - bracket_loc
                    count += 1
                elif char == "*":
                    if grid[h][w] == 1:
                        grid[h][w] = 0
                    else:
                        grid[h][w] = 1
                    count += 1

                else:
                    move = operation[char]
                    w = (w + move[1]) % width
                    h = (h + move[0]) % height
                    count += 1
            else:
                if char == "]":
                    skip = False
    out = '\r\n'.join(
        [''.join([str(i) for i in grid[j]]) for j in range(len(grid))]
    )
    return out

out = interpreter("*e*e*e*es*es*ws*ws*w*w*w*n*n*n*ssss*s*s*s*", 0, 6, 9)
print(out)

def interpreter_answer(code, iterations, width, height):
    code = "".join(c for c in code if c in "[news]*")
    canvas = [ [0] * width for _ in range(height) ]
    row = col = step = count = loop = 0

    while step < len(code) and count < iterations:
        command = code[step]

        if loop:
            if   command == "[": loop += 1
            elif command == "]": loop -= 1

        elif command == "n": row = (row - 1) % height
        elif command == "s": row = (row + 1) % height
        elif command == "w": col = (col - 1) % width
        elif command == "e": col = (col + 1) % width
        elif command == "*": canvas[row][col] ^= 1
        elif command == "[" and canvas[row][col] == 0: loop += 1
        elif command == "]" and canvas[row][col] != 0: loop -= 1

        step += 1 if not loop else loop // abs(loop)
        count += 1 if not loop else 0

    return "\r\n".join("".join(map(str, row)) for row in canvas)
<file_sep>/magnet_box.py
"""
Professor <NAME> just discovered a new type of magnet material. He put particles of this material in a box made of small boxes arranged in K rows and N columns as a kind of 2D matrix K x N where K and N are postive integers. He thinks that his calculations show that the force exerted by the particle in the small box (k, n) is:

v(k, n) = \frac{1}{k(n+1)^{2k}}

The total force exerted by the first row with k = 1 is:

u(1, N) = \sum_{n=1}^{n=N}v(1, n) = \frac{1}{1.2^2} + \frac{1}{1.3^2}+...+\frac{1}{1.(N+1)^2}

We can go on with k = 2 and then k = 3 etc ... and consider:

S(K, N) = \sum_{k=1}^{k=K}u(k, N) = \sum_{k=1}^{k=K}(\sum_{n=1}^{n=N}v(k, n)) \rightarrow (doubles(maxk, maxn))

Task:
To help Professor Chambouliard can we calculate the function doubles that will take as parameter maxk and maxn such that doubles(maxk, maxn) = S(maxk, maxn)? Experiences seems to show that this could be something around 0.7 when maxk and maxn are big enough.

Examples:
doubles(1, 3)  => 0.4236111111111111
doubles(1, 10) => 0.5580321939764581
doubles(10, 100) => 0.6832948559787737
Notes:
In u(1, N) the dot is the multiplication operator.

Don't truncate or round: Have a look in "RUN EXAMPLES" at "assertFuzzyEquals".
"""

def assertFuzzyEquals(actual, expected, msg=""):
    merr = 1e-6
    inrange = abs(actual - expected) <= merr
    if (inrange == False):
        msg = "At 1e-6: Expected value must be {:0.6f} but got {:0.6f}"
        msg = msg.format(expected, actual)
    return Test.expect(inrange, msg)

def doubles(maxk, maxn):
    out = 0
    for k in range(1, maxk + 1):
        for n in range(1, maxn + 1):
            out_add = 1 / (k * ((n + 1) ** (2 * k)))
        if out_add < 1e-100:  # without this causes RTE
            return out
        out += out_add
    return out
    # your code

print(doubles(1, 100000))

def doubles_answer(maxk, maxn):
    out = sum([
        sum([
            (n+1)**(-2*k) for n in range(1, maxn+1)
        ]) / k for k in range(1, maxk+1)
    ])  # sum and inline list seems much faster than nested for loops
<file_sep>/denico.py
"""
Task
Write a function deNico/de_nico() that accepts two parameters:

key/$key - string consists of unique letters and digits
message/$message - string with encoded message
and decodes the message using the key.

First create a numeric key basing on the provided key by assigning each letter position in which it is located after setting the letters from key in an alphabetical order.

For example, for the key crazy we will get 23154 because of acryz (sorted letters from the key).
Let's decode cseerntiofarmit on using our crazy key.

1 2 3 4 5
---------
c s e e r
n t i o f
a r m i t
  o n
After using the key:

2 3 1 5 4
---------
s e c r e
t i n f o
r m a t i
o n
Notes
The message is never shorter than the key.
Don't forget to remove trailing whitespace after decoding the message
Examples
deNico("crazy", "cseerntiofarmit on  ") => "secretinformation"
deNico("abc", "abcd") => "abcd"
deNico("ba", "2143658709") => "1234567890"
deNico("key", "eky") => "key"
"""

import numpy as np
import re
from math import floor

def de_nico(key,msg):
    key_len = len(key)
    msg_len = len(msg)
    chunk = []
    chunk_decode = []
    for i in range(floor(msg_len / key_len)):
        chunk.append(msg[i * key_len:(i + 1) * key_len])
    if msg_len % key_len != 0:
        chunk.append(msg[(i + 1) * key_len:])

    # fetch the order
    ord = np.argsort(np.argsort([i for i in key]))

    for w in chunk:
        for i in range(len(ord)):
            try:
                chunk_decode.append(w[ord[i]])  # if not out of range
            except:
                continue
        print(w)
        print(ord)
    out = ''.join(chunk_decode)
    out = re.search('(.*?)\s*$', out).group(1)  # remove trailing ' '
    return out

print(de_nico('fsmrpw', 'uvdvxlccwiyppremwbsbaq'))

def de_nico_answer(key, msg):
    ll = len(key)
    order = [sorted(key).index(c) for c in key]
    s = ''

    while msg:
        s = s + ''.join(msg[i] for i in order if i < len(msg))  # reorder a chunk
        msg = msg[ll:]  # move to the next chunk
    return s.strip()  # remove trailing ' '
<file_sep>/partition.py
"""
In number theory and combinatorics, a partition of a positive integer n, also called an integer partition, is a way of writing n as a sum of positive integers. Two sums that differ only in the order of their summands are considered the same partition. If order matters, the sum becomes a composition. For example, 4 can be partitioned in five distinct ways:
4
3 + 1
2 + 2
2 + 1 + 1
1 + 1 + 1 + 1
"""

def exp_sum_answer(n):
  if n < 0:
    return 0
  dp = [1]+[0]*n
  for num in xrange(1,n+1):
    for i in xrange(num,n+1):
      dp[i] += dp[i-num]
  return dp[-1]
<file_sep>/proper_fraction.py
from math import sqrt
def proper_fractions(n):
    if n <= 1:
        return 0

    def find_prime_factors(i):
        p = []
        p_add = p.append
        if i % 2 == 0:  # if even
            p_add(2)
            while i % 2 == 0:
                i = i / 2
        if i == 1:
            return p
        for j in range(3, round(sqrt(i)) + 1, 2):
            if i % j == 0:
                p_add(j)
                while i % j == 0:
                    i = i / j
        if i > 2:
            p_add(i)
        return p
    p = find_prime_factors(n)
    if n % 2 == 0:
        d = [i for i in range(1, n, 2) if sum(map(lambda x: i % x == 0, p)) == 0]
    else:
        d = [i for i in range(1, n) if sum(map(lambda x: i % x == 0, p)) == 0]

    return(len(d))
    #your code here
print(proper_fractions(15))
# returns RTE

def proper_fractions_answer(n):
    phi = n > 1 and n  # assign n if condition else assign False
    for p in range(2, int(n ** .5) + 1):  # ** .5 equals sqrt()
        if not n % p:  # if n % p == 0
            phi -= phi // p
            while not n % p:
                n //= p
    if n > 1:
        phi -= phi // n
    return phi

# Euler's totient formula?
<file_sep>/simpleEvents.py
"""
Your goal is to write an Event constructor function, which can be used to make event objects.

An event object should work like this:

it has a .subscribe() method, which takes a function and stores it as its handler
it has an .unsubscribe() method, which takes a function and removes it from its handlers
it has an .emit() method, which takes an arbitrary number of arguments and calls all the stored functions with these arguments
As this is an elementary example of events, there are some simplifications:

all functions are called with correct arguments (e.g. only functions will be passed to unsubscribe)
you should not worry about the order of handlers' execution
the handlers will not attempt to modify an event object (e.g. add or remove handlers)
the context of handlers' execution is not important
each handler will be subscribed at most once at any given moment of time. It can still be unsubscribed and then subscribed again
Also see an example test fixture for suggested usage
"""
"""
# Tests
event = Event()

class Testf():
    def __init__(self):
        self.calls=0
        self.args=[]
    def __call__(self,*args):
        self.calls+=1
        self.args+=args

f=Testf()

event.subscribe(f)
event.emit(1, 'foo', True)

Test.assert_equals(f.calls, 1) #calls a handler
Test.assert_equals(f.args, [1, 'foo', True]) #passes arguments

event.unsubscribe(f)
event.emit(2)

Test.assert_equals(f.calls, 1) #no second call
"""

class Event():
    def __init__(self):
        self.func = set()

    def subscribe(self, func):
        self.func.add(func)

    def unsubscribe(self, func):
        self.func.discard(func)

    def emit(self, *args):
        for i in self.func:
            i(*args)
    #your code here
<file_sep>/VigenèreCipher.py
from math import ceil

class VigenereCipher(object):
    def __init__(self, key, alphabet):
        self.key = key
        self.alphabet = alphabet

    def encode(self, text):
        text_len = len(text)
        pass_len = len(self.key)
        password2 = self.key * ceil(len(text) / len(self.key))

        new_word = []
        for i in range(len(text)):
            try:
                shifted = self.alphabet.index(text[i]) + self.alphabet.index(password2[i])
                shifted = shifted % len(self.alphabet)
                new_word.append(self.alphabet[shifted])
            except ValueError:
                new_word.append(text[i])
        return(''.join(new_word))

    def decode(self, text):
        text_len = len(text)
        pass_len = len(self.key)
        password2 = self.key * ceil(len(text) / len(self.key))

        new_word = []
        for i in range(len(text)):
            try:
                shifted = self.alphabet.index(text[i]) - self.alphabet.index(password2[i])
                shifted = shifted % len(self.alphabet)
                new_word.append(self.alphabet[shifted])
            except ValueError:
                new_word.append(text[i])
        return(''.join(new_word))
<file_sep>/README.md
# Python scripts for Codewars
### Model answers were appended at the end of each script.
<file_sep>/carpark.py
"""
Task
 	Your task is to escape from the carpark using only the staircases provided to reach the exit. You may not jump over the edge of the levels (you’re not Superman!) and the exit is always on the far right of the ground floor.
Rules
 	1. You are passed the carpark data as an argument into the function.
2. Free carparking spaces are represented by a 0
3. Staircases are represented by a 1
4. Your parking place (start position) is represented by a 2
5. The exit is always the far right element of the ground floor.
6. You must use the staircases to go down a level.
7. You will never start on a staircase.
8. The start level may be any level of the car park.
9. Each floor will have only one staircase apart from the ground floor which will not have any staircases.
Returns
 	Return an array of the quickest route out of the carpark
R1 = Move Right one parking space.
L1 = Move Left one parking space.
D1 = Move Down one level.
Example
Initialise
carpark = [[1, 0, 0, 0, 2],
           [0, 0, 0, 0, 0]]
Working Out
You start in the most far right position on level 1
You have to move Left 4 places to reach the staircase => "L4"
You then go down one flight of stairs => "D1"
To escape you have to move Right 4 places => "R4"
Result
result = ["L4", "D1", "R4"]
"""

def escape(carpark):
    out = []  # output list
    floor_num = len(carpark)  # number of floors

    for i in range(floor_num):
        if 2 in carpark[i]:
            start_floor = i  # floor of the starting location
            loc = carpark[start_floor].index(2)  # starting location
            break

    stair_num = 0  # number of consecutive stairs
    for i in range(start_floor, floor_num):
        floor = carpark[i]  # current floor

        if i == floor_num - 1:  # ground floor
            exit = len(floor) - 1
            if loc == exit:
                return out
            else:
                out.append("R" + str(exit - loc))
                return out

        stair = floor.index(1)

        if stair_num > 0:  # when located at a staircase
            if stair == loc:
                stair_num += 1
                out[-1] = 'D' + str(stair_num)
                continue
            else:
                stair_num = 0

        if loc > stair:
            out.append('L' + str(loc - stair))
        else:
            out.append('R' + str(stair - loc))
        out.append('D1')  # down a staircase

        stair_num = 1
        loc = stair

languages: Markdown Python


text:
<file_sep># funktion-nats-example
A funktion java example showing funktion being used with NATs messaging

repo_name: rajdavies/funktion-nats-example


text: <file_sep>c'est un petit test prérentrée pour voir si mon setup peut etre viable a l'école


text:
<file_sep>library(shiny)
library(googlesheets4)
library(googledrive)

# UI ----------------------------------------------------------------------------
ui <- fluidPage(
  titlePanel("Downloading Data"),
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset", "Choose a dataset:",
                  choices = c('每日資訊','發病日','新確診數','死亡數','地圖',
                              '地圖2','人口數(110.04)','檢驗量','估算死亡個數',
                              'ICU','Mechanical ventilation','mortality risk',
                              'literature-SEVERE','literature-LIFT','progression',
                              'severe not by age','醫療院所病床數','三高盛行率','hospitalized')),
      # Button
      downloadButton("downloadData", "Download")),
    # Main panel for displaying outputs ----
    mainPanel(
      tableOutput("table"))
  ))

# server ----------------------------------------------------------------------
server <- function(input, output) {
  outtbl<- reactive({
    req(input$dataset)
    googlesheets4::read_sheet('https://docs.google.com/spreadsheets/d/1mLKyntxDWUV1LDDfdNN3tnk2LA7UYnBmc8_t7WgVENQ/edit#gid=1946089651',
                              sheet= input$dataset,
                              col_names= F, col_types= 'c')
  })
  # Table of selected dataset ---- content
  output$table <- renderTable({
    outtbl()
  })
  # Downloadable csv of selected dataset ----
  output$downloadData <- downloadHandler(
    filename = function() {
      paste(input$dataset, ".csv", sep = "")
    },
    content = function(file) {
      write.csv(outtbl(), file, row.names = FALSE)
    }
  )

}

# Create Shiny app ----
shinyApp(ui, server)

repo_language: R