text:
<repo_name>shubhamshuklaer/nvim_config<file_sep>/unmanaged/my_snippets/UltiSnips/plaintex.snippets
snippet set_ "set rep"
$\mathrm{$1}$
endsnippet

snippet bb_ "double lines"
$\mathbb{$1}$
endsnippet
<file_sep>/nvimrc
let g:nvim_config_dir = '~/.config/nvim'
call plug#begin(g:nvim_config_dir.'/plugged')
" Plug 'Shougo/deoplete.nvim'
" Plug 'mileszs/ack.vim'
" Plug 'kien/ctrlp.vim'
" Plug 'mattn/emmet-vim'
" Plug 'nathanaelkane/vim-indent-guides'
Plug 'fholgado/minibufexpl.vim'
Plug 'scrooloose/nerdcommenter'
" On-demand loading
Plug 'scrooloose/nerdtree', { 'on':  'NERDTreeToggle' }
Plug 'xuhdev/SingleCompile'
" Plug 'scrooloose/syntastic'
Plug 'vim-scripts/TaskList.vim'
Plug 'SirVer/ultisnips'
" Plug 'tpope/vim-abolish'
Plug 'ntpeters/vim-better-whitespace'
Plug 'easymotion/vim-easymotion'
Plug 'powerman/vim-plugin-viewdoc'
" Plug 'honza/vim-snippets'
Plug 'tpope/vim-surround'
Plug 'tpope/vim-repeat'
" Plug 'benekastah/neomake'
" Plug 'editorconfig/editorconfig-vim'
" Black Hole Redirection
" See wiki at https://github.com/svermeulen/vim-easyclip
Plug 'svermeulen/vim-easyclip'
" In favour of lightweight vim-airline
" Plug 'powerline/powerline'
Plug 'bling/vim-airline'
" Plug 'Shougo/unite.vim'
" Plug 'Rip-Rip/clang_complete'
" Unmanaged plugin (manually installed and updated)
Plug g:nvim_config_dir.'/unmanaged/my_snippets'
Plug g:nvim_config_dir.'/unmanaged/c_cpp_codepainter'
Plug g:nvim_config_dir.'/unmanaged/nvim-example-python-plugin'
call plug#end()

" If nvimrc is sourced twice the au commands will be added twice... this clears
" the au commands define before
autocmd!

syntax on
filetype on
filetype plugin indent on

" Nerd tree
let NERDTreeShowHidden=1
command! Nt pwd | NERDTreeToggle
" command! Ntc pwd | NERDTreeClose
" Keep closed when vim start
" let g:NERDTreeHijackNetrw=0
" Close tree after opning file
let g:NERDTreeQuitOnOpen = 1

" vim tab
" For python use spaces not tabs
set number
set cindent
set tabstop=4
set softtabstop=4
set shiftwidth=4
set shiftround
" Converts tab to spaces
set expandtab

" vim Nerd tree tabs
let g:nerdtree_tabs_focus_on_files=1
" let g:nerdtree_tabs_open_on_console_startup=1

" vim enable mouse
" No need of mouse
" set mouse=a

" Backspace
set backspace=indent,eol,start

" Folding"
set foldmethod=indent
set foldlevel=99
hi Folded ctermbg=grey
" Searching
set incsearch "incremental search

" auto indent according to c indent standard
set cindent

