text:
<file_sep>package com.sape.feecalculator.utility;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtility {

   public static Date getDate(String dateStr) throws ParseException {
        String pattern = "dd/MM/yyyy";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

        return  simpleDateFormat.parse(dateStr);

    }
    public static String getStringDate(Date date) {
        String pattern = "dd/MM/yyyy";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);

        return simpleDateFormat.format(date);

    }
}
<file_sep>package com.sape.feecalculator.utility;

import com.sape.feecalculator.beans.Transaction;
import com.sape.feecalculator.beans.TransactionSummary;
import com.sape.feecalculator.calculator.FeeCalculation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

@Component
public class TransactionUtility {

    @Autowired
    @Qualifier(value = "intraDayFeeCalc")
    FeeCalculation intraTransactionCalc;

    @Autowired
    @Qualifier(value = "normalDayFeeCalc")
    FeeCalculation normalTransactionCalc;

    BiPredicate<Transaction,Transaction> clientPredicate=(t1,t2)->t1.getClientId().equals(t2.getClientId());
    BiPredicate<Transaction,Transaction> securityPredicate=(t1,t2)->t1.getSecurityId().equals(t2.getSecurityId());
    BiPredicate<Transaction,Transaction> datePredicate=(t1,t2)->t1.getTransactionDate().equals(t2.getTransactionDate());
    BiPredicate<Transaction,Transaction> transactionBiPredicate=(t1,t2)->t1.getTransactionType().equals(t2.getTransactionType());

    BiPredicate<TransactionSummary,TransactionSummary> clientSummaryPre=(t1,t2)->t1.getClientId().equals(t2.getClientId());
    BiPredicate<TransactionSummary,TransactionSummary> prioritySummaryPred=(t1,t2)->t1.getPriorityFlag().equals(t2.getPriorityFlag());
    BiPredicate<TransactionSummary,TransactionSummary> dateSummaryPre=(t1,t2)->t1.getTransactionDate().equals(t2.getTransactionDate());
    BiPredicate<TransactionSummary,TransactionSummary> transactionSummaryPre=(t1,t2)->t1.getTransactionType().equals(t2.getTransactionType());

    Comparator<TransactionSummary> compByCliendId=Comparator.comparing(TransactionSummary::getClientId);
    Comparator<TransactionSummary> compByTransactionType=Comparator.comparing(TransactionSummary::getTransactionType);
    Comparator<TransactionSummary> compByTransactionDate=Comparator.comparing(TransactionSummary::getTransactionDate);
    Comparator<TransactionSummary> compByPriority=Comparator.comparing(TransactionSummary::getPriorityFlag);

    public  List<TransactionSummary> getSummary(List<Transaction> list) throws ParseException {
        List<TransactionSummary> summaryList=new ArrayList<>();
        List<Integer> list1=new ArrayList<>();
        for(int i=0;i<list.size();i++)
        {
            boolean flag=false;
            int nonRead=0;
            for(int j=i+1;j<list.size();j++)
            {
                if(clientPredicate.and(securityPredicate)
                        .and(datePredicate)
                        .test(list.get(i),list.get(j))
                        &&transactionBiPredicate.negate().
                        test(list.get(i),list.get(j))&&!list1.contains(j))
                {
                    flag=true;
                    nonRead=j;
                    break;
                }
            }
            if(!list1.contains(i)) {
                if (flag) {
                    summaryList.add(intraTransactionCalc.doCalculation(list.get(i)));
                    summaryList.add(intraTransactionCalc.doCalculation(list.get(nonRead)));
                } else {
                    summaryList.add(normalTransactionCalc.doCalculation(list.get(i)));
                }
                list1.add(nonRead);
            }
        }
        return summaryList;

    }

    public  List<TransactionSummary> groupDataOnField(List<TransactionSummary> list)
    {
        List<TransactionSummary> summaryList=new ArrayList<>();
        List<Integer> list1=new ArrayList<>();
        for(int i=0;i<list.size();i++)
        {
            boolean flag=false;
            int nonRead=0;
            for(int j=i+1;j<list.size();j++)
            {
                if(clientSummaryPre
                        .and(dateSummaryPre)
                        .and(transactionSummaryPre)
                        .and(prioritySummaryPred)
                        .test(list.get(i),list.get(j))
                                &&!list1.contains(j))
                {
                    flag=true;
                    nonRead=j;
                    break;
                }
            }
            if(!list1.contains(i)) {
                if (flag) {
                    TransactionSummary transactionSummary=list.get(i);
                    transactionSummary.setProcessingFee(transactionSummary.getProcessingFee().add(list.get(nonRead).getProcessingFee()));
                    summaryList.add(transactionSummary);
                } else {
                    summaryList.add(list.get(i));
                }
                list1.add(nonRead);
            }
        }
        return summaryList;

    }

    public  List<TransactionSummary> sortDataOnField(List<TransactionSummary> list)
    {

        return list
                .stream()
                .sorted(compByCliendId.thenComparing(compByTransactionType).thenComparing(compByTransactionDate).thenComparing(compByPriority))
                .collect(Collectors.toList());

    }

}
<file_sep>package com.sape.feecalculator.config;

import com.sape.feecalculator.calculator.FeeCalculation;
import com.sape.feecalculator.calculator.IntraDayTransactionCalculatorImpl;
import com.sape.feecalculator.calculator.NormalTransactionCalculatorImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class BeanConfiguration {

    @Bean(value ="intraDayFeeCalc")
    public FeeCalculation intraDayFeeCalc() {
        return new FeeCalculation(new IntraDayTransactionCalculatorImpl());
    }
    @Bean(value = "normalDayFeeCalc")
    public FeeCalculation normalDayFeeCalc() {
        return new FeeCalculation(new NormalTransactionCalculatorImpl());
    }
}

<file_sep>package com.sape.feecalculator.beans;

import java.math.BigDecimal;
import java.util.Date;

public class TransactionSummary {

    private String clientId;
    private String transactionType;
    private Date transactionDate;
    private String priorityFlag;
    private BigDecimal processingFee;

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public Date getTransactionDate() {
        return transactionDate;
    }

    public void setTransactionDate(Date transactionDate) {
        this.transactionDate = transactionDate;
    }

    public String getPriorityFlag() {
        return priorityFlag;
    }

    public void setPriorityFlag(String priorityFlag) {
        this.priorityFlag = priorityFlag;
    }

    public BigDecimal getProcessingFee() {
        return processingFee;
    }

    public void setProcessingFee(BigDecimal processingFee) {
        this.processingFee = processingFee;
    }
}
<file_sep>readFilePath=C:/mypersonal/Testsapient/Sample_Input.csv
writeFilePath=C:/mypersonal/Testsapient/Output_Input.csv
<file_sep>package com.sape.feecalculator.beans;

import com.opencsv.bean.CsvBindByPosition;

public class Transaction {

    @CsvBindByPosition(position = 0)
    private String externalTransactionId;
    @CsvBindByPosition(position = 1)
    private String clientId;
    @CsvBindByPosition(position = 2)
    private String securityId;
    @CsvBindByPosition(position = 3)
    private String transactionType;
    @CsvBindByPosition(position = 4)
    private String   transactionDate;
    @CsvBindByPosition(position = 5)
    private String marketValue;
    @CsvBindByPosition(position = 6)
    private String priorityFlag;

    public String getExternalTransactionId() {
        return externalTransactionId;
    }

    public void setExternalTransactionId(String externalTransactionId) {
        this.externalTransactionId = externalTransactionId;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getSecurityId() {
        return securityId;
    }

    public void setSecurityId(String securityId) {
        this.securityId = securityId;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public String getTransactionDate() {
        return transactionDate;
    }

    public void setTransactionDate(String transactionDate) {
        this.transactionDate = transactionDate;
    }

    public String getMarketValue() {
        return marketValue;
    }

    public void setMarketValue(String marketValue) {
        this.marketValue = marketValue;
    }

    public String getPriorityFlag() {
        return priorityFlag;
    }

    public void setPriorityFlag(String priorityFlag) {
        this.priorityFlag = priorityFlag;
    }
}
<file_sep>package com.sape.feecalculator.beans;

import com.opencsv.bean.CsvBindByName;
import com.opencsv.bean.CsvBindByPosition;

public class TransactionDTO {

    @CsvBindByName(column ="Client Id")
    @CsvBindByPosition(position = 0)
    private String clientId;
    @CsvBindByName(column ="Transaction Type")
    @CsvBindByPosition(position = 1)
    private String transactionType;
    @CsvBindByName(column ="Transaction Date")
    @CsvBindByPosition(position = 2)
    private String transactionDate;
    @CsvBindByName(column ="Priority Flag")
    @CsvBindByPosition(position = 3)
    private String priorityFlag;
    @CsvBindByName(column ="Processing Fee")
    @CsvBindByPosition(position = 4)
    private String processingFee;

    public TransactionDTO(String clientId, String transactionType, String transactionDate, String priorityFlag, String processingFee) {
        this.clientId = clientId;
        this.transactionType = transactionType;
        this.transactionDate = transactionDate;
        this.priorityFlag = priorityFlag;
        this.processingFee = processingFee;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getTransactionType() {
        return transactionType;
    }

    public void setTransactionType(String transactionType) {
        this.transactionType = transactionType;
    }

    public String getTransactionDate() {
        return transactionDate;
    }

    public void setTransactionDate(String transactionDate) {
        this.transactionDate = transactionDate;
    }

    public String getPriorityFlag() {
        return priorityFlag;
    }

    public void setPriorityFlag(String priorityFlag) {
        this.priorityFlag = priorityFlag;
    }

    public String getProcessingFee() {
        return processingFee;
    }

    public void setProcessingFee(String processingFee) {
        this.processingFee = processingFee;
    }
}
<file_sep>package com.sape.feecalculator.repo;

import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;

import java.io.IOException;
import java.util.List;

public interface FileReadWriter {

     List readData(String fileName, Class c) throws IOException;
     void writeData(String fileName,List list,Class c) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException;
}
<file_sep>package com.sape.feecalculator.calculator;

import com.sape.feecalculator.beans.Transaction;
import com.sape.feecalculator.beans.TransactionSummary;

import java.text.ParseException;

public class FeeCalculation {

    TransactionCalculator transactionCalculator;

    public FeeCalculation(TransactionCalculator transactionCalculator)
    {
         this.transactionCalculator=transactionCalculator;
    }

    public TransactionSummary doCalculation(Transaction transaction) throws ParseException {
        return transactionCalculator.calculateCharge(transaction);
    }
}

languages: Java INI


text:
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-29 06:27
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0008_auto_20160529_1040'),
    ]

    operations = [
        migrations.AddField(
            model_name='blog',
            name='commen',
            field=models.PositiveIntegerField(default=0, verbose_name='评论'),
        ),
    ]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-29 02:17
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0005_auto_20160528_1822'),
    ]