" Single compile
" You may find that your ~/.vimrc doesn't support mapping |, or \|. In these
" cases, try using <bar> instead.
nmap <F9> :update <bar> SCCompile <CR>
nmap <F10> :update <bar> SCCompileRun <CR>
" ctrlp fuzzy open
let g:ctrlp_map = '<c-p>'
let g:ctrlp_cmd = 'CtrlP'
let g:ctrlp_working_path_mode = 'ra'
set wildignore+=*/tmp/*,*.so,*.swp,*.zip
let g:ctrlp_custom_ignore = {
  \ 'dir':  '\v[\/]\.(git|hg|svn)$',
  \ 'file': '\v\.(exe|so|dll)$',
  \ 'link': 'some_bad_symbolic_links',
  \ }

" colum and row number in status bar
set ruler

" single compile set default python compiler as python3
" Changing it back to default puthon2
" call SingleCompile#ChooseCompiler('python', 'python3')
" single compile template for lex
call SingleCompile#SetCompilerTemplate('lex', 'flex', 'flex', 'flex', '-o $(FILE_TITLE)$.yy.c', '')
call SingleCompile#SetOutfile('lex', 'flex', '$(FILE_TITLE)$.yy.c')
call SingleCompile#ChooseCompiler('lex', 'flex')

" Single compile template for markdown
call SingleCompile#SetCompilerTemplate('markdown', 'markdown', 'markdown', 'markdown', '$(FILE_NAME)$ > $(FILE_TITLE)$.html','')
call SingleCompile#SetOutfile('markdown', 'markdown', '$(FILE_TITLE)$.html')
call SingleCompile#ChooseCompiler('markdown', 'markdown')

" Single compile template for using c++14
call SingleCompile#SetCompilerTemplate('cpp', 'g++',
                \'GNU C++ Compiler', 'g++', '-g -o $(FILE_TITLE)$ -std=c++14',
                \g:SingleCompile_common_run_command)

" Single compile template for markdown
" Open quickfix window if error
" let g:SingleCompile_showquickfixiferror = 1
" annoying
let g:SingleCompile_showquickfixiferror = 0

" Set relative numbering
set relativenumber

" change file type of .md from modula2 to markdown
autocmd BufRead,BufNew *.md set filetype=markdown

" Trigger configuration Ultisnips
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<c-b>"
let g:UltiSnipsJumpBackwardTrigger="<c-z>"

" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"

" Disabling arrow keys
inoremap  <Up>     <NOP>
inoremap  <Down>   <NOP>
inoremap  <Left>   <NOP>
inoremap  <Right>  <NOP>
noremap   <Up>     <NOP>
noremap   <Down>   <NOP>
noremap   <Left>   <NOP>
noremap   <Right>  <NOP>

noremap h <NOP>
" noremap j <NOP>
" noremap k <NOP>
noremap l <NOP>
" noremap w <NOP>
" noremap W <NOP>
" noremap b <NOP>
" noremap B <NOP>
" noremap e <NOP>
" noremap E <NOP>

" Use <Leader><Leader>f or F instead from easymotion plugin
" noremap f <NOP>
" noremap F <NOP>

imap <ESC> <NOP>

" jk is faster than pressing esc
inoremap jk <ESC>

" mapping :W to :w
" ! is there to tell vim to replace these commands if they already exist
command! WQ wq
command! Wq wq
command! W w
command! Q q
command! Wqa wqa
command! WQa wqa
command! WQA wqa

" autoreload file if changed on disk
set autoread

" <F1> is for vim help
" <F2> to open vim cheatsheet
let nvim_cheatsheet_path=g:nvim_config_dir."/nvim_material/nvim_cheatsheet"
nnoremap <F2> :execute ":e " . nvim_cheatsheet_path<CR>
" <F3> the make command
nnoremap <F3> :Neomake!<CR>
" <F4> refresh ctags
nnoremap <F4> :!ctags -R .<CR>
" <F5> for refresh current file
nnoremap <F5> :e<CR>
" <F6> Gstatus
nnoremap <F6> :Gstatus<CR>
" <F7> Doxigen
nnoremap <F7> :Dox<CR>
" <F8> open custom snippet file curresponding to the file type
function! Open_corr_snippet()
    redir => snippet_file_name
    set filetype?
    redir END
    " snippet_file_name will contain eg.."   filetype=cpp" 3 spaces in front
    let snippet_file_name=snippet_file_name[12:]
    let snippet_file_name=":e ".g:nvim_config_dir."/unmanaged/my_snippets/UltiSnips/".snippet_file_name.".snippets"
    execute snippet_file_name
endfunction

nnoremap <F8> :call Open_corr_snippet()<CR>
" <F9> and <F10> are for Single compile plugin
" <F11> doesn't work
" <F12> is toggle paste

function! Toggle_paste()
    redir => paste_ret_val
    set paste?
    redir END
    let match_val=matchstr(paste_ret_val,'.*nopaste.*')
    if empty(match_val)
        set nopaste
        echom "Set to nopaste"
    else
        set paste
        echom "Set to paste"
    endif
endfunction

nnoremap <F12> :call Toggle_paste()<CR>

" to add a space after comment
let NERDSpaceDelims=1

" Use the system clipboard register by defaust
set clipboard=unnamedplus

" colour scheme
" set t_Co=256
" colors zenburn

" Set ultisnips triggers
let g:UltiSnipsExpandTrigger="<tab>"
let g:UltiSnipsJumpForwardTrigger="<tab>"
let g:UltiSnipsJumpBackwardTrigger="<s-tab>"

" Moving between splits
" Actuall its ctrl+w+movement but we are mapping it to
" ctrl+movement
map <c-j> <c-w>j
map <c-k> <c-w>k
map <c-l> <c-w>l
map <c-h> <c-w>h

" To open task list
map <leader>td <Plug>TaskList
" History
map <leader>g :GundoToggle<CR>
"" TODO fasdjfasdjj
" Supertab
au FileType python set omnifunc=pythoncomplete#Complete
let g:SuperTabDefaultCompletionType = "context"

" ACk
nmap <leader>a <Esc>:Ack!

" http://vim.wikia.com/wiki/Replace_a_builtin_command_using_cabbrev
" Function for mapping commands with lower case start letter
" :commnad only allow upper case start letter for user defined commands
" TODO learn how this function works
function! CommandCabbr(abbreviation, expansion)
  execute 'cabbr ' . a:abbreviation . ' <c-r>=getcmdpos() == 1 && getcmdtype() == ":" ? "' . a:expansion . '" : "' . a:abbreviation . '"<CR>'
endfunction
command! -nargs=+ CommandCabbr call CommandCabbr(<f-args>)
" Use it on itself to define a simpler abbreviation for itself.
CommandCabbr ccab CommandCabbr
" This method is better cause it preserves the completion for example
" E ~/home/shubham/hello.txt
call CommandCabbr("tabe","echom\ 'Please use buffers instead'")
call CommandCabbr("E","e")

" Reloading nvimrc automatically on save
" http://learnvimscriptthehardway.stevelosh.com/chapters/12.html
augroup reload_dotfiles " {
    autocmd!
    autocmd BufWritePost $MYVIMRC source $MYVIMRC
    " Can't do for bashrc and bash_aliases cause vim creates a sub-shell
    " autocmd BufUnload ~/.bashrc !source ~/.bashrc
    " autocmd BufUnload ~/.bash_aliases !source ~/.bash_aliases
augroup END " }

" If you select some lines then press > to indent the lines, the selection is
" removed. The indentation can be repeated on the same range using ., but if you
" still want to retain the visual selection after having pressed > or <, you can
" use these mappings
" gv redoes the previous selection
vnoremap > >gv
vnoremap < <gv

" It hides buffers instead of closing them. This means that you can have
" unwritten changes to a file and open a new file using :e, without being
" forced to write or undo your changes first. Also, undo buffers and marks are
" preserved while the buffer is open.
set hidden

" Save read only file
" :w file_name will write to a file
" :w some_prog will pipe the output to stdin of someprog
cnoremap sudow w !sudo tee % >/dev/null

" Scratch no autohide
let g:scratch_autohide = 0

"CC for cclose
command! CC cclose
command! PC pclose

" Arduino
au BufRead,BufNewFile *.pde set filetype=arduino
au BufRead,BufNewFile *.ino set filetype=arduino

" IndentLine
" vertical line indentation
let g:indentLine_color_term = 239
let g:indentLine_color_gui = '#09AA08'
let g:indentLine_char = '│'

"Replace occurance of word under cursor
"map mapps in all mode :map mapps in insert and command mode
":vmap maps in visual mode
"replace in current line
"When you are in command mode <C-r><C-w> will paste the word under the cursor
"you can also use <C-r><C-w> to paste into replacement area and then edit that
:map <Leader>rl :s/\<<C-r><C-w>\>//gc
"replace in selection
"visual mode auto adds '<,'> in front
:vmap <Leader>rs :s/\<<C-r><C-w>\>//gc
:map! <Leader>rs :'<,'>s/\<<C-r><C-w>\>//gc
"replace in whole file
:map <Leader>ra :%s/\<<C-r><C-w>\>//gc

"Stripwhitespace from vim-better-whitespace plugin clean all trailing
"whitespaces in the file
:nnoremap <Leader>SW :StripWhitespace<CR>

"e nvimrc
:map <Leader>ev :e $MYVIMRC<CR>
"block visual
:map <Leader>bv <C-v>
" For saving and closing buffer at same time
" see :h :bar for help with what <bar> does... '|' is used to write multiple
" commands on the same line in command mode eg :w | :bd <bar> is actually used
" in nvimrc for that otherwise you will have to escape bar like \| to get its
" functionality
:map <Leader>sc :w <bar> :bd<CR>

" Search word
:map <Leader>sw /\<\>

"fswitch
"when bufenter happens for a cpp file this au command will set the
"fswitchdst and fswitchlocs variables of the plugin
"NOT-NEEDED present by default
" au! BufEnter *.cpp let b:fswitchdst = 'h' | let b:fswitchlocs = './'
:map <Leader>fr :FSSplitRight<CR>
:map <Leader>fh :FSHere<CR>

:map ]q :cnext<CR>
:map [q :cprev<CR>

" viewdoc plugin opn viewdoc as a new windo on topleft
" let g:viewdoc_open='topleft new'
" we can use vim window commands like
" :vertical ,:topleft or :to, :botright or :bo
let g:viewdoc_open='vertical bo new'
:map <Leader>tb :TagbarToggle<CR>

" If you have viminfo set, it will save local marks (a-z) by default. The '100
" tells Vim to save marks and other information for up to 100 files. The f1
" directive tells Vim to also save global marks (A-Z) when it exits. If you
" don't want Vim to do this, set it to f0 instead.
set viminfo='100,f1

"Open browser
let g:netrw_nogx = 1 " disable netrw's gx mapping.
nmap gx <Plug>(openbrowser-smart-search)
vmap gx <Plug>(openbrowser-smart-search)

" Use deoplete.
" let g:deoplete#enable_at_startup = 1

"No highlight on search
set nohlsearch

"Enabling c++14 syntax check for syntastic
let g:syntastic_cpp_compiler = 'g++'
let g:syntastic_cpp_compiler_options = ' -std=c++14'

:map <Leader>em :e ~/macros.cpp<CR>

" Comment in favour of airline
" http://got-ravings.blogspot.in/2008/08/vim-pr0n-making-statuslines-that-own.html
" set statusline=%t       "tail of the filename
" set statusline+=[%{strlen(&fenc)?&fenc:'none'}, "file encoding
" set statusline+=%{&ff}] "file format
" set statusline+=%h      "help file flag
" set statusline+=%m      "modified flag
" set statusline+=%r      "read only flag
" set statusline+=%y      "filetype
" set statusline+=%=      "left/right separator
" set statusline+=%c,     "cursor column
" set statusline+=%l/%L   "cursor line/total lines
" set statusline+=\ %P    "percent through file

let g:airline_section_z='%P : %l/%L : %c'

" Delete not cut
" http://stackoverflow.com/questions/11993851/vim-how-to-delete-not-cut
" Not needed I am using vim-easyclip plugin
" nnoremap <leader>d "_d
" vnoremap <leader>d "_d
" vnoremap <leader>p "_dP
<file_sep>/unmanaged/my_snippets/UltiSnips/cpp.snippets
snippet	code_chef "code_chef template" b
#include <iostream>
using namespace std;

int main(){
	ios_base::sync_with_stdio(false);

	int t$1;
	cin>>t;

	while(t){
		$2
		t--;
	}

	return 0;
}
endsnippet

snippet fori "fori"
for(int i=0; i<n$1;i++){
}
endsnippet

snippet { "{ complition"
{
    $1
}
endsnippet

snippet temp_code "temp c++ code"
#include<bits/stdc++.h>
using namespace std;

int main(){
	$1
	return 0;
}
endsnippet

snippet code_jam "code jam c++ template"
#include<bits/stdc++.h>

using namespace std;

int main(){
	int t,kase=1$1;
	cin>>t;
	while(kase<=t){
		$2
		cout << "Case #" << kase << ": " << ans << endl;
		kase++;
	}
	return 0;
}
endsnippet

languages:
Vim Snippet
Vim Script

repo_language: Vim Snippet


text:
<repo_name>DENG-FU/SmartImageView<file_sep>/README.md
# SmartImageView
很好用的开源框架，主要应用于Android的网络图片加载，如请求新闻客户端的图片加载。

branch_name: refs/heads/master

repo_language: Markdown

repo_name: DENG-FU/SmartImageView


text:
<file_sep>---
layout: post
title: 'Styfle For President'
date: 2021-02-19 23:17:16 +0000
categories: jekyll update
---

{% highlight js %}
for (let i = 0; i < 100; i++) {
    console.log("STYFLE FOR PRESIDENT")
}
{% endhighlight %}

repo_name: coetry/fast-jekyll-test


text:
<repo_name>jkingharman/rawtext_analyser<file_sep>/analyser.rb

$LOAD_PATH << '.'

require "menu.rb"

class Analyser

include Menu

attr_accessor :file, :selector, :subselector, :all, :all_without, :sen, :para, :avr

def initialize
  @file = ""
  @selector = 0
  @subselector = 0
  @all = 0
  @all_without = 0
  @sen = 0
  @para = 0
  @avr = 0
end

def selector
  @selector = 0
  until @selector >= 1 && @selector <= 4
    puts "Input:"
    @selector = gets.chomp.to_i
    bad_input unless @selector >= 1 && @selector <= 4
  end
end

def sub_selector
  @subselector = 0
  until @subselector >= 1 && @subselector <= 6
    puts "\n Input: \n"
    @subselector = gets.chomp.to_i
   bad_input unless @subselector >= 1 && @subselector <= 6
  end
end

def read_from
  read_from_m
  @file = File.read(gets.chomp + ".txt")
  puts "\n\n file loaded"
end

def write_to
  write_to_m
  puts "\n Write your files content here: \n "
  content = gets.chomp
  puts "\n What will the file's name be? \n "
  File.write(gets.chomp + ".txt", content)
end

def all_chars
  @all = @file.split("").length
  all_m
end

def all_chars_bar_space
  @all_without = @file.gsub(/\s+/,"").split("").length
  all_without_m
end

def sentence_count
  @sen = @file.split(/\.|\?|!/).length # Give the user notification of fragments and ellipse problem.
  sen_m
end

def para_count
  @para = @file.split("\n\n").length
  para_m
end

def average
  @avr = @file.gsub(/\s+/,"").split("").length / @file.split(/\.|\?|!/).length
  avr_m
end

# Add a percentage of fluff words function here.

def options
  until @selector == 4
    display_menu()
    selector()
  if @selector == 1
    read_from
  elsif @selector ==  2
    write_to
  elsif @selector == 3
    sub_menu
  elsif @selector == 4
    goodbye
  else
    bad_input
  end
  end
end

def sub_menu
  @subselector = 0
  until @subselector == 6
    sub_display_menu
    sub_selector
  if @subselector == 1
    all_chars
  elsif @subselector ==  2
    all_chars_bar_space
  elsif @subselector == 3
    sentence_count
  elsif @subselector == 4
    para_count
  elsif @subselector == 5
    average unless @file == ""
  elsif @subselector == 6
    puts "return to main menu."
  else
    bad_input
  end
  end
end

def init
  welcome
  options
end

end

analyser = Analyser.new
analyser.init

<file_sep>/menu.rb

$LOAD_PATH << '.'

module Menu

def welcome
puts "\n Welcome to your text analyser!"
end

def display_menu
puts "\n What would you like to do? \n\n Press 1 to read from file. \n\n Press 2 to write to file. \n\n Press 3 to access stats analysis. \n\n Press 4 to quit. \n"
end

def sub_display_menu
puts "\n Welcome to stats analysis. What to do? \n\n Press 1 to see a character count. \n\n Press 2 to see a character count excluding whitespace. \n\n Press 3 to see a sentence count. \n\n Press 4 to see a para count. \n\n Press 5 to see the avr. length of your sentences. \n\n Press 6 to return to the main menu. \n"
end

def write_to_m
puts "\n You want to write to a file. You must input the file's name and the content to transfer. Please do so carefully! \n"
end

def read_from_m
puts "\n You want to read from a file in this programme's directory. Be sure to enter the file name correctly! \n" \
end

def all_m
puts "\n There are #{@all} chars in your text. \n"
end

def all_without_m
puts "\n There are #{@all_without} chars in your text, discounting whitespace. \n"
end

def sen_m
puts "\n There are #{@sen} sentences in your text. \n"
end

def para_m
puts "\n There are #{@para} paragraphs in your text. \n"
end

def avr_m
puts "\n The mean length of your sentences is #{@avr}. \n"
end

def bad_input
puts "I can't understand your input :( Try again."
end

def goodbye
puts "\n You choose to quit. Thanks for using the text analyser."
end

end<file_sep>/README.md

### Text Analyser

#### Project: Working with files.

(WiP!) This is a command line text analyser. The programme can read from file, write to file and analyse what's read in. For example, it can tell a user how many characters their text has, what the average length of its sentences is, paragraph number, and more.

I started making the programme for two big reasons: to get some practice with regexs and to work with files. As it stands, the programme is not fully developed. I outline some of the things I hope to change/add with in-code comments.

languages: Markdown Ruby


text:
<repo_name>kelxvel/java<file_sep>/task7/ValidatorHTML.java
import java.util.Stack;
import java.util.regex.*;

public class ValidatorHTML {
    private static final Pattern tagPattern = Pattern.compile("<(.*?)>");

    /**
     * Checks the correctness of HTML code in terms of order of opening / closing tag.
     * Also prints tag name and position number in htmlCode where error found.
     * @param htmlCode HTML code to be validate
     * @return true if the htmlCode correct HTML in terms of order of opening / closing tag
     */
    public boolean validate(String htmlCode) {
        Matcher m = tagPattern.matcher(htmlCode);
        Stack<String> tags = new Stack<>();
        while (m.find()) {
            String tag = m.group();
            if (tag.startsWith("</")) {
                String element = getElementNameByTag(tag);
                if (!tags.empty()) {
                    String e = getElementNameByTag(tags.pop());
                    if (!e.equalsIgnoreCase(element)) {
                        System.out.println("Error in column " + htmlCode.indexOf(tag) + ": " + tag);
                        return false;
                    }
                } else {
                    System.out.println("Error in column " + htmlCode.indexOf(tag) + ": " + tag);
                    return false;
                }
            } else if (tag.endsWith("/>")) {
                continue;
            } else {
                tags.push(tag);
            }
        }
        if (!tags.empty()) {
            String tag = tags.pop();
            System.out.println("Error in column " + htmlCode.indexOf(tag) + ": missing closing tag for: " + tag);
            return false;
        }
        return true;
    }

    private static String getElementNameByTag(String tag) {
        if (tag.startsWith("</"))
            tag = tag.replaceFirst("</", "");
        else if (tag.startsWith("<"))
            tag = tag.replaceFirst("<", "");
        else
            return null;

        if (tag.endsWith("/>"))
            tag = tag.replaceAll("/>$", "");
        else if (tag.endsWith(">"))
            tag = tag.replaceAll(">$", "");
        else
            return null;

        return (tag.trim().split(" ", 2))[0];
    }

    public static void main(String[] args) {
        String[] testCode = {
                "
Hello world!
",
                "
Hello world!
",
                "
Hello world!"
        };
        ValidatorHTML validator = new ValidatorHTML();
        for (String c : testCode)
            System.out.println(validator.validate(c));
    }
}
<file_sep>/task6/HashMap.java
import java.util.*;
import java.util.Map.Entry;