    operations = [
        migrations.AlterField(
            model_name='blog',
            name='chapin',
            field=models.PositiveIntegerField(default=0, verbose_name='差评'),
        ),
        migrations.AlterField(
            model_name='blog',
            name='dianzan',
            field=models.PositiveIntegerField(default=0, verbose_name='点赞'),
        ),
        migrations.AlterField(
            model_name='blog',
            name='look',
            field=models.PositiveIntegerField(default=0, verbose_name='浏览量'),
        ),
    ]
<file_sep>#coding = utf-8
from django.db import models
from django.contrib import admin
from django.db.models import permalink
from a.fileds import ThumbnailImageField
from django.contrib.auth.models import AbstractUser
# Create your models here.

class Item(models.Model):
    text = models.TextField(default='')
    times = models.CharField(max_length=50)

class Tag(models.Model):
    """
    标签
    """

    name = models.CharField('名称', max_length=16)
class Category(models.Model):
    """
    分类
    """

    name = models.CharField('名称', max_length=16)
class Blog(models.Model):
    """
    博客
    """
    title = models.CharField('标题', max_length=32)
    author = models.CharField('作者', max_length=16)
    content = models.TextField('正文')
    created = models.DateTimeField('发布时间', auto_now_add=True)
    category = models.ForeignKey(Category, verbose_name='分类')
    tags = models.ManyToManyField(Tag, verbose_name='标签')
    dianzan = models.PositiveIntegerField('点赞', default=0)
    look = models.PositiveIntegerField('浏览量', default=0)
    chapin = models.PositiveIntegerField('差评', default=0)
    commen = models.PositiveIntegerField('评论', default=0)
class Comment(models.Model):
    """
    评论
    """

    blog = models.ForeignKey(Blog, verbose_name='博客')

    name = models.CharField('称呼', max_length=16)
    email = models.EmailField('邮箱')
    content = models.CharField('内容', max_length=140)

    created = models.DateTimeField('发布时间', auto_now_add=True)
class Day(models.Model):
    """
    日志
    """
    title = models.CharField('标题', max_length=32)
    author = models.CharField('作者', max_length=16)
    content = models.TextField('正文')
    created = models.DateTimeField('发布时间', auto_now_add=True)

class PhotoItem(models.Model):
    name = models.CharField(max_length=250)
    description = models.TextField()

    class Meta:
        ordering = ['name']

    def __str__(self):
        return self.name

    @permalink
    def get_absolute_url(self):
        return ('item_detail', None, {'pk': self.id})

class Photo(models.Model):
    item = models.ForeignKey(PhotoItem)
    title = models.CharField(max_length=100)
    image = ThumbnailImageField(upload_to='photos')
    caption = models.CharField(max_length=250, blank=True)

    class Meta:
        ordering = ['title']

    def __str__(self):
        return self.title

    @permalink
    def get_absolute_url(self):
        return ('photo_detail', None, {'pk': self.id})<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 11:41
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0012_auto_20160606_1937'),
    ]

    operations = [
        migrations.DeleteModel(
            name='MyUser',
        ),
    ]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-28 10:22
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0004_auto_20160526_1435'),
    ]

    operations = [
        migrations.AddField(
            model_name='blog',
            name='chapin',
            field=models.TextField(default='0', verbose_name='差评'),
        ),
        migrations.AddField(
            model_name='blog',
            name='dianzan',
            field=models.TextField(default='0', verbose_name='点赞'),
        ),
        migrations.AddField(
            model_name='blog',
            name='look',
            field=models.TextField(default='0', verbose_name='浏览量'),
        ),
    ]
<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 12:03
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0015_auto_20160606_2000'),
    ]

    operations = [
        migrations.DeleteModel(
            name='MyUser',
        ),
        migrations.AddField(
            model_name='tag',
            name='name',
            field=models.CharField(default=14, max_length=16, verbose_name='名称'),
            preserve_default=False,
        ),
    ]
<file_sep>#coding = utf-8
from django.shortcuts import render,redirect,HttpResponse
from app.models import Item,Blog,Comment,Day
import time
from django.contrib.auth import authenticate,login
from django.contrib.auth.models import User
from django.http import Http404
from .forms import CommentForm
#from haystack.forms import SearchForm
from django.views import generic
from .models import PhotoItem, Photo
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.conf import settings
from django.core.mail import send_mail
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
#登录系统
def home_page(request):
    if request.method == 'POST':
        username=request.POST['user']
        password=request.POST['<PASSWORD>']
        user = authenticate(username=username,password=<PASSWORD>)
        if user and user.is_active:
            login(request, user)
            request.session['username'] = username
            return redirect('list/')
        else:
            return redirect('/')
    return render(request,'home.html')

#主页
def list_page(request):
    username = request.session.get('username')
    if request.method == 'POST':
        Item.objects.create(text=request.POST['item_text'],times = time.strftime("%Y-%m-%d %X", time.localtime()))
    items = Item.objects.all()
    return render(request,'list.html',{'items':items,'username':username})

def logout_view(request):
    logout(request)
    return store_view(request)
def gy_page(request):
	return render(request,'gy.html')

#相册系统
class IndexView(generic.ListView):
    template_name = 'items/index.html'
    def get_queryset(self):
        return PhotoItem.objects.all()[:5]

class ListView(generic.ListView):
    model = PhotoItem
    template_name = 'items/items_list.html'

class ItemDetailView(generic.DetailView):
    model = PhotoItem
    template_name = 'items/items_detail.html'
class PhotoDetailView(generic.DetailView):
    model = Photo
    template_name = 'items/photos_detail.html'

#日志系统
def day_page(request):
    days = Day.objects.all().order_by('-created')
    return render(request,'day.html',{'days': days})
def new_day(request):
    try:
    	if request.method == 'POST':
            title = request.POST['title']
            author = request.POST['author']
            content = request.POST['content']
            errors = []
            if len(title) < 1:
                errors.append("标题不能为空")
                return render(request,'newday.html',{'errors':errors})
            if len(author) < 1:
                errors.append("作者不能为空")
                return render(request,'newday.html',{'errors':errors})
            if len(content) < 1:
                errors.append("内容不能为空")
                return render(request,'newday.html',{'errors':errors})
            Day.objects.create(title = request.POST['title'],author = request.POST['author'],content = request.POST['content'])
            return redirect("http://127.0.0.1:8000/list/day/")
    except Exception as e:
    	errors.append(str(e))
    	return render(request,'newday.html',{'errors':errors})
    return render(request,'newday.html')
def day_detail(request, Day_id):
    try:
        day = Day.objects.get(id=Day_id)
    except day.DoesNotExist:
        raise Http404
    return render(request, 'day-detail.html', {'day':day})

#动态
def dt_page(request):
	return render(request,'dt.html')

#更多
def gd_page(request):
	return render(request,'gd.html')

#个人信息系统
def xx_page(request):
    usernameas = request.session.get('username')
    if request.method == 'POST':
            username=request.POST['name']
            password1=request.POST['<PASSWORD>']
            password2=request.POST['<PASSWORD>']
            email=request.POST['email']
            phone=request.POST['phone']
            user = User.objects.get(username = usernameas)
            if user.password == <PASSWORD>:
                user.username = username
                user.password = <PASSWORD>
                user.email = email
                user.phone = phone
                user.save()
                request.session['username'] = username
                return redirect('http://127.0.0.1:8000/list')
    return render(request,'xx.html')

#注册系统
def userRegister(request):
    try:
        if request.method=='POST':
            username=request.POST['name']
            password1=request.POST['<PASSWORD>1']
            password2=request.POST['<PASSWORD>']
            email=request.POST['email']
            phone=request.POST['phone']
            errors=[]
            filterResult=User.objects.filter(username=username)
            if len(filterResult)>0:
                errors.append("用户名已存在")
                return render(request,'zhuce.html',{'errors':errors})
            if len(password1) < 6:
                errors.append("请输入大于6位数密码")
                return render(request,'zhuce.html',{'errors':errors})
            if password1!=password2:
                errors.append("两次输入的密码不一致!")
                return render(request,'zhuce.html',{'errors':errors})
            if len(email) < 9:
                errors.append("请输入有效邮箱")
                return render(request,'zhuce.html',{'errors':errors})
            from_email = settings.DEFAULT_FROM_EMAIL
            to_email = settings.SERVER_EMAIL
            user=User()
            user.username=username
            user.set_password(<PASSWORD>)
            user.email=email
            user.save()
            user.is_active=False
            newUser=authenticate(username=username,password=<PASSWORD>)
            message = "nasi"
            send_mail(u'注册用户验证信息',message, from_email,[email])
            if newUser is not None:
                send_mail('用户注册', '注册成功',from_email,[to_email], fail_silently=False)
                login(request, newUser)
                request.session['username'] = username
                return redirect("http://127.0.0.1:8000/list/")
    except Exception as e:
        errors.append(str(e))
        return render(request,'zhuce.html',{'errors':errors})
    return render(request,'zhuce.html')

#博客系统及评论系统及搜索系统
def blog_page(request):
    if request.method == "POST":
    	keywords = request.POST['q']
    	sform = SearchForm(request.POST)
    	posts = sform.search()
    	return render(request, 'search_list.html',
                  {'posts': posts, 'list_header': '关键字 \'{}\' 搜索结果'.format(keywords)})
    blogs = Blog.objects.all().order_by('-created')
    paginator = Paginator(blogs, 10)
    page = 1
    try:
    	contacts = paginator.page(page)
    except PageNotAnInteger:
    	contacts = paginator.page(1)
    except EmptyPage:
    	contacts = paginator.page(paginator.num_pages)
    return render(request,'blog.html', {"blogs": contacts})
def detail(request, blog_id):
    try:
        blog = Blog.objects.get(id=blog_id)
        blog.look = blog.look + 1
        blog.save()
    except Blog.DoesNotExist:
        raise Http404

    if request.method == 'GET':
        form = CommentForm()
        if request.GET.get('dianzan') :
        	blog.dianzan = blog.dianzan + 1
        	blog.save()
        if request.GET.get('chapin') :
        	blog.chapin = blog.chapin + 1
        	blog.save()
    else:
        form = CommentForm(request.POST)
        if form.is_valid():
            blog.commen = blog.commen + 1
            blog.save()
            cleaned_data = form.cleaned_data
            cleaned_data['blog'] = blog
            Comment.objects.create(**cleaned_data)
    ctx = {
        'blog': blog,
        'comments': blog.comment_set.all().order_by('-created'),
        'form': form
    }
    return render(request, 'blog-detail.html',ctx)

<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 11:37
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0011_auto_20160606_1909'),
    ]

    operations = [
        migrations.CreateModel(
            name='MyUser',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('password', models.CharField(max_length=128, verbose_name='password')),
                ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
                ('email', models.EmailField(db_index=True, max_length=255, unique=True, verbose_name='Email')),
                ('username', models.CharField(db_index=True, max_length=50, unique=True)),
                ('is_active', models.BooleanField(default=True)),
                ('is_admin', models.BooleanField(default=False)),
                ('types', models.IntegerField(default=0)),
                ('sex', models.IntegerField(default=1)),
                ('uid', models.CharField(max_length=50, null=True)),
                ('access_token', models.CharField(max_length=100, null=True)),
                ('url', models.URLField(null=True)),
                ('desc', models.CharField(max_length=2000, null=True)),
                ('avatar', models.CharField(max_length=500, null=True)),
            ],
            options={
                'db_table': 'user',
            },
        ),
        migrations.RemoveField(
            model_name='tag',
            name='name',
        ),
    ]