/**
 * This class implements a hash table, which maps keys to values.
 * This implementantion permits <tt>null</tt> values and the <tt>null</tt> key.
 */
public class HashMap<K, V> {
    /**
     * The default initial capacity, used when none specified in constructor.
     */
    public static final int DEFAULT_INITIAL_CAPACITY = 16;

    /**
     * The maximum capacity,.
     */
    public static final int MAXIMUM_CAPACITY = 1073741824;

    /**
     * The load factor, used when none specified in constructor.
     */
    public static final float DEFAULT_LOAD_FACTOR = 0.75F;

    private Entry<K, V>[] table;

    private int size;
    private int threshold;
    private final float loadFactor;

    /**
     * Constructs an empty <tt>HashMap</tt> with the specified initial
     * capacity and load factor.
     *
     * @param  capacity the initial capacity
     * @param  loadFactor the load factor
     * @throws IllegalArgumentException if the initial capacity is negative
     *         or the load factor is nonpositive
     */
    public HashMap(int capacity, float loadFactor) {
        if (capacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " + capacity);
        if (capacity > MAXIMUM_CAPACITY)
            capacity = MAXIMUM_CAPACITY;
        if ((loadFactor <= 0.0F) || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " + loadFactor);

        this.size = 0;
        this.table = new Entry[capacity];
        this.loadFactor = loadFactor;
        this.threshold = (int) (capacity * loadFactor);
    }

    /**
     * Construct an empty <tt>HashMap</tt> with the specified initial
     * capacity and the default load factor (0.75).
     *
     * @param capacity the initial capacity
     */
    public HashMap(int capacity) {
        this(capacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Constructs an empty <tt>HashMap</tt> with the default initial capacity
     * (16) and the default load factor (0.75).
     */
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt></tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public V put(K key, V value) {
        int h = hash1(key);
        for (int i = 0; i < table.length; i++) {
            int idx = h % table.length;
            if (table[idx] == null) {
                table[idx] = new HashEntry<>(key, value);
                break;
            } else if (key.equals(table[idx].getKey())) {
                V oldValue = table[idx].getValue();
                table[idx].setValue(value);
                return oldValue;
            }
            h += i * hash2(key);
        }
        if (++size > threshold)
            resize();
        return null;
    }

    /**
     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     *
     *
A return value of {@code null} does not necessarily
     * indicate that the map contains no mapping for the key; it's also
     * possible that the map explicitly maps the key to {@code null}.
     */
    public V get(Object key) {
        int h = hash1(key);
        for (int i = 0; i < table.length; i++) {
            int idx = h % table.length;
            if (table[idx] != null) {
                if (key.equals(table[idx].getKey()))
                    return table[idx].getValue();
            }
            h += i * hash2(key);
        }
        return null;
    }

    /**
     * Remove the mapping for the specified key from this map if present.
     *
     * @param key key whose mapping is to be removed from the map
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    public boolean remove(Object key) {
        int h = hash1(key);
        for (int i = 0; i < table.length; i++) {
            int idx = h % table.length;
            if (table[idx] != null && key.equals(table[idx].getKey())) {
                table[idx] = null;
                return true;
            }
            h += i * hash2(key);
        }
        return false;
    }

    /**
     * Return the number of key-value mappings in this map.
     * @return the number of key-value mappings in this map
     */
    public int size() { return size; }

    public Set<Entry<K, V>> entrySet() {
        Set<Entry<K, V>> set = new HashSet<>(size);
        for (Entry<K, V> e : table)
            if (e != null)
                set.add(e);
        return set;
    }

    private void resize() {
        if (table.length >= MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        int newCapacity = table.length * 2;
        threshold = (int) (newCapacity * loadFactor);
        Entry<K, V>[] oldTable = table;
        table = new Entry[newCapacity];

        for (int i = 0; i < oldTable.length; i++) {
            if (oldTable[i] == null)
                continue;
            K key = oldTable[i].getKey();
            V value = oldTable[i].getValue();

            int h = hash1(key);
            for (int j = 0; j < table.length; j++) {
                int idx = h % table.length;
                if (table[idx] == null) {
                    table[idx] = new HashEntry<>(key, value);
                    break;
                }
                h += j * hash2(key);
            }
            oldTable[i] = null;
        }
    }

    private static int hash1(Object key) {
        return key.hashCode() * 31;
    }

    private static int hash2(Object key) {
        return 1 + key.hashCode() * 63;
    }

    private static class HashEntry<K, V> implements Entry<K, V> {
        private final K key;
        private V value;

        public HashEntry(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() { return key; }

        public V getValue() { return value; }

        public V setValue(V value) {
            V prev = this.value;
            this.value = value;
            return prev;
        }
    }

    public static void main(String[] args) {
        HashMap<Integer, String> hashMap = new HashMap<>(4);
        for (int i = 0; i < 10; i++)
            hashMap.put(i, "i: " + i);
        for (Entry<Integer, String> e : hashMap.entrySet())
            System.out.println(e.getValue());
        hashMap.remove(4);
        System.out.println("after remove/");
        for (int i = 0; i < 10; i++)
            System.out.println(hashMap.get(i));
    }
}
<file_sep>/task1/Calculator.java
import java.text.*;

public class Calculator {
    public static void main(String[] args) {
        if (args.length != 3) {
            System.err.println("Usage: [value] [value] [add || sub || mul || div || mod]");
            System.exit(1);
        }

        double first = Double.parseDouble(args[0].replace(',', '.'));
        double second = Double.parseDouble(args[1].replace(',', '.'));
        String operator = args[2].toLowerCase();

        double result = 0.0;
        try {
            result = calculate(first, second, operator);
        }
        catch (OverflowException | ArithmeticException e) {
            System.err.println(e);
            System.exit(2);
        }

        DecimalFormat df = new DecimalFormat("#.###");
        System.out.println(df.format(result));
    }

    public static double calculate(double first, double second, String operator)
            throws OverflowException, ArithmeticException {
        double result = 0.0;
        switch (operator) {
            case "add":
                if (isAddOverflow(first, second)) throw new OverflowException();
                result = first + second;
                break;
            case "sub":
                if (isSubOverflow(first, second)) throw new OverflowException();
                result = first - second;
                break;
            case "mul":
                if (isMulOverflow(first, second)) throw new OverflowException();
                result = first * second;
                break;
            case "div":
                if (second == 0.0) throw new ArithmeticException("Divide by zero");
                if (isDivOverflow(first, second)) throw new OverflowException();
                result = first / second;
                break;
            case "mod":
                result = first % second;
                break;
            default:
                System.err.println("Unresolved operation");
                System.exit(3);
                break;
        }
        return result;
    }

    public static boolean isAddOverflow(double l, double r) {
        if ((l == Double.MAX_VALUE && r > 0.0) || (r == Double.MAX_VALUE && l > 0.0) ||
                (l == Double.MIN_VALUE && r < 0.0) || (r == Double.MIN_VALUE && l < 0.0)) {
            return true;
        }
        return false;
    }

    public static boolean isSubOverflow(double l, double r) {
        if ((l == Double.MAX_VALUE && r < 0.0) || (r == Double.MAX_VALUE && l < 0.0) ||
                (l == Double.MIN_VALUE && r > 0.0) || (r == Double.MIN_VALUE && l > 0.0)) {
            return true;
        }
        return false;
    }

    public static boolean isMulOverflow(double l, double r) {
        if (((Math.abs(r) > 0.0) && (Math.abs(l) == Double.MAX_VALUE)) ||
                ((Math.abs(l) > 0.0) && (Math.abs(r) == Double.MAX_VALUE))) {
            return true;
        }
        return false;
    }

    public static boolean isDivOverflow(double l, double r) {
        if (((Math.abs(r) < 0.0) && (Math.abs(l) == Double.MAX_VALUE)) ||
                ((Math.abs(l) < 0.0) && (Math.abs(r) == Double.MAX_VALUE))) {
            return true;
        }
        return false;
    }

    private static class OverflowException extends Exception {
        public String toString() {
            return getClass().getName() + ": Overflow";
        }
    }
}

repo_language: Java

repo_name: kelxvel/java


text:
<file_sep># 4.tund
4.tund (27.09.2016)
<file_sep><?php
require("functions.php");
//kui ei ole kasutaja id'd
if (!isset($_SESSION["userId"])){
	//suunan sisselogimise lehele
	header("Location: login.php");
}

//kui on ?logout aadressireal siis login välja
if (isset($_GET["logout"])) {
	session_destroy();
	header("Location: login.php");
}
?>

DATA

Tere tulemast <?=$_SESSION["firstName"];?> <?=$_SESSION["lastName"];?>!

Kasutajanimi: <?=$_SESSION["userName"];?>

E-mail: <?=$_SESSION["userEmail"];?>

Loodud: <?=$_SESSION["created"];?>

Logi välja

languages: Markdown PHP


text:
<file_sep># Converting tabular data to Ontolex-Lexicog

## Ontolex-Lemon and Lexicog

Lexicography is the science of words and their semantic relationships. Wouldn't it be beneficial to take advantage of linked data for lexicography too? Well, this is the motivation behind Ontolex-Lemon.

[Lemon](https://lemon-model.net/) stands for the lexicon model for ontologies (*lemon*) which provides rich linguistic grounding for ontologies. By rich, the creators theoretically aim at all types of information related to words in dictionaries, such as morphological and syntactic properties. The [Ontolex-Lemon](https://www.w3.org/2016/05/ontolex/) is the result of the [W3C Ontology-Lexica Community Group](https://www.w3.org/community/ontolex/).

One of the useful modules in Ontolex-Lemon is the [Ontolex-Lemon lexicography module (lexicog)](https://jogracia.github.io/ontolex-lexicog/).

## Conversion to Ontolex-Lexicog

This tool gets as input the lexicographic data in a tabular format, such as [comma-separated values (CSV)](https://en.wikipedia.org/wiki/Comma-separated_values) and tab-separated values (TSV). In the current version of the tool, the conversion can be done for the followings:

- headwords
- part-of-speech tags
- senses
- examples
- idioms
- and `see also`.

The conversion can be configured using a configuration file called `configuration.json`. In this file, you can set various information such as source and target languages with their codes, PoS tags according to the [Lexinfo module](https://www.lexinfo.net/ontology/2.0/lexinfo).

To run the code, clone or download [this repository](https://github.com/sinaahmadi/Tabular2Lexicog) and pass the input file and the configuration files respectively following `-input` and `-config` arguments in the command line:

```
python -input Sample_dictionary.tsv -config configuration.json
```

**Please note that this script can deal with relatively simple structures for the moment**.

## A working example

These are a few entries in a Kurdish dictionary in tabular format ([original data in `tsv`](https://raw.githubusercontent.com/sinaahmadi/Tabular2Lexicog/master/Sample_dictionary.tsv)):

			Headword
			POS
			Sense (translation)
			Example
			Expression
			Cf.

			aferîde
			m
			creature

			aferîn
			excl
			bravo
			bravo ji ... re: good for ...

			afirandin
			v.t.
			to create

			afîş
			f
			poster

			aga
			adj
			aware

			agadarî
			f
			information
			 announcement; awareness

			agah

			aga

			agahdarî

			agadarî

			agir
			m
			fire

			agir danîn bi: to set fire to

In order to carry out the conversion correctly, we set a few conventions:

- Senses are separated using `;` or `,`.
- Any part-of-speech tag can be used, as long as the correct mappings are provided in the configuration file. This regards `Word`, `MultiwordExpression` and `Affix` classes in Ontolex-Lemon.

The results is created in a folder with the source language name, as in [Kurmanji](https://github.com/sinaahmadi/Tabular2Lexicog/tree/master/Kurmanji).
<file_sep>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Tue August 6 09:45:08 2019
 @author: <NAME> (<EMAIL>)
"""

import codecs
import string
import json
import os
import sys
import shortuuid
shortuuid.set_alphabet(string.digits)

class template:
	def __init__(self, configuration): #source_language, target_language, source_script="", target_script=""):
		self.source_language = configuration["source_language"]
		self.source_language_code = configuration["source_language_code"]
		self.source_script = configuration["source_language_script"]
		self.source_lang_script = self.source_language
		if configuration["source_language_script"] and configuration["source_language_code"]:
			self.source_lang_script = configuration["source_language_code"] + "-" + configuration["source_language_script"]
		self.source_language_url = configuration["source_language_url"]
		self.target_language = configuration["target_language"]
		self.target_language_code = configuration["target_language_code"]
		self.target_script = configuration["target_language_script"]
		self.target_language_url = configuration["target_language_url"]
		self.pos_map = configuration["pos_map"]
		self.gender_map = configuration["gender_map"]
		self.number_map = configuration["number_map"]
		self.affixes_pos = configuration["affixes_pos"]
		self.prefixes = """
@prefix : <http://example.org/owlim/> .
@prefix lexicog: <http://www.w3.org/ns/lemon/lexicog#> .
@prefix ontolex: <http://www.w3.org/ns/lemon/ontolex#> .
@prefix vartrans: <http://www.w3.org/ns/lemon/vartrans#> .
@prefix synsem: <http://www.w3.org/ns/lemon/synsem#> .
@prefix lexinfo: <http://www.lexinfo.net/ontology/2.0/lexinfo#> .
@prefix lime: <http://www.w3.org/ns/lemon/lime#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix dc: <http://purl.org/dc/elements/1.1/> .
@prefix dct: <http://purl.org/dc/terms/> .
@prefix contact: <http://www.w3.org/2000/10/swap/pim/contact#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
		"""
		#----------------------
		 # LEXICOGRAPHIC RESOURCE
		self.lexicographic_template_header = """
:|-G-|_Dictionary a lexicog:LexicographicResource ;
    dct:title ""@en ;
    dct:description "" ;
    rdfs:label ""@en ;
    dct:created "2019-08-21"^^xsd:date ;
    dct:modified "2019-08-21"^^xsd:date ;
    owl:versionInfo "0.1" ;
    cc:license "" ;
    dct:creator "" ;
	dc:contributer "" ;
	dct:language |-B-| ;
""".replace("|-G-|", self.source_language).replace("|-B-|", self.source_language_url)

		self.lexicographic_entry = """	lexicog:entry :HEAD_entry ;"""

		self.lexicographic_entry_comp = """
:HEAD_entry a lexicog:Entry ;
	rdfs:member :HEAD_comp ."""

		self.lexicographic_entry_sense = """ rdf:_X :sense ;
"""

		self.lexicographic_tail = """:HEAD a lexicog:LexicographicComponent .
"""

		self.lexicographic_entry_comp_cf = """
:HEAD_entry a lexicog:Entry ;
	rdfs:member :CF_comp ;
	owl:sameAs :CF_entry ."""
		#----------------------

		self.lexicon_metadata = """
:|-G-|_lexicon a lime:Lexicon ;
	lime:language "|-A-|" ;
	dct:language |-B-| ;
	lime:lexicalEntries "X-X|-X-|X-X"^^xsd:integer ;
	dct:description ""@en ;
	dct:creator "" ;
""".replace("|-A-|", self.source_language_code).replace("|-B-|", self.source_language_url).replace("|-G-|", self.source_language)

		self.entry_meta = "	lime:entry :lex_HEAD ;"

		self.entry_body = """
:lex_HEAD a ontolex:LexicalEntry, ontolex:ENTRYTYPE ;
	ontolex:canonicalForm :form_HEAD ;
	rdfs:label "HDWORD"@|-C-| ;
	lexinfo:partOfSpeech lexinfo:POS ;
	lexinfo:gender lexinfo:GENDER ;
	ontolex:sense SENSES .

:form_HEAD a ontolex:Form ;
	dct:language |-B-| ;
	ontolex:writtenRep "HDWORD"@|-C-| ;
	lexinfo:number lexinfo:NUMBER ;
""".replace("|-C-|", self.source_lang_script).replace("|-B-|", self.source_language_url)

		self.entry_translation = """:TRANS a ontolex:LexicalEntry ;
	dct:language |-F-| ;
	rdfs:label "LABEL"@|-E-| ;
	ontolex:sense :TRANS_sense ;

:trans_HEAD_sense a vartrans:Translation ;
	vartrans:source :HEAD_sense ;
	vartrans:target :TRANS_sense ;
""".replace("|-E-|", self.target_language_code).replace("|-F-|", self.target_language_url)

		self.entry_example = """:HEAD_sense a lexicog:UsageExample ;
	rdf:value "EX1"@|-C-| ;
	rdf:value "EX2"@|-E-| .
""".replace("|-C-|", self.source_lang_script).replace("|-E-|", self.target_language_code)

		self.entry_body_cf = """
:lex_HEAD a ontolex:LexicalEntry, ontolex:ENTRYTYPE ;
	ontolex:canonicalForm :form_HEAD ;
	rdfs:label "HDWORD"@|-C-| ;

:form_HEAD owl:sameAs :form_CF .

""".replace("|-C-|", self.source_lang_script)

		self.lexicog_lexicon_relation = ":lexicog_subj lexicog:describes :lexicon_subj ."

	def create_triple_subject(self, lang, ALL_SUBJECTS):
		search = True
		while search:
			entry_ID = lang + "_" + shortuuid.uuid()[0:10]
			if entry_ID not in ALL_SUBJECTS.keys():
				return entry_ID

	def create_lexicog(self, entry_ID, senses_origin_ID):
		lexico_header = self.lexicographic_entry.replace("HEAD", entry_ID)
		lexico_comp = self.lexicographic_entry_comp.replace("HEAD", entry_ID)
		lexico_sense = ":" + entry_ID + "_comp"
		lexico_tail = self.lexicographic_tail.replace("HEAD", entry_ID+"_comp")

		for s_ind in range(len(senses_origin_ID)):
			lexico_sense += self.lexicographic_entry_sense.replace("X", str(s_ind)).replace("sense", list(senses_origin_ID)[s_ind]+"_sense_X_comp".replace("X", str(s_ind)))
			lexico_tail += self.lexicographic_tail.replace("HEAD", list(senses_origin_ID)[s_ind]+"_sense_X_comp".replace("X", str(s_ind)))

		return lexico_header, lexico_comp, lexico_sense, lexico_tail

	def find_frames(self, word_list):
		frame_boundaries = list()
		for id in range(len(word_list)-1):
			if True not in [True if i != "" else False for i in word_list[id]]:
				pass
			else:
				step = id +1
				while word_list[step][0] == "" and word_list[step][1] == "" and True in [True if i != "" else False for i in word_list[step]]:
					frame_boundaries.append((id, step))
					step = step + 1
				id = step
		return frame_boundaries
# ================================================
# Main
# ================================================
input_file_name, configuration_file_name = "", ""
if len(sys.argv) == 5:
	for i in [1, 3]:
		if sys.argv[i] == "-input":
			input_file_name = sys.argv[i+1]
		elif sys.argv[i] == "-config":
			configuration_file_name = sys.argv[i+1]
if not len(input_file_name) and not len(configuration_file_name):
	raise ValueError('Arguments not identifiable.')

lex = codecs.open(input_file_name, "r", "utf-8").read().replace("\r", "").split("\n")
lex = [e.split("\t") for e in lex]
with open(configuration_file_name) as f:
    configuration = json.load(f)

if not os.path.exists(configuration["source_language"]):
	os.mkdir(configuration["source_language"])

tmplt = template(configuration)

invalids = list()
ALL_SUBJECTS_origin = dict() # entry,
ALL_SUBJECTS_en = dict()
entry_senses_ID = dict()
final_resource = ""
lexicog_header, lexicog_comp, lexico_sense, lexicog_tail = "", "", "", ""
LEXICON_meta, LEXICON_RESOURCE = "", ""
lexicog_lexicon_triples,lexicog_lexicon_triples_cf = "", ""

lex_frames = tmplt.find_frames(lex)

for ind in range(len(lex)):
	entry = lex[ind]
	entry_type = ""
	is_cf = False
	lexicon_body = ""
	headword = entry[0].strip()
	print(headword)

	# Check if the entry is in a frame. If yes, skip (for this version of the code)
	if ind in [i[1] for i in lex_frames]:
		pass
	# Find entry type (Word, Affix, MultiwordExpression, cf)
	elif headword != "":
		if True in [True if d in headword else False for d in string.digits]:
			pass
		else:
			if entry[1] in tmplt.affixes_pos:
				entry_type = "Affix"
			elif entry[1] == "" and entry[5] != "":
				is_cf = True
			elif "-" not in headword:
				if entry[1] == "":
					if entry[2] != "":
						entry_type = "Word"

				elif "," not in headword and entry[1] in tmplt.pos_map.keys():
					entry_type = "Word"
			else:
				if " " not in headword and len(headword) > 1:
					entry_type = "MultiwordExpression"
				else:
					entry_type = "Word"

	if entry_type:
		# create subject for triples of the entry
		entry_ID = tmplt.create_triple_subject(tmplt.source_language_code, ALL_SUBJECTS_origin) # entry ID
		ALL_SUBJECTS_origin[entry_ID] = headword

		senses = [s.strip().replace("\"", "") for s in entry[2].split(";")]
		sense_IDs = dict()
		for s in senses:
			if s:
				sense_ID_en = tmplt.create_triple_subject(tmplt.target_language_code, ALL_SUBJECTS_en)
				sense_ID_origin = tmplt.create_triple_subject(tmplt.source_language_code, ALL_SUBJECTS_origin)
				ALL_SUBJECTS_en[sense_ID_en] = s
				sense_IDs[sense_ID_origin]= sense_ID_en

		entry_senses_ID[entry_ID] = sense_IDs

		# LEXICON-LEXICOG RELATION -----
		lexicog_lexicon_triples += tmplt.lexicog_lexicon_relation.replace("lexicog_subj", entry_ID+"_comp").replace("lexicon_subj", "lex_"+entry_ID) + "\n"

		# LEXICOGRAPHIC RESOURCE
		lexicog_entry_output = tmplt.create_lexicog(entry_ID, sense_IDs.keys())
		lexicog_header += lexicog_entry_output[0] + "\n"
		lexicog_comp += lexicog_entry_output[1] + "\n"
		if sense_IDs:
			lexico_sense += lexicog_entry_output[2] + "\n"
		lexicog_tail += lexicog_entry_output[3]

		# LEXICON ----------------------
		LEXICON_meta += tmplt.entry_meta.replace("HEAD", entry_ID)+ "\n"

		# Gender
		gender = "GENDER"
		if entry[1] in tmplt.gender_map.keys():
			gender = tmplt.gender_map[entry[1]]

		# Number
		number = "NUMBER"
		if entry[1] in tmplt.number_map.keys():
			number = tmplt.number_map[entry[1]]

		# Example
		# Examples of idioms and headwords were originally separated by ;
		# This was temporarily ignored. A better conversion of such cases will be needed.
		examples = dict()
		if entry[3] != "":
			example = entry[3].replace("\"; \"", "|").replace("\", \"", "|").replace("\",\"", "|").replace(", \"", "|")
			for ex in example.split("|"):
				ex = ex.replace("\"", "")
				ex_1, ex_2 = ex.split(":")[0], ex.split(":")[1]
				examples[ex_1.strip()] = ex_2.strip()

		# Idioms should be placed as new entries but in the same lexicographic component of the headword
		lexicon_body = tmplt.entry_body.replace("ENTRYTYPE", entry_type).replace("HEAD", entry_ID).replace("HDWORD", headword).replace("POS", tmplt.pos_map[entry[1]]).replace("GENDER", gender).replace("NUMBER", number).replace("SENSES", ", ".join(":"+s+"_sense" for s in sense_IDs.keys()))
		lexicon_body = lexicon_body.replace("\n	lexinfo:gender lexinfo:GENDER ;", "").replace("\n	lexinfo:number lexinfo:NUMBER ;", "")

		translations = ""
		for origin_sense_ID in sense_IDs:
			translations += tmplt.entry_translation.replace("TRANS", sense_IDs[origin_sense_ID]).replace("LABEL", ALL_SUBJECTS_en[sense_IDs[origin_sense_ID]]).replace("HEAD_sense", origin_sense_ID+"_sense") + "\n"

			lexicog_lexicon_triples += tmplt.lexicog_lexicon_relation.replace("lexicog_subj", origin_sense_ID+"_comp").replace("lexicon_subj", origin_sense_ID+"_sense") + "\n"

		examples_content = ""
		for ex in examples:
			examples_content += tmplt.entry_example.replace("HEAD_sense", origin_sense_ID+"_sense").replace("EX1", ex).replace("EX2", examples[ex]) + "\n"

		lexicon_body += "\n" + translations + examples_content
		lexicon_body = lexicon_body.replace("\n\tlexinfo:partOfSpeech lexinfo:POS ;", "").replace("\n\tontolex:sense  .", "")

	else:
		# Cf. entries
		if is_cf:
			# print(headword)
			entry_ID = tmplt.create_triple_subject(tmplt.source_language_code, ALL_SUBJECTS_origin) # entry ID
			ALL_SUBJECTS_origin[entry_ID] = headword
			if entry[5].strip() in list(ALL_SUBJECTS_origin.values()):
				CF_id = list(ALL_SUBJECTS_origin.keys())[list(ALL_SUBJECTS_origin.values()).index(entry[5])]
				# Lexicography
				lexicog_header += tmplt.lexicographic_entry.replace("HEAD", entry_ID)+ "\n"
				lexicog_comp += tmplt.lexicographic_entry_comp_cf.replace("HEAD", entry_ID).replace("CF", CF_id) + "\n"
				lexicog_lexicon_triples_cf += tmplt.lexicog_lexicon_relation.replace("lexicog_subj", entry_ID+"_entry").replace("lexicon_subj", "lex_"+entry_ID) + "\n"
				# Lexicon
				LEXICON_meta += tmplt.entry_meta.replace("HEAD", entry_ID)+ "\n"
				lexicon_body = tmplt.entry_body_cf.replace("ENTRYTYPE", "Word").replace("HDWORD", headword).replace("HEAD", entry_ID).replace("CF", CF_id)

			else:
				invalids.append("\t".join(entry))

	if lexicon_body:
		LEXICON_RESOURCE += lexicon_body + "\n"

LEXICOGRAPHIC_RESOURCE = (tmplt.lexicographic_template_header + lexicog_header + lexicog_comp + "\n" + lexico_sense + lexicog_tail).replace(" ;\n\n", " .\n\n")
LEXICON_RESOURCE = (tmplt.lexicon_metadata.replace("X-X|-X-|X-X", str(len(lex)-len(invalids))) + LEXICON_meta + LEXICON_RESOURCE).replace(" ;\n\n", " .\n\n")
final_resource = tmplt.prefixes + "\n\n# LEXICOGRAPHIC RESOURCE -------------------------------------------\n " + \
				LEXICOGRAPHIC_RESOURCE + "\n\n# LEXICON ----------------------------------------------------------\n" + \
				LEXICON_RESOURCE + "# LEXICOGRAPHIC RESOURCE - LEXICON RELATIONS -------------------\n\n" + \
				lexicog_lexicon_triples + "\n" + lexicog_lexicon_triples_cf

if True:
	# write invalides
	codecs.open(configuration["source_language"]+"/invalids.txt", "w", "utf-8").write("\n".join(invalids))
	# write triples subject
	with open(configuration["source_language"]+"/entries_ID.json", 'w', encoding='utf-8') as f:
		json.dump(ALL_SUBJECTS_origin, f)

	with open(configuration["source_language"]+"/entry_senses.json", 'w', encoding='utf-8') as f:
		json.dump(entry_senses_ID, f)

	with open(configuration["source_language"]+"/|-E-|_senses_IDs.json".replace("|-E-|", configuration["target_language_code"]), 'w', encoding='utf-8') as f:
		json.dump(ALL_SUBJECTS_en, f)

	# codecs.open("Kurmanji/final.txt", "w", "utf-8").write(final_resource)
	codecs.open(configuration["source_language"]+"/Dictionary.ttl", "w", "utf-8").write(final_resource)

languages: Markdown Python


text:
<file_sep># Climate
> Simple weather app

[![Swift Version][swift-image]][swift-url]
[![License][license-image]][license-url]

Climate is an iOS application that fetches live weather data from OpenWeather API from any city and also presents user with weather data from their current location.

## Features

- [x] User can search for live weather in any city
- [x] Climate presents weather conditions at user's current location
- [x] Light mode and dark mode available

## Requirements

- iOS 13.0+
- Xcode 11

## References

Thank you AppBrewery for providing the skeleton for this project! (https://github.com/appbrewery/Clima-iOS13)

[swift-image]:https://img.shields.io/badge/swift-5.0-orange.svg
[swift-url]: https://swift.org/
[license-image]: https://img.shields.io/badge/License-MIT-blue.svg
[license-url]: LICENSE
[travis-image]: https://img.shields.io/travis/dbader/node-datadog-metrics/master.svg?style=flat-square
[travis-url]: https://travis-ci.org/dbader/node-datadog-metrics
[codebeat-image]: https://codebeat.co/badges/c19b47ea-2f9d-45df-8458-b2d952fe9dad
[codebeat-url]: https://codebeat.co/projects/github-com-vsouza-awesomeios-com
<file_sep>//
//  WeatherManagerDelegate.swift
//  Clima
//
//  Created by <NAME> on 8/2/20.
//  Copyright © 2020 App Brewery. All rights reserved.
//

import Foundation

protocol WeatherManagerDelegate {
    func didUpdateWeather(_ weather: WeatherModel)
}
<file_sep>//
//  WeatherController.swift
//  Clima
//
//  Created by <NAME> on 8/2/20.
//  Copyright © 2020 App Brewery. All rights reserved.
//

import Foundation

protocol WeatherManagerDelegate {
    func didUpdateWeather(_ weatherManager: WeatherManager,weather: WeatherModel)
    func didFailWithError(error: Error)
}

struct WeatherManager {

    var delegate: WeatherManagerDelegate? //optional so that it's not mandatory to be initialized

    let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=5dc08abdd11bdd6e86d9b93d0d4136a9&units=metric"

    var currentLat: Double?
    var currentLon: Double?

    func fetchWeather (cityName: String) {
        let urlString = "\(weatherURL)&q=\(cityName)"
        performRequest(with: urlString)
    }

    mutating func fetchWeather (latitude: Double, longitude: Double) {
        let urlString = "\(weatherURL)&lat=\(Int(latitude))&lon=\(Int(longitude))"
        performRequest(with: urlString)
        currentLat = latitude
        currentLon = longitude
    }

    func performRequest(with urlString: String) {
        //1.Creat URL
        if let url = URL (string: urlString) {
            //URL Session
            let session = URLSession (configuration: .default)
            //task
            let task = session.dataTask(with: url) { (data, response, error) in
                if let safeData = data {
                    if let weather = self.parseJSON(weatherData: safeData) {
                        self.delegate?.didUpdateWeather(self, weather: weather)
                    }
                }

                if error != nil {
                    self.delegate?.didFailWithError(error: error!)
                    return
                }
            }
            //start task
            task.resume()
        }
    }

    func parseJSON (weatherData: Data) -> WeatherModel? {
        let decoder = JSONDecoder()
        do {
            //self changes WeatherData from an object from a Decodable Protocol type
            let decodedData = try decoder.decode(WeatherData.self, from: weatherData)

            let temp = decodedData.main.temp
            let id = decodedData.weather[0].id
            let name = decodedData.name

            let weatherModel = WeatherModel(conditionId: id, cityName: name, temperature: temp)

            return weatherModel

        } catch {
            delegate?.didFailWithError(error: error)
            return nil
        }
    }

}

languages: Swift Markdown

repo_language: Swift

repo_name: quinntrang/Climate


text:
<repo_name>humaira83/FakeNews<file_sep>/README.md
# FakeNews
How to create a Fake news without pc?


text:
<repo_name>vishalkumar12364/NodeMongo<file_sep>/views/entry/addOrEdit.hbs

{{viewTitle}}

<form action="/entry" method="POST" autocomplete="off">
    <input type="hidden" name="_id" value="{{entry._id}}">

        Title
        <input type="text" class="form-control" name="title" placeholder="title" value="{{entry.title}}">

            {{entry.titleError}}

            Date
            <input type="date" class="form-control" name="date" placeholder="Date" value="{{entry.date}} " >

            {{entry.titleError}}

            content
            <textarea rows=6 type="text" class="form-control" name="content" placeholder="Content" value="{{entry.content}}"></textarea>

            {{entry.titleError}}

        <button type="submit" class="btn btn-info"> Submit</button>
         View All

</form><file_sep>/controllers/entryController.js
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Entry = mongoose.model('entry');

router.get('/', (req, res) => {
    res.render("entry/addOrEdit", {
        viewTitle: "Insert Entry"
    });
});

router.post('/', (req, res) => {
    if (req.body._id == '')
        insertRecord(req, res);
        else
        updateRecord(req, res);
});

function insertRecord(req, res) {
    var entry = new Entry();
    entry.title = req.body.title;
    entry.content = req.body.content;
    entry.date = req.body.date;
    entry.save((err, doc) => {
        if (!err)
            res.redirect('entry/list');
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("entry/addOrEdit", {
                    viewTitle: "Insert Entry",
                    entry: req.body
                });
            }
            else
                console.log('Error during record insertion : ' + err);
        }
    });
}

function updateRecord(req, res) {
    Entry.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
        if (!err) { res.redirect('entry/list'); }
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("entry/addOrEdit", {
                    viewTitle: 'Update Entry',
                    entry: req.body
                });
            }
            else
                console.log('Error during record update : ' + err);
        }
    });
}

router.get('/list', (req, res) => {
    Entry.find((err, docs) => {
        if (!err) {
            res.render("entry/list", {
                list: docs
            });
        }
        else {
            console.log('Error in retrieving entry list :' + err);
        }
    });
});

function handleValidationError(err, body) {
    for (field in err.errors) {
        switch (err.errors[field].path) {
            case 'title':
                body['titleError'] = err.errors[field].message;
                break;
            default:
                break;
        }
    }
}

router.get('/:id', (req, res) => {
    Entry.findById(req.params.id, (err, doc) => {
        if (!err) {
            res.render("entry/addOrEdit", {
                viewTitle: "Update Entry",
                entry: doc
            });
        }
    });
});

router.get('/delete/:id', (req, res) => {
    Entry.findByIdAndRemove(req.params.id, (err, doc) => {
        if (!err) {
            res.redirect('/entry/list');
        }
        else { console.log('Error in Entry delete :' + err); }
    });
});

module.exports = router;

languages: Handlebars JavaScript

repo_language: Handlebars


text:
<repo_name>Kissa0330/portfolio2<file_sep>/pages/Works.vue
<template>

WORKS

{{ work.name }}

{{ work.category }}

        <svg
          class="works-svg-arrow"
          xmlns="http://www.w3.org/2000/svg"
          width="72.004"
          height="24.224"
          viewBox="0 0 72.004 24.224"
          :style="{ stroke: colors.hex }"
        >
          <g
            id="グループ_19"
            data-name="グループ 19"
            transform="translate(0 1.592)"
          >
            <line
              id="線_9"
              data-name="線 9"
              x2="72.004"
              transform="translate(0 20.633)"
              fill="none"
              stroke-width="4"
            />
            <line
              id="線_10"
              data-name="線 10"
              x2="20.582"
              y2="20.263"
              transform="translate(50.018 -0.167)"
              fill="none"
              stroke-width="4"
            />
          </g>
        </svg>

</template>

<file_sep>/pages/index.vue
<template>

Hello

I'm frontend engineer and designer

</template>

<file_sep>/pages/About.vue
<template>

PROFILE

            UI/UXデザイナー兼フロントエンドエンジニアです。

            Web/アプリのデザインやLPの実装、APIの実装などが出来ます。

            自分が考えたものを作ってる瞬間が大好きです。

デザイナーやフロントエンジニアのバイトやインターンを探しています。

Twitter

Github

Behance

SKILLS

{{ skill }}

</template>

<file_sep>/layouts/default.vue
<template>

        <nuxt />

      <client-only>

          <transition>
            <chrome-picker
              :value="colors"
              @input="updateValue"
              v-if="pickerView"
            ></chrome-picker>
          </transition>

      </client-only>
      <button
        class="default-button-bucket"
        @click="pickerView = !pickerView"
        :style="{ backgroundColor: colors.hex }"
      >

      </button>

</template>

<file_sep>/components/Header.vue
<template>

RAIKA'S PORTFOLIO

        <transition>
          <Nuxt-link to="/">

TOP

          </Nuxt-link>
        </transition>
        <transition>
          <Nuxt-link to="/about">

ABOUT

          </Nuxt-link>
        </transition>
        <transition>
          <Nuxt-link to="/works">

WORKS

          </Nuxt-link>
        </transition>

</template>

repo_language: Vue


text:
<repo_name>Naveen-86/JavaScriptDS<file_sep>/Map/birthDays.js
let jan = new Map();
let feb = new Map();
let mar = new Map();
let apr = new Map();
let may = new Map();
let jun = new Map();
let jul = new Map();
let aug = new Map();
let sep = new Map();
let oct = new Map();
let nov = new Map();
let dec = new Map();
let persons = 1;
while (persons <= 50) {
  persons++;
  let month = Math.floor(1 + ((Math.random() * 100) % 12));

  switch (month) {
    case 1:
      jan.set(persons, month);
      break;
    case 2:
      feb.set(persons, month);
      break;
    case 3:
      mar.set(persons, month);
      break;
    case 4:
      apr.set(persons, month);
      break;
    case 5:
      may.set(persons, month);
      break;
    case 6:
      jun.set(persons, month);
      break;
    case 7:
      jul.set(persons, month);
      break;
    case 8:
      aug.set(persons, month);
      break;
    case 9:
      sep.set(persons, month);
      break;
    case 10:
      oct.set(persons, month);
      break;
    case 11:
      nov.set(persons, month);
      break;
    case 12:
      dec.set(persons, month);
      break;
    default:
      console.log("thanks!");
  }
}

for (let person of jan.keys()) {
  console.log(person + " -> Jan");
}

for (let person of feb.keys()) {
  console.log(person + " -> Feb");
}

for (let person of mar.keys()) {
  console.log(person + " -> Mar");
}

for (let person of apr.keys()) {
  console.log(person + " -> Apr");
}

for (let person of may.keys()) {
  console.log(person + " -> May");
}

for (let person of jun.keys()) {
  console.log(person + " -> Jun");
}

for (let person of jul.keys()) {
  console.log(person + " -> Jul");
}

for (let person of aug.keys()) {
  console.log(person + " -> Aug");
}

for (let person of sep.keys()) {
  console.log(person + " -> Sep");
}

for (let person of oct.keys()) {
  console.log(person + " -> Oct");
}

for (let person of nov.keys()) {
  console.log(person + " -> Nov");
}

for (let person of dec.keys()) {
  console.log(person + " -> Dec");
}<file_sep>/Arrays/randomNum.js
let randomNumber = [];
for (let i = 0; i < 10; i++) {
  randomNumber[i] = Math.floor(100 + Math.random() * 900);
}
const maximumNumber = Math.max(...randomNumber);
const minimumNumber = Math.min(...randomNumber);

console.log(...randomNumber);

console.log("Maximum = " + maximumNumber + " and  minimum = " + minimumNumber);
const maxFiltered = randomNumber.filter((number) => number < maximumNumber);
const minFiltered = randomNumber.filter((number) => number > minimumNumber);

const secondMax = Math.max(...maxFiltered);
const secondMin = Math.min(...minFiltered);

console.log(
  "second maximum = " + secondMax + " and second minimum = " + secondMin
);

repo_language: JavaScript


text:
<file_sep># The_Sparks_Foundation
This repository contains my submission's to the given tasks in GRIPFEB2021 batch.

branch_name: refs/heads/main


text:
<repo_name>SashoDimitrovski/Ivi-Cosmetics_Front-End<file_sep>/README.md
# IviCosmetics-FE
Single page website made for Macedonian company called "Ivi Cosmetics". Made by team of students at SEDC.


text:
<file_sep># ozf
saya adalah


text:
<repo_name>YangtaoGe518/DPS-Assignment2<file_sep>/test/UDP_Network.py
import socket
import sys
import pickle
import select
from time import sleep

class Network():
    def __init__(self, password):
        self.__password = <PASSWORD>
        self.__server = False
        try: # try to make UDP connection
            self.__sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        except socket.error as err:
            print("socket creation failed with error %s" %(err))
            sys.exit()
        self.__recv_buf = bytes() # use bytes to convey the messages
        self.get_local_ip_addr()

    def get_local_ip_addr(self):
        # obtained from the original network code
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # use UDP to get the local IP
        # connect to nrg.cs.uc.ac.uk
        s.connect(("172.16.58.3", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip

    def server(self, port):
        self.__server = True

<file_sep>/test/SimpleChat_Client.py
import sys
import socket
from time import sleep

def get_sock():
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # here use TCP
    except socket.error as err:
        print("socket creation failed with error %s" %(err))
        sys.exit()
    return sock

def client(sock, ip, port):
    while True: # here is the infinte loop
        try:
            sock.connect((ip, port))
            print("connected to", ip, "on port", port)
            return sock
        except ConnectionRefusedError as err:
            # here server is not ready
            sock.close()
            sock = get_sock()
            print ("Waiting for server")
            sleep (1)

sock = get_sock()
sock = client(sock, "127.0.0.1", 1234) #communication with the local device

while True:
    text = input("->")
    encode_text = text.encode()
    sock.send(encode_text)<file_sep>/test/robustChat_Server.py
import sys
import socket
from time import sleep

def get_sock():
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # here use TCP
    except socket.error as err:
        print("socket creation failed with error %s" %(err))
        sys.exit()
    return sock

def server(sock, port):
    # we need to bind the socket to a specific port
    while True:
        try:
            sock.bind(('', port)) #bind the host(socket) with the port
            break # here break the loop if the socket is binded to the port
        except OSError as err:
            # sometimes the port is used by other program -- wait untill it free
            print(err)
            print("Waiting ,will retry in 10 sec")
            sleep (10) # wait for 10s then connect again
    # tell the socket to listen for incoming connection
    sock.listen(1)
    print("listening for incoming connection")

    # wait until the connection arrived
    client_sock, address = sock.accept() # accept method returns a tuple
    print ("got on incomming connection free", address)
    return client_sock  # if it is bind successfully --- return the sock

# ___________________________MAIN FUNCTION________________________________

listener_sock = get_sock()
sock = server(listener_sock, 1234)
# above code is the same as simpleChat

while True:
    try:
        encoded_text = sock.recv(1024)
    except KeyboardInterrupt as err:
        print ("user termination")
        sock.close()
        break # exit the loop --- end the infinite loop here

    if len(encoded_text) == 0: # if nothing send to the server, we think the connection is closed
        print("connection closed by remote end")
        break # exit the loop

    text = encoded_text.decode('utf-8')  # get the text and decode it
    print(text) <file_sep>/test/nonBlockingAux.py
from fcntl import fcntl, F_GETFL, F_SETFL
<file_sep>/test/resuableChat_client.py
import sys
import socket
from time import sleep

def get_sock():
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # here use TCP
    except socket.error as err:
        print("socket creation failed with error %s" %(err))
        sys.exit()
    return sock

def client(sock, ip, port):
    while True: # here is the infinte loop
        try:
            sock.connect((ip, port))
            print("connected to", ip, "on port", port)
            return sock
        except ConnectionRefusedError as err:
            # here server is not ready
            sock.close()
            sock = get_sock()
            print ("Waiting for server")
        except OSError as err:
            print("OSERROR: " ,err)

# ___________________________MAIN FUNCTION________________________________

sock = get_sock()
sock = client(sock, "127.0.0.1", 1234) #communication with the local device

while True:
    try:
        text = input("->")
    except EOFError as err:
        print("End of input, closing connection")
        sock.close()
        break

    encode_text = text.encode('utf-8')
    sock.send(encode_text)

    try:
        bytessent = sock.send(encode_text)
        print("sent", bytessent, "bytes")
    except BrokenPipeError as err:
        print("Connection closed by remote end")
        break
        <file_sep>/test/nonBlockingChat_client.py
import sys
import socket
from time import sleep
from nonblocking_readline import * # here need use UNIX

def get_sock():
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # here use TCP
    except socket.error as err:
        print("socket creation failed with error %s" %(err))
        sys.exit()
    return sock

def client(sock, ip, port):
    while True: # here is the infinte loop
        try:
            sock.connect((ip, port))
            print("connected to", ip, "on port", port)
            return sock
        except ConnectionRefusedError as err:
            # here server is not ready
            sock.close()
            sock = get_sock()
            print ("Waiting for server")
        except OSError as err:
            print("OSERROR: " ,err)

# ___________________________MAIN FUNCTION________________________________

sock = get_sock()
sock = client(sock, "127.0.0.1", 1234) #communication with the local device
sock.setblocking(False)

close_connect = False

while close_connect == False:
    try:
        key_text = nonblocking_readline()  # need define another function
    except (EOFError, KeyboardInterrupt):
        close_connect = True

    if key_text != "":   # if sent empty data to the clinet --- close the connection
        encode_text = key_text.encode('utf-8')

        try:
            bytessent = sock.send(encode_text)
            print ("sent ", bytessent, "bytes")
        except BrokenPipeError as err:
            close_connect = True

    try:
        received_bytes = sock.recv(1024)
        if len(received_bytes) == 0:   # receive nothing
            close_connect = True
        else:
            net_text = received_bytes.encode('utf-8')
            print(">>", net_text)
    except BlockingIOError:
        pass

print("End of input, closing connection")
sock.close()

repo_language: Python


text:
<file_sep>import React from 'react';
import { StyleSheet, Text, View, TextInput, TouchableHighlight, AsyncStorage, Image, ScrollView } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { AppLoading } from 'expo';
import Icon from 'react-native-vector-icons/Feather';
import Boba from './components/boba.js';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      city: '',
      data: {},
      newData: {},
      loaded: false,
      noNewData: true
    };
  }

  componentDidUpdate = () => {
    this.loadBoba();
  }

  componentDidMount = () => {
    this.loadBoba();
  }

  loadBoba = async () => {
    try {
      const getBoba = await AsyncStorage.getItem('boba');
      const parsedBoba = JSON.parse(getBoba);
      this.setState({loaded: true, data: parsedBoba || {}});
    } catch (err) {
      console.log(err);
    }
  };

  deleteBoba = city => {
    const {data} = this.state
    let copy = data
    delete copy[city]
    AsyncStorage.setItem('boba', JSON.stringify(copy))
  }

  handleSave = () => {
    const {data, newData} = this.state
    if (newData) {
      let copy = data
      copy[newData.city] = {city: newData.city, results: newData.results}
      AsyncStorage.setItem('boba', JSON.stringify(copy))
      this.setState({noNewData: true, newData: {}})
    }
  }

  handleSubmit = () => {
    const {city} = this.state;
    fetch(
      `https://developers.zomato.com/api/v2.1/cities?q=${city}&apikey=da9010e85d15798abd4afa175a44f514`
    )
      .then(res => res.json())
      .then(json => {
        const selectCity = json.location_suggestions[0];
        const city_id = selectCity.id;
        fetch(
          `https://developers.zomato.com/api/v2.1/search?entity_id=${city_id}&entity_type=city&q=boba&apikey=da9010e85d15798abd4afa175a44f514`
        )
          .then(res => res.json())
          .then(json => {
            this.setState({noNewData: false, newData: {city: city, results: json.results_found}});
          });
      })
    this.setState({city: ''});
  };

  render() {
    const {city, data, newData, loaded, noNewData} = this.state;
    if (!loaded) {
      return <AppLoading />;
    }
    return (
      <View style={styles.container}>
      <LinearGradient colors={['#FFA392', '#ffecd2']} style={styles.backgroundgradient} />

        <Text style={styles.title}>ChubbyStraw</Text>

        <View style={styles.inputContainer}>
          <TextInput style={styles.textInput} value={city} placeholder="C I T Y"
          onChangeText={city => this.setState({city: city})} placeholderTextColor='rgba(89,17,23,0.4)' />
          <TouchableHighlight underlayColor='#46090F' onPressOut={this.handleSubmit} style={styles.search}>
            <View style={styles.searchIcon}><Icon name="search" size={30} color='#F3C4B7' /></View>
          </TouchableHighlight>
        </View>

        <TouchableHighlight underlayColor='#ECE1D9' style={styles.save} onPressOut={this.handleSave}>
          <Text style={styles.saveText}>SAVE DAT BOBA ( ੭ˊ꒳ˋ)੭ ♡⁺˚</Text>
        </TouchableHighlight>

        <Image source={require('./assets/boba.png')} style={styles.image} />
        <ScrollView contentContainerStyle={styles.bobaContainer}>
          {noNewData ? null : <Boba key={newData.city} deleteBoba={this.deleteBoba} {...newData} />}
          {Object.values(data).map(item => <Boba key={item.city} deleteBoba={this.deleteBoba} {...item} />)}
        </ScrollView>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#FFCCAA',
    paddingTop: 70,
  },
  image: {
    opacity: 0.1,
    position: 'absolute',
    top: 400,
    width: 200,
    height: 300,
    alignSelf: 'center',
  },
  backgroundgradient: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    height: 1000,
  },
  title: {
    fontSize: 48,
    fontWeight: '900',
    color: 'white',
    letterSpacing: 3,
    fontFamily: 'ArialRoundedMTBold',
    textAlign: 'center',
  },
  bobaContainer: {
    width: 400,
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 20,
  },
  inputContainer: {
    paddingTop: 20,
    marginLeft: 32,
    marginRight: 32,
    justifyContent: 'space-between',
    flexDirection: 'row',
  },
  textInput: {
    borderColor: 'rgba(89,17,23,0.2)',
    borderBottomWidth: 3,
    color: '#591117',
    width: 270,
    height: 50,
    fontSize: 25,
    paddingLeft: 10,
    paddingRight: 16,
    fontFamily: 'ArialRoundedMTBold',
    fontWeight: 'bold',
    letterSpacing: 3,
  },
  save: {
    width: 370,
    height: 65,
    borderWidth: 0,
    borderRadius: 20,
    backgroundColor: '#FFF4E9',
    padding: 16,
    margin: 16,
    shadowOffset:{ width: 5, height: 10,},
    shadowColor: '#975326',
    shadowOpacity: 0.3,
    shadowRadius: 10,
  },
  saveText: {
    color: 'rgba(89,17,23,0.4)',
    fontWeight: 'bold',
    fontSize: 20,
    textAlign: 'center',
    fontFamily: 'ArialRoundedMTBold',
    letterSpacing: 3,
  },
  search: {
    backgroundColor: '#591117',
    width: 60,
    height: 60,
    borderRadius: 30,
    shadowOffset:{ width: 5, height: 5,},
    shadowColor: '#975326',
    shadowOpacity: 0.6,
    shadowRadius: 7,
  },
  searchIcon: {
    left: 15,
    top: 15,
  }
});
<file_sep># ChubbyStraw
A mobile app that provides the number of boba shops in a given city through open API using React Native

<img width="1017" alt="Screen Shot 2019-09-11 at 2 30 39 PM" src="https://user-images.githubusercontent.com/47490469/64724582-bf3fdc00-d4a0-11e9-89a3-be631d886038.png">

languages: Markdown JavaScript


text:
<file_sep>adminUser:
  password: <PASSWORD>/adminUser:password
  username: admin
docker:
  password: <PASSWORD>:<PASSWORD>/docker:password
  url: https://apro.nbnco.net.au/clna-prototype-generic
  username: modassarrana
enableDocker: true
pipelineUser:
  email: <EMAIL>
  token: local:faas/pipelineUser:token
  username: modassarrana
prow:
  hmacToken: local:faas/prow:hmacToken

repo_language: YAML


text:
<file_sep>package com.tts.mycustomsite;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class MyCustomSiteApplicationTests {

	@Test
	void contextLoads() {
	}

}


text:
<file_sep>import os
import texture_gen
import glob
from tqdm import tqdm

from generate_shapes import ShapeGenerator
from skimage import io, color, img_as_float32

def main():
    # Generate 2d Shape Images
    # DATASETS: 3 Shapes, 5 Shapes, 5 Shapes w/ Random Size

    num_images = 700 # Number of images per each shape
    # Destination path for original 2D images
    destination_orig = "./datasets/six_shapes/"
    print("Generating Images and saving to " + destination_orig)

    generator = ShapeGenerator(destination_orig, num_images)
    generator.generate_shapes()

    # Apply Textures to Images
    # NOTE: destination_textured should end in '/'
    destination_textured = "./datasets/six_shapes_t/"
    print("Generating Texutes and saving to " + destination_textured)
    textures, t_names = texture_gen.load_textures()

    # Load original image shapes + generate new images to save
    data_path = os.path.join(destination_orig,'*g')
    files = glob.glob(data_path)
    for f1 in tqdm(files, desc="Loading..."):
        img = io.imread(f1, as_gray = True)
        # print(img.shape)
        img = img_as_float32(img)

        texture_gen.generate_textures(img, f1, textures, t_names, destination_textured)

if __name__ == '__main__':
    main()<file_sep>import matplotlib.pyplot as plt
import numpy as np
import os
import PIL

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# print(tf.__version__) # Have to use at least tf 2.3

img_height = img_width = 200
batch_size = 15

# Use dataset from directory
directory = "./datasets/three_shapes_size_t/"

ds_train = tf.keras.preprocessing.image_dataset_from_directory(
    directory,
    labels = "inferred",
    label_mode = "int",
    color_mode = "grayscale",
    batch_size = batch_size,
    image_size = (img_height, img_width),
    shuffle = True,
    seed = 33,
    validation_split = 0.2,
    subset = "training"
)

ds_validation = tf.keras.preprocessing.image_dataset_from_directory(
    directory,
    labels = "inferred",
    label_mode = "int",
    color_mode = "grayscale",
    batch_size = batch_size,
    image_size = (img_height, img_width),
    shuffle = True,
    seed = 33,
    validation_split = 0.2,
    subset = "validation"
)

class_names = ds_train.class_names
# print(class_names)

num_classes = len(class_names)

# Custom Model
model = keras.Sequential([
  layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 1)),
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Conv2D(32, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Conv2D(64, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Flatten(),
 #  layers.Dropout(0.5),
  layers.Dense(128, activation='relu'),
  layers.Dense(64, activation="relu"),
  layers.Dense(num_classes, activation="softmax")
])

model.compile(optimizer=keras.optimizers.Adam(),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.summary()

num_epochs = 15
history = model.fit(
  ds_train,
  epochs=num_epochs,
  verbose=2,
  validation_data=ds_validation
)

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(num_epochs)

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Testing Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Testing Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Testing Loss')
plt.legend(loc='upper right')
plt.title('Training and Testing Loss')
plt.savefig("loss_accuracy_plots_large_0.png", bbox_inches="tight")
=======
# Visualization Code
# plt.figure(figsize=(10, 10))
# for images, labels in ds_train.take(1):
#   for i in range(9):
#     ax = plt.subplot(3, 3, i + 1)
#     plt.imshow(images[i].numpy().astype("uint8"),cmap="gray")
#     plt.title(class_names[labels[i]])
#     plt.axis("off")

# plt.show()

# num_classes = len(class_names)

# # Custom Model
# model = keras.Sequential([
#   layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 1)),
#   layers.Conv2D(16, 3, padding='same', activation='relu'),
#   layers.MaxPooling2D(),
#   layers.Conv2D(32, 3, padding='same', activation='relu'),
#   layers.MaxPooling2D(),
#   layers.Conv2D(64, 3, padding='same', activation='relu'),
#   layers.MaxPooling2D(),
#   layers.Flatten(),
#   layers.Dropout(0.5),
#   layers.Dense(128, activation='relu'),
#   layers.Dense(64, activation="relu"),
#   layers.Dense(num_classes, activation="softmax")
# ])

# model.compile(optimizer=keras.optimizers.Adam(),
#               loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
#               metrics=['accuracy'])

# model.summary()

# num_epochs = 15
# history = model.fit(
#   ds_train,
#   epochs=num_epochs,
#   verbose=2,
#   validation_data=ds_validation
# )

# acc = history.history['accuracy']
# val_acc = history.history['val_accuracy']

# loss = history.history['loss']
# val_loss = history.history['val_loss']

# epochs_range = range(num_epochs)

# plt.figure(figsize=(8, 8))
# plt.subplot(1, 2, 1)
# plt.plot(epochs_range, acc, label='Training Accuracy')
# plt.plot(epochs_range, val_acc, label='Testing Accuracy')
# plt.legend(loc='lower right')
# plt.title('Training and Testing Accuracy')

# plt.subplot(1, 2, 2)
# plt.plot(epochs_range, loss, label='Training Loss')
# plt.plot(epochs_range, val_loss, label='Testing Loss')
# plt.legend(loc='upper right')
# plt.title('Training and Testing Loss')
# plt.savefig("loss_accuracy_plots_large_0.png", bbox_inches="tight")
>>>>>>> ea3411d3321480c160275a950cb7a84cd72105b5
<file_sep>from abc import ABC, abstractmethod

import numpy as np
import io
from PIL import Image
import uuid
from os import path

# 2D shape generator, each shape is saved in png file
class AbstractShape(ABC):
    def __init__(self, destination, painter):
        self.painter = painter
        self.destination = destination
        self.radius = None
        self.x = None
        self.y = None

    # Sets background canvas color
    def set_bg_color(self):
        color = [0,0,0] # All Black

        self.painter.fillcolor(color[0], color[1], color[2])
        self.painter.color(color[0], color[1], color[2])
        self.painter.penup()
        self.painter.setposition(-160, 160)
        self.painter.pendown()
        self.painter.begin_fill()

        self.painter.goto(160, 160)
        self.painter.goto(160, -160)
        self.painter.goto(-160, -160)
        self.painter.goto(-160, 160)

        self.painter.end_fill()
        self.painter.penup()

    # Set shape fill and draw color
    def set_shape_color(self):
        color = [255,255,255] # all white
        self.painter.fillcolor(color[0], color[1], color[2])
        self.painter.color(color[0], color[1], color[2])
        self.painter.penup()

    # Sets and randomizes parameters for each shape to generate
    def set_params(self):
        self.painter.reset()

        self.set_bg_color()
        self.set_shape_color()

        # Set Shape Size/Perimeter
        self.radius = np.random.randint(20, 75)
        # self.radius = 40

        # Set Shape Rotation
        self.rotation = np.deg2rad(np.random.randint(-180, 180))
        # self.rotation = 0

        # Set Center Coordinates
        self.x = np.random.randint(-80 + self.radius, 80 - self.radius)
        self.y = np.random.randint(-80 + self.radius, 80 - self.radius)
        # self.x = self.y = 0

    # Saves Drawing with unique name as a png file
    # The name of the save image is as follows : [Type of shape]_[UUID].png
    # NOTE: Installed GhostScript on Windows for this to work
    def save_drawing(self):
        ps = self.painter.getscreen().getcanvas().postscript(
            colormode='color', pageheight=199, pagewidth=199
        )
        im = Image.open(io.BytesIO(ps.encode('utf-8')))
        im.save(path.join(
            self.destination,
            self.__class__.__name__ + "_" + str(uuid.uuid1()) + '.png'
        ), quality=100, format='png')

    # Draws shape relative to parameters
    def draw(self):
        self.painter.penup()
        shape_coordinates = self.get_shape_coordinates()
        r_coordinates = []

        # Calculates rotated shape coordinates
        for item in shape_coordinates:
            r_coordinates.append(
                (
                    (item[0] - self.x) * np.cos(self.rotation) -
                    (item[1] - self.y) * np.sin(self.rotation) + self.x,

                    (item[0] - self.x) * np.sin(self.rotation) +
                    (item[1] - self.y) * np.cos(self.rotation) + self.y
                )
            )

        self.painter.goto(r_coordinates[-1])

        self.painter.pendown()
        self.painter.begin_fill()

        # for idx, coord in enumerate(r_coordinates):
        for coord in r_coordinates:
            self.painter.goto(coord)
            # if self.should_break and self.should_break == idx:
            #     self.painter.end_fill()
            #     self.painter.begin_fill()

        self.painter.end_fill()
        self.painter.hideturtle()

    def generate(self):
        """
            Generate an image that contains a shape drown inside it, in function
            of the set of random parameters that where configured in the
            function ‘__set_random_params‘.

        :return: None
        """
        self.set_params()
        self.draw()
        self.save_drawing()

    @abstractmethod
    def get_shape_coordinates(self):
        # Calculates coordinates of points with no rotatation relative to center
        raise NotImplementedError()

# 2D shape generator for polygon with arbritary number of sides/vertices
class AbstractPolygonShape(AbstractShape, ABC):

    number_of_vertices = None
    # should_break = None

    def get_shape_coordinates(self):

        if not self.number_of_vertices:
            raise NotImplementedError(
                "The number of vertices must be specified in sub classes."
            )

        coordinates = []
        for vertex in range(self.number_of_vertices):
            coordinates.append(
                (
                    self.radius * np.cos(
                        2 * np.pi * vertex / self.number_of_vertices
                    ) + self.x,
                    self.radius * np.sin(
                        2 * np.pi * vertex / self.number_of_vertices
                    ) + self.y
                )
            )
        return coordinates

class Triangle(AbstractPolygonShape):

    number_of_vertices = 3

class Square(AbstractPolygonShape):

    number_of_vertices = 4

class Pentagon(AbstractPolygonShape):

    number_of_vertices = 5

class Hexagon(AbstractPolygonShape):

    number_of_vertices = 6

class Heptagon(AbstractPolygonShape):

    number_of_vertices = 7

class Circle(AbstractShape):

    def draw(self):

        self.painter.setposition(self.x, self.y - self.radius)

        self.painter.pendown()
        self.painter.begin_fill()
        self.painter.ht()
        self.painter.circle(self.radius)
        self.painter.end_fill()

    def get_shape_coordinates(self):
        pass<file_sep>## 2D-Shape-and-Texture-Classification

https://docs.google.com/presentation/d/1Bj9CBX28tg_7ktYXXeGqa1CvohkoYT_kKzeUSX37KsA/edit?usp=sharing

# Generating Dataset

In main.py:
-num_images is the number of images to generate for each shape, and also the number of images that will be in each class.
-destination_orig is the folder to store the original shape images
-destination_textured is the folder to store the final shape + texture images

In shapes.py:
-This is where one can add new shapes. To add polygons, follow the design for any oteher polygon and just change the class name and number of sides.

In generate_shapes.py:
-GENERATOR_CLASSES is a list of the Shape classes we will generate and this can be adjusted to add or remove shapes

In texture_gen.py:
-img_dir is the directory for the texture file images

In order to generate a dataset run 'python main.py'.

# Running Model

To run any model, just call 'python model_name.py' and in each of these files directory is the folder that holds the dataset with the textured images in their respective folders.

model.py is my custom model<file_sep>import turtle
import shapes
from tqdm import tqdm

class ShapeGenerator:

    # Shapes we will be generating
    GENERATOR_CLASSES = [
        shapes.Circle,
        shapes.Triangle,
        shapes.Square,
        shapes.Pentagon,
        shapes.Hexagon,
        shapes.Heptagon
    ]

    def __init__(self,destination,num_images):
        turtle.colormode(255) # Use ints or float range for colors

        turtle.setup(width=200, height=200)
        turtle.hideturtle()
        turtle.tracer(False) # Hide Animations for speed-up

        self.painter = turtle.Turtle()

        self.num_images = num_images

        self.shapes = []
        for generator in self.GENERATOR_CLASSES:
            self.shapes.append(generator(destination,self.painter))

    def generate_shapes(self):
        for _ in tqdm (range (self.num_images), desc="Loading..."):
            for shape in self.shapes:
                shape.generate()
<file_sep>import matplotlib.pyplot as plt
import numpy as np
import os
import PIL

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# print(tf.__version__) # Have to use at least tf 2.3

img_height = img_width = 299
batch_size = 25

# Use dataset from directory
directory = "./datasets/six_shapes_t/"

ds_train = tf.keras.preprocessing.image_dataset_from_directory(
    directory,
    labels = "inferred",
    label_mode = "int",
    color_mode = "rgb",
    batch_size = batch_size,
    image_size = (img_height, img_width),
    shuffle = True,
    seed = 3,
    validation_split = 0.1,
    subset = "training"
)

ds_validation = tf.keras.preprocessing.image_dataset_from_directory(
    directory,
    labels = "inferred",
    label_mode = "int",
    color_mode = "rgb",
    batch_size = batch_size,
    image_size = (img_height, img_width),
    shuffle = True,
    seed = 3,
    validation_split = 0.1,
    subset = "validation"
)

class_names = ds_train.class_names
# print(class_names)

num_classes = len(class_names)

# Transfer Learning w/InceptionV3 Model (using pretrained model as feature extractor)

preprocess_input = keras.applications.inception_v3.preprocess_input

inception_model = keras.applications.InceptionV3(input_shape = [img_height,img_width,3], weights="imagenet", include_top=False)
inception_model.trainable = False
inception_model.summary()

inputs = keras.Input(shape=(img_height,img_width,3))
x = preprocess_input(inputs)
x = inception_model(x, training = False)

# Custom Classification Head (Explore other possibilities)
x = layers.Flatten()(x)
outputs = layers.Dense(num_classes, activation = "softmax")(x)

model = keras.Model(inputs, outputs)

model.summary()

model.compile(optimizer=keras.optimizers.Adam(),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

num_epochs = 7
history = model.fit(
  ds_train,
  epochs=num_epochs,
  verbose=2,
  validation_data=ds_validation
)

acc = history.history['accuracy']
val_acc = history.history['val_accuracy']

loss = history.history['loss']
val_loss = history.history['val_loss']

epochs_range = range(num_epochs)

plt.figure(figsize=(8, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Testing Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Testing Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Testing Loss')
plt.legend(loc='upper right')
plt.title('Training and Testing Loss')
# plt.show()
plt.savefig("inception_model.png", bbox_inches="tight")
<file_sep>import cv2
import os
import glob
from skimage import io, color, img_as_float32, img_as_ubyte
import numpy as np
from PIL import Image
import uuid

# Loads and resizes textures
def load_textures():
    # Load Textures
    img_dir = "./textures" # Directory for Textures
    data_path = os.path.join(img_dir,'*g')
    files = glob.glob(data_path)
    textures = []
    t_names = []
    for f1 in files:
        img = io.imread(f1, as_gray = True)
         # Resizes Textures to be 200 by 200
        img = cv2.resize(img, dsize = (200,200))
        img = img_as_float32(img)
        textures.append(img)

        # Parse texture name
        texture_name = (f1.split('\\')[-1]).split('.')[0]
        t_names.append(texture_name)

    # Returns list of textures + associated names
    return textures, t_names

# Generates and Saves Shape w/ Texture Applied
# Assumes original image is black background, white foreground
def generate_textures(img1,img_name,textures,t_names,dest_textured):
    textured_images = []

    for texture in textures:
        # Add images (background is texture, foreground is texture + shape)
        img2 = img1 + texture
        # Compare orig texture and img2, where not equal is our shape pixels
        new_image = np.where((img2 == texture),0.5,texture)

        textured_images.append(img_as_ubyte(new_image))

    save_images(textured_images, img_name, t_names, dest_textured)

# Saves textured images, based off original image name and textured image names
def save_images(images, img_name, t_names, dest):
    # Find Shape Name
    shape = img_name.split('\\')[-1].split('_')[0]

    for img,texture in zip(images,t_names):
        # Generate Name w/ UUID
        label = shape.lower() + "_" + texture
        filename  = str(uuid.uuid1()) + ".png"
        # Save Image in Dest
        new_path = dest + label + "/"
        try:
            os.mkdir(new_path)
        except:
            pass

        Image.fromarray(img).convert("L").save(new_path + filename)


text:
<file_sep>Reproduce Machine Learning
=====================================

Code for reproducing experiments in ["Improved Training of Wasserstein GANs"](https://arxiv.org/abs/1704.00028)

and ["Improving the Improved Training of Wasserstein GANs"](https://openreview.net/pdf?id=SJx9GQb0-)

The python code is modified based on the original code of two papers.

## Prerequisites

- Python, NumPy, TensorFlow(1.2.1), SciPy, Matplotlib
- A recent NVIDIA GPU

## Models

Configuration for all models is specified in a list of constants at the top of
the file, type of WGAN also needs to be specified. To run generative model for CT-WGAN and GP-WGAN on MNIST

- `python gan_mnist_testcode.py`

For the CIFAR10 dataset, edit the file to specify the path to the dataset in
`DATA_DIR` before running. CIFAR10 dataset is publicly available; the
download URL is in the file.

- `python gan_cifar_testcode.py`


text:
<repo_name>leticelvin/TreasureHunt-Pt1<file_sep>/u1_js_pt1_elv_let.js
var points = 0;

function addpoints() {
points = points + 5;
return points;
}

function removepoints() {
points = points - 5;
return points;
}

var chest1 = "x";
var chest2 = "x";
var chest3 = "x";
var chests = [chest1, chest2, chest3];
var concealedchests = [chest1, chest2, chest3];
var z;
z = Math.floor((Math.random() * 3) + 1);

//chestshuffle puts the diamond in a random chest
function chestshuffle(z) {
   switch(z) {
     case 1:
        chests[0] = "v";
        chests[1] = "x";
        chests[2] = "x";
      break;
     case 2:
        chests[0] = "x";
        chests[1] = "v";
        chests[2] = "x";
      break;
     case 3:
        chests[0] = "x";
        chests[1] = "x";
        chests[2] = "v";
      break;
      default:
      break;
   }
   return z;

}
//chestshuffle();

setTimeout(function() {
for (i=0; i<1; i++) {
console.log("-----------------------")
console.log("Time to guess! Pick a chest from 1-3")
console.log(chests) //Matches the video
console.log(z);
} 1000});

//different decisions depending on what number the user chooses by typing in openchest(number)
function guess(x) {
   chestshuffle(z);
   //console.log(arguments[0]);
   if (x == z) {
         console.log(chests);
         console.log("Woohoo! You found the diamond");
         addpoints();
         console.log("Your score is "  + points);
         console.log("-----------------------");
         console.log("Time to guess! Pick a chest from 1-3")
         console.log(concealedchests);
         z = Math.floor((Math.random() * 3) + 1);
         chestshuffle()
      } else {
         console.log(chests);
         console.log("Muhaha! You picked the wrong chest...");
         removepoints();
         console.log("Your score is "  + points);
         console.log("-----------------------");
         console.log("Time to guess! Pick a chest from 1-3")
         console.log(concealedchests);
         z = Math.floor((Math.random() * 3) + 1);
         chestshuffle()
   }
}