<file_sep><!DOCTYPE html>

    <meta charset="UTF-8">
    <title>{{ blog.title }}</title>
    <meta name = "viewport" content = "width=device - width,initial-scale = 1.0">
     <link href = "/static/bootstrap/css/bootstrap.min.css" rel = "stylesheet" media ="screen">

博客目录

{{ blog.title }}

            {{ blog.author }}
            {{ blog.created|date:"Y-m-d H:i" }}

            {{ blog.content }}
<form action="{% url 'detail' blog.id %}" method="GET">
<button class="btn btn-default" name = "dianzan" value= "5" type="submit"></button>  {{blog.dianzan}}
<button class="btn btn-default" name = "chapin" value= "5" type="submit"></button>  {{blog.chapin}}</form>

评论

            {% for comment in comments %}

                    {{ comment.name }} 说: {{ comment.content }}

            {% endfor %}

提交评论

            <form action="{% url 'detail' blog.id %}" method="post">

                {% csrf_token %}
                {% for field in form %}

                        {{ field.label }}: {{ field }}

                        {{ field.errors }}

                {% endfor %}
                <button type="submit" style="margin-top: 10px">提交</button>
            </form>

<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-06 11:09
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('app', '0010_auto_20160606_1848'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='newuser',
            name='groups',
        ),
        migrations.RemoveField(
            model_name='newuser',
            name='user_permissions',
        ),
        migrations.DeleteModel(
            name='NewUser',
        ),
    ]
<file_sep>"""a URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin
from app import views
urlpatterns = [
    #url(r'^admin/', include(admin.site.urls)),
    url(r'^$',views.list_page,name = 'list'),
    url(r'^gy/$',views.gy_page,name = 'gy'),
    url(r'^gd/$',views.gd_page,name = 'gd'),
    url(r'^dt/$',views.dt_page,name = 'dt'),
    url(r'^xx/$',views.xx_page,name = 'xx'),
    url(r'^photo/$', views.IndexView.as_view(), name='index'),
    url(r'^photo/list/$', views.ListView.as_view(), name='item_list'),
    url(r'^photo/(?P<pk>\d+)/$', views.ItemDetailView.as_view(), name='item_detail'),
    url(r'^photo/facker/(?P<pk>\d+)/$', views.PhotoDetailView.as_view(), name='photo_detail'),
    url(r'^day/$',views.day_page,name = 'day'),
    url(r'^day/new/$', views.new_day,name = 'newday'),
    url(r'^day/(\d+)/$', views.day_detail,name = 'day_detail'),
    url(r'^blog/$',views.blog_page,name = 'blog'),
    url(r'^blog/(\d+)/$', views.detail,name = 'detail'),
]

<file_sep>from django.contrib import admin
from .models import  Blog,Category,Day,Tag,Photo,PhotoItem

class PhotoInline(admin.TabularInline):
    model = Photo

class PhotoItemAdmin(admin.ModelAdmin):
    inlines = [PhotoInline]

admin.site.register(PhotoItem, PhotoItemAdmin)
admin.site.register(Photo)
admin.site.register([Category,Blog,Tag])
admin.site.register(Day)

branch_name: refs/heads/master

languages: HTML Python

repo_language: HTML

repo_name: draDgon/django


text:
<repo_name>matteo-ronchetti/Scripts<file_sep>/tribals.user.js
// ==UserScript==
// @name         tribals base
// @namespace    http://your.homepage/
// @version      0.2
// @description  enter something useful
// @author       You
// @match        https://it41.tribals.it/*
// @grant        none
// ==/UserScript==

function parseCost(el){return parseInt(el.getAttribute("data-cost"))}

//hide AD
if(document.querySelector("#SkyScraperAd"))document.querySelector("#SkyScraperAd").style.display = "none";
if(document.querySelector("#ContentAd"))document.querySelector("#ContentAd").style.display = "none";

//get the production rates
var prodWin = document.querySelector("#show_prod");
if(prodWin){
    var production = Array.prototype.slice.call(prodWin.querySelectorAll("strong")).map(function(el){return parseInt(el.innerHTML)});
}else{
    var production = JSON.parse(localStorage["::production"])
}
localStorage["::production"] = JSON.stringify(production);

//get the current resource state
var resources = [parseInt(document.querySelector("#wood").innerHTML),parseInt(document.querySelector("#stone").innerHTML),parseInt(document.querySelector("#iron").innerHTML)]

console.log("asa",production,resources);

var costRows = document.querySelectorAll("#buildings tr");
if(costRows)for(var i = 1;i < costRows.length;i++){
	var costElements = Array.prototype.slice.call(costRows[i].querySelectorAll("td")).splice(1,3);
    var costs = costElements.map(parseCost);
    var max = 0;var maxIndex = -1;
    if(costs.length == 3)for(var j = 0;j < 3;j++){
    	var time = (costs[j] - resources[j])/production[j];
    	if(time > max){
    		max = time;
    		maxIndex = j;
    	}
    }
    if(maxIndex > -1){
    	costElements[maxIndex].style.background = "hsla(0, 100%, 50%, 0.2)";
    }
}
<file_sep>/reports.user.js
// ==UserScript==
// @name         Inserisci nel simulatore
// @namespace    http://your.homepage/
// @version      0.2
// @description  enter something useful
// @author       You
// @match        https://it41.tribals.it/*
// @grant        none
// ==/UserScript==

function $create(tag,options){
    var res = document.createElement(tag);
    if(options)for(var o in options){
        if(o == "html"){
            res.innerHTML = options[o];
        }else{
            if(typeof options[o] == "string")res.setAttribute(o,options[o]);
        }
    }
    return res;
}

function createLink(title,link){
    var a = document.createElement("a");
    a.innerHTML = title;
    a.href = link;
    a.style.marginRight = "20px";
    return a;
}

function insertAfter(newNode, referenceNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

function tableRow(){
    var tr = $create("tr");
    var td = $create("td",{colspan: "2"});
    for (var i = 0; i < arguments.length; i++) {
        td.appendChild(arguments[i]);
    };
    tr.appendChild(td);
    return tr;
}

function extractUnits(table,offset){
    offset = (offset === undefined)?1:offset;
    var total = {};
    var died = {};
    var remaining = {};

    if(table){
        var totalEl = table.children[1].children;
        var diedEl = (table.children[2])?table.children[2].children:null;
        for(var i = offset;i < totalEl.length;i++){
            var unitName = totalEl[i].className.match(/unit-item-([^ ]+)/)[1];
            total[unitName] = parseInt( totalEl[i].innerHTML);
            died[unitName] = diedEl?parseInt( diedEl[i].innerHTML):0;
            remaining[unitName] = total[unitName] - died[unitName];
        }
    }

    return {total: total,died: died,remaining: remaining};
}

function extractAdditionals(table){
    var obj = {};

    var match = table.innerHTML.match(/<td>\+([0-9])%/);
    if(match){
        obj.flag = parseInt(match[1])-1;
    }else{
        obj.flag = 0;
    }

    return obj;
}

window.extractUnits = extractUnits;

function inAdd(a,b){
    for(var p in a.total){
        if(b.total[p])a.total[p] += b.total[p];
    }
}

function createSimulatorLink(label,att,def,attBonus,defBonus,wallLevel){
    var link = window.location.origin+"/game.php?screen=place&mode=sim&simulate";

    if(att){
        for(var unit in att){
            link += "&att_"+unit+"="+att[unit];
        }
        link += "&att_flag="+attBonus.flag;
    }

    if(def){
        for(var unit in def){
            link += "&def_"+unit+"="+def[unit];
        }
        link += "&def_flag="+defBonus.flag;
    }

    if(wallLevel){
        link += "&def_wall="+wallLevel;
    }

    return createLink(label,link);
}

var reportContainer = document.querySelector("td [colspan='2'][valign='top']");

var defenseTable = document.getElementById("attack_info_def").children[0];
var attackTable = document.getElementById("attack_info_att").children[0];
var attackUnitsTable = document.getElementById("attack_info_att_units").children[0];
var defenseUnitsTable = document.getElementById("attack_info_def_units").children[0];

var attackUnits = extractUnits(attackUnitsTable);
var defenseUnits = extractUnits(defenseUnitsTable);

var attackBonus = extractAdditionals(attackTable);
var defenseBonus = extractAdditionals(defenseTable);

if(document.getElementById("attack_spy_resources")){//se è una spiata
    var awayElement = document.querySelector("#attack_spy_away .vis");
    var awayUnits = extractUnits(awayElement?awayElement.children[0]:null,0);
    var buildings = JSON.parse(document.getElementById("attack_spy_building_data").getAttribute("value"));
    console.log(buildings);
    var wall = buildings.find(function(build){return build.id == "wall"});
    inAdd(defenseUnits,awayUnits);
    reportContainer.appendChild(createSimulatorLink(" » Simula piallata",null,defenseUnits.total,null,defenseBonus,wall.level));
}else{
    var attTotalLink = createSimulatorLink("Inserisci nel simulatore",attackUnits.total,null,attackBonus);
    var attRemainingLink = createSimulatorLink("Inserisci rimanenti nel simulatore",attackUnits.remaining,null,attackBonus);
    attackTable.appendChild(tableRow(attTotalLink,attRemainingLink));

    var defRemainingLink = createSimulatorLink("Inserisci rimanenti nel simulatore",null,defenseUnits.remaining,null,defenseBonus);
    var defTotalLink = createSimulatorLink("Inserisci nel simulatore",null,defenseUnits.total,null,defenseBonus);
    defenseTable.appendChild(tableRow(defTotalLink,defRemainingLink));

    reportContainer.appendChild(createSimulatorLink(" » Inserisci tutto nel simulatore",attackUnits.total,defenseUnits.total,attackBonus,defenseBonus));
}

repo_language: JavaScript

repo_name: matteo-ronchetti/Scripts


text:
<repo_name>styrofomeBoots/pyCasso<file_sep>/pycasso.py
import os
import functools
import pygetwindow as gw
import time
import pyautogui as ag
from PIL import Image, ImageGrab

ag.FAILSAFE = True

os.system('start mspaint.exe')

time.sleep(2)

pw = gw.getWindowsWithTitle('Untitled - Paint')[0]

time.sleep(2)

pw.maximize()
ag.click(x=187, y=87, clicks=1, button='left')  # open resize
time.sleep(1)
ag.click(x=222, y=156, clicks=1, button='left')  # change to pixels
time.sleep(1)
ag.click(x=74, y=267, clicks=1, button='left')  # turn off maintain ratio
time.sleep(1)
ag.click(x=244, y=192, clicks=2, button='left', interval=.2)
time.sleep(1)
ag.typewrite('715', interval=.2)  # enter height
time.sleep(1)
ag.click(x=235, y=229, clicks=2, button='left', interval=.2)
time.sleep(1)
ag.typewrite('461', interval=.2)  # enter width
time.sleep(1)
ag.click(x=155, y=452, clicks=1, button='left')

pw.resizeTo(988, 796)

im = Image.open('shiba.jpg')
im.show()
time.sleep(1)
ph = gw.getWindowsWithTitle('Photos')[0]

grey_tuple = (34, 34, 34)
ag.moveTo(1348, 322)
x_move_from = 1348
y_move_from = 322
x_start = 0
y_start = 0

while x_start == 0:
    x_tuple = ImageGrab.grab().load()[x_move_from, y_move_from]
    if grey_tuple != x_tuple:
        x_move_from = x_move_from - 1
        ag.moveTo(x_move_from, y_move_from)
    else:
        x_start = x_move_from + 3

x_move_from = 1348

while y_start == 0:
    y_tuple = ImageGrab.grab().load()[x_move_from, y_move_from]
    if grey_tuple != y_tuple:
        y_move_from = y_move_from - 1
        ag.moveTo(x_move_from, y_move_from)
    else:
        y_start = y_move_from + 3

print(x_start)
print(y_start)

# start at x 68
# pick brush at 383 136
# edit color at 860 78
# activate window 839 344
# activate red 681 463
# activate green 677 484
# activate blue 678 510
# confirm color at 302 533

start_paint_x = 68
start_paint_y = y_start

def click_paint():
    ag.click(x=839, y=344, clicks=1, button='left')

click_paint()
ag.click(x=269, y=102, clicks=1, button='left')
time.sleep(.1)
ag.moveTo(383, 136)
ag.click(x=383, y=136, clicks=1, button='left')
# get color from picture start

def choose_color(red, green, blue):
    ag.click(x=860, y=78, clicks=1, button='left')
    time.sleep(.1)
    ag.click(x=681, y=463, clicks=2, button='left', interval=.1)
    time.sleep(.1)
    ag.typewrite(str(red), interval=.1)
    ag.click(x=678, y=485, clicks=2, button='left', interval=.1)
    time.sleep(.1)
    ag.typewrite(str(green), interval=.1)
    ag.click(x=679, y=508, clicks=2, button='left', interval=.1)
    time.sleep(.1)
    ag.typewrite(str(blue), interval=.1)
    ag.click(x=302, y=533, clicks=2, button='left', interval=.1)

ag.moveTo(x_start, y_start)
x_photo = x_start
y_photo = y_start
# pic_height = 198
# pic_width = 298
pic_height = 0
pic_width = 0

# where it starts paintng in paint
x_paint = 68
y_paint = y_start

painting = True
while painting:
    if pic_width <= 298:
        color_tup = ImageGrab.grab().load()[x_photo, y_photo]
        click_paint()
        choose_color(color_tup[0], color_tup[1], color_tup[2])
        ag.moveTo(x_paint, y_paint)
        ag.click(x=x_paint, y=y_paint, clicks=1, button='left', duration=1)
        pic_width += 1
        x_photo += 1
        x_paint += 1
    elif pic_height <= 198:
        pic_width = 0
        x_photo = x_start
        x_paint = 68
        pic_height += 1
        y_photo += 1
        y_paint += 1
    else:
        painting = True

# print(ag.position())

# ag.moveTo(383, 136)
<file_sep>/README.md
# PyCasso

## Attempting to Artistically Recreate Images in MS Paint

### Initial Image

### First Attempt

It works. But it takes about 3 seconds per pixel with 300x200 pixels. Trying to find a way to
manipulate MS Paint directly instead of using pyAutoGui. I also plan on skipping pixels and using wider
brush strokes to give off a more "painted" look. Right now it looks like it is copying the image pixel for pixel.

languages: Markdown Python

repo_language: Markdown

repo_name: styrofomeBoots/pyCasso


text:
<file_sep># Sublime Text SVG Snippets

Basic SVG elements for Sublime Text 2 and 3.

# Installation

Clone this repository into your Sublime Text User Packages folder.
For ST3 on Mac OS X it's:
```
/Users/<user>/Library/Application Support/Sublime Text 3/Packages/User
```


text:
<repo_name>MSviridenkov/TicTacToeOnline<file_sep>/components/Game.js
/**
 * Created by MSviridenkov on 10.03.17.
 */
'use strict';
import React from 'react';
import Sound from 'react-sound';
import Square from './Square';

const myTurnStatus = 'It\'s your turn';
const opponentsTurnStatus = 'Waiting for the opponent\'s turn...';

class Game extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            squares: Array(9).fill(null),
            isMyTurn: this.props.host,
            status: this.props.host ? myTurnStatus : opponentsTurnStatus,
            buttonTransparent: true,
            playClickSound: false
        };

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

    componentDidMount() {
        this.props.socket.on('after opponent turn', this.changeStateAfterTurn);
    }

    /**
     * Изменяет состояние (состояние поля, может ли игрок ходить в данный момент,
     * статус игры) после совершенного кем-либо хода в зависимости от переданного
     * в параметрах массива состояний квадратов поля.
     * Для этого, в том числе, определяется: настала ли ничья; определился ли победитель, и кто он.
     * @param squares
     */
    changeStateAfterTurn(squares) {
        const draw = calculateDraw(squares);
        const winner = calculateWinner(squares);

        let newStatus;
        let newIsMyTurn = !this.state.isMyTurn;

        if (draw) {
            newStatus = 'DRAW!';
            newIsMyTurn = false;
        } else if (winner) {
            if ((winner === 'X' && this.props.host) || (winner === 'O' && !this.props.host)) {
                newStatus = 'YOU WIN!';
            } else {
                newStatus = 'YOU LOSE!';
            }
            newIsMyTurn = false;
        } else {
            newStatus = newIsMyTurn ? myTurnStatus : opponentsTurnStatus;
        }

        this.setState({
            squares: squares,
            isMyTurn: newIsMyTurn,
            status: newStatus,
            playClickSound: true
        });
    }

    /**
     * Изменяет состояние квадратов поля после клика на один из квадратов.
     * Сообщает серверу о том, что был совершен ход.
     * @param i
     */
    handleClick(i) {
        const squares = this.state.squares.slice();
        squares[i] = this.props.host ? 'X' : 'O';
        this.props.socket.emit('next turn', {squares: squares, host: this.props.host, roomId: this.props.roomId});
        this.changeStateAfterTurn(squares);
    }

    /**
     * Отрисовывает i-й квадрат поля.
     * @param i
     * @returns {XML}
     */
    renderSquare(i) {
        return <Square value={this.state.squares[i]}
                       isMyTurn={this.state.isMyTurn}
                       clicked={(this.state.squares[i] != null)}
                       host={this.props.host}
                       onClick={() => this.handleClick(i)} />;
    }

    render() {
        return (

{this.state.playClickSound ? <Sound url="/sounds/click.wav" playStatus={Sound.status.PLAYING}/> : null}

{this.state.status}

                        {this.renderSquare(0)}
                        {this.renderSquare(1)}
                        {this.renderSquare(2)}

                        {this.renderSquare(3)}
                        {this.renderSquare(4)}
                        {this.renderSquare(5)}

                        {this.renderSquare(6)}
                        {this.renderSquare(7)}
                        {this.renderSquare(8)}

        );
    }
}

/**
 * Определяет выявился ли победитель на основе переданного
 * в параметрах массива состояний квадратов поля.
 * Возвращает победителя (X или O) или null, если он не выявлен.
 * @param squares
 * @returns {*}
 */
function calculateWinner(squares) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6],
    ];
    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
            return squares[a];
        }
    }
    return null;
}

/**
 * Определяет, настала ли ничья.
 * @param squares
 * @returns {boolean}
 */
function calculateDraw(squares) {
    var draw = true;
    for (let i = 0; i < squares.length; i++) {
        draw = draw && (squares[i] != null);
    }
    return draw;
}

export default Game
<file_sep>/components/MessageList.js
/**
 * Created by MSviridenkov on 12.03.17.
 */
'use strict';
import React from 'react';
import Message from './Message';

class MessageList extends React.Component {
    /**
     * Прокручивает чат до нижнего сообщения в списке сообщений.
     */
    scrollToBottom() {
        const scrollHeight = this.messageList.scrollHeight;
        const height = this.messageList.clientHeight;
        const maxScrollTop = scrollHeight - height;
        this.messageList.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
    }

    componentDidUpdate() {
        this.scrollToBottom();
    }

    render() {
        return (

 {this.messageList = div;}}>
                {
                    this.props.messages.map((message, i) => {
                        return (
                            <Message
                                key={i}
                                user={message.user}
                                text={message.text}
                            />
                        );
                    })
                }

        );
    }
};

export default MessageList
<file_sep>/browserify-build.command
browserify -t [ babelify --presets [ es2015 react ] ] index.js -o public/app.js

languages: Shell JavaScript

repo_language: Shell

repo_name: MSviridenkov/TicTacToeOnline


text:
<repo_name>mediapole/Travel_Display_Mobile<file_sep>/js/ini-travel.js
label = new Array();

label['home'] = {fr: "Agence"};
label['list'] = {fr: "Liste des séjours"};
label['product'] = {fr: "Séjour"};
label['favorite'] = {fr: "Favoris"};
label['contact'] = {fr: "Contact"};
label['back'] = {fr: "Retour"};
label['currency'] = {fr: "€"};


text:
<file_sep># unique-book-ids
Test repo for apicurio


text:
<repo_name>Zelcus/portfolio<file_sep>/src/components/card.js
import * as React from "react";

export const Card = ({ name, imageSrc }) => {
    return (

{name}

    );
};
<file_sep>/src/styles/variables.scss
$mainBlack: #232129;

$smallSpacing: 24px;
$mediumSpacing: 48px;
$largeSpacing: 94px;
<file_sep>/src/pages/index.js
import "../../gatsby-browser.js";
import * as React from "react";
import { Navigator } from "../components/nav.js";
import "../styles/main.scss";

const IndexPage = () => {
    return (

            <Navigator />
            <title>Home Page</title>

Zacharias

<NAME>

    );
};

export default IndexPage;
<file_sep>/src/pages/code.js
import * as React from "react";
import "../styles/main.scss";
import { Card } from "../components/card.js";
import { Navigator } from "../components/nav.js";
const CodePage = () => {
    return (

            <Navigator />
            <title>Code Page</title>

                <Card name="Lime Technologies" image="" />

    );
};

export default CodePage;

branch_name: refs/heads/main

languages: SCSS JavaScript

repo_language: SCSS

repo_name: Zelcus/portfolio


text:
<file_sep>import { Component, OnInit } from '@angular/core';
import { PhotoService } from '../photo/photo.service';

@Component({
  selector: 'app-photo-list',
  templateUrl: './photo-list.component.html',
  styleUrls: ['./photo-list.component.css']
})
export class PhotoListComponent implements OnInit {

  photos:Object[] = []; //Array de photos que será exibido no template do component

  constructor(private photoservice: PhotoService ){ //constructor instancia o HttpClient para que a requisição da API seja realizada
  }

  ngOnInit():void{

    this.photoservice.listFromUser('flavio')
      .subscribe(photos=>{ this.photos = photos })
  }
}

repo_language: TypeScript

repo_name: smolskig/AluraPic