language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
Shell | UTF-8 | 559 | 3.328125 | 3 | [] | no_license | #!/bin/bash
ls -1 /home/dean/Music > /tmp/artists
while read artist; do
echo "----------------------------------------------------"
echo ${artist}
echo "----------------------------------------------------"
cd "/home/dean/Music/${artist}"
ls -1 . > /tmp/albums
while read album; do
cd "/home/dean/Music/${artist}/${album}"
tmp_artist=`find . -name "01*" -exec id3v2 -l {} \; | egrep 'TPE' \
| awk -F':' '{print $2}'`
echo "${tmp_artist}: ${album}"
done < /tmp/albums
echo ""
done < /tmp/artists
|
Java | UTF-8 | 1,422 | 2.09375 | 2 | [] | no_license | package com.xsd.jx.bean;
/**
* Date: 2020/10/12
* author: SmallCake
*/
public class VersionResponse {
/**
* desc : string
* id : 0
* is_must : 0
* platform : 0
* url : string
* version : 0
* version_name : string
*/
private String desc;
private int id;
private int is_must;
private int platform;
private String url;
private int version;
private String version_name;
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIs_must() {
return is_must;
}
public void setIs_must(int is_must) {
this.is_must = is_must;
}
public int getPlatform() {
return platform;
}
public void setPlatform(int platform) {
this.platform = platform;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public String getVersion_name() {
return version_name;
}
public void setVersion_name(String version_name) {
this.version_name = version_name;
}
}
|
C# | UTF-8 | 458 | 3.078125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LineNumbers
{
class Program
{
static void Main(string[] args)
{
string[] input = File.ReadAllLines("input.txt");
var output = input.Select((line, index) => $"{index + 1}. {line}");
File.WriteAllLines("numberedOutput.txt", output);
}
}
}
|
C# | UTF-8 | 1,063 | 3.359375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Batman.store
{
public abstract class Article
{
public Guid Id { get; private set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public decimal Price { get; private set; }
public uint Count { get; set; }
protected Article(string manufacturer, string model, decimal price, uint count)
{
this.Id = Guid.NewGuid();
this.Manufacturer = manufacturer;
this.Model = model;
if (price>=0)
{
this.Price = price;
}
else
{
throw new StoreException("Price must be non negative");
}
this.Count = count;
}
public override string ToString()
{
string printArticle = GetType().Name + " " + this.Manufacturer + " " + this.Model;
return printArticle;
}
}
}
|
C# | UTF-8 | 535 | 2.953125 | 3 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
using System.Text;
namespace A7
{
public class Tarea
{
public string name { get; set; }
public string encargado { get; set; }
public int horas { get; set; }
public Tarea(string name, string encargado, int horas)
{
this.name = name; this.encargado = encargado; this.horas = horas;
}
public override string ToString()
{
return name + " - " + encargado + " - " + horas;
}
}
}
|
C# | UTF-8 | 6,367 | 2.59375 | 3 | [] | no_license | using AmazonsGameLib;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Point = AmazonsGameLib.Point;
namespace GamePlayer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public Game Game { get; set; }
public Stack<(Move, bool)> MoveHistoryStack = new Stack<(Move, bool)>();
public Stack<(Move, bool)> MoveUndoHistoryStack = new Stack<(Move, bool)>();
Owner ComputerPlaying = AmazonsGameLib.Owner.None;
public AmazonBoardControl BoardControl { get; set; }
public MainWindow()
{
}
private void NewCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
MainGrid.Children.Clear();
Game = new Game();
Game.Begin(null, null, 10);
MoveHistoryStack.Clear();
BoardControl = new AmazonBoardControl(Game.CurrentBoard.Clone(), false);
BoardControl.MoveUpdated += BoardControl_MoveUpdated;
MainGrid.Children.Add(BoardControl);
MainGrid.UpdateLayout();
}
private void BoardControl_MoveUpdated(Move move, bool reverse)
{
MoveHistoryStack.Push((move, reverse));
if (reverse)
Game.ApplyReverseMove(move);
else
Game.ApplyMove(move);
}
private void SaveCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = Game != null && BoardControl != null;
}
private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var saveFileDialog = new SaveFileDialog();
saveFileDialog.DefaultExt = "json";
saveFileDialog.AddExtension = true;
saveFileDialog.Filter = "json|*.json";
saveFileDialog.Title = "Save Game";
if (saveFileDialog.ShowDialog(this).Value)
{
string json = Serializer.Serialize(Game);
using (StreamWriter writer = new StreamWriter(File.Open(saveFileDialog.FileName, FileMode.Create)))
{
writer.Write(json);
}
}
}
private void OpenCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
var openFileDialog = new OpenFileDialog();
openFileDialog.DefaultExt = "json";
openFileDialog.Title = "Open Game";
if (openFileDialog.ShowDialog(this).Value)
{
string json = "";
using (StreamReader reader = new StreamReader(File.Open(openFileDialog.FileName, FileMode.Open)))
{
json = reader.ReadToEnd();
}
Game openGame = Serializer.Deserialize<Game>(json);
if (openGame == null)
{
MessageBox.Show($"Error creating game from file {openFileDialog.FileName}");
return;
}
Game = openGame;
BoardControl = new AmazonBoardControl(Game.CurrentBoard.Clone(), false);
BoardControl.MoveUpdated += BoardControl_MoveUpdated;
MainGrid.Children.Clear();
MainGrid.Children.Add(BoardControl);
MainGrid.UpdateLayout();
}
}
private void UndoCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = MoveHistoryStack.Count > 0;
}
private void UndoCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
(Move move, bool reverse) = MoveHistoryStack.Pop();
MoveUndoHistoryStack.Push((move, reverse));
Game.UndoLastMove();
BoardControl.SetBoard(Game.CurrentBoard.Clone());
}
private void RedoCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = MoveUndoHistoryStack.Count > 0;
}
private void RedoCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
(Move move, bool reverse) = MoveUndoHistoryStack.Pop();
MoveHistoryStack.Push((move, reverse));
if (reverse) Game.ApplyReverseMove(move);
else Game.ApplyMove(move);
BoardControl.SetBoard(Game.CurrentBoard);
}
private void PlayCommand_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = Game != null && BoardControl != null && !Game.IsComplete();
}
private void PlayCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
AnalysisGraph analysisGraph = new AnalysisGraph();
var optimusDeep = new OptimusDeep(3, analysisGraph);
optimusDeep.BeginNewGame(Game.CurrentPlayer, 10);
ComputerPlaying = Game.CurrentPlayer;
Cursor orgCursor = Cursor;
Cursor = Cursors.Wait;
BoardControl.SetReadOnlyTillNextDraw();
Task.Run(() =>
{
var cancellationTokenSrc = new CancellationTokenSource(9000);
var bestMoveTask = optimusDeep.PickBestMoveAsync(Game.CurrentBoard, cancellationTokenSrc.Token);
return bestMoveTask.Result;
}).ContinueWith((t) =>
{
Move move = t.Result;
Dispatcher.Invoke(() =>
{
BoardControl.ApplyMove(move, false);
Cursor = orgCursor;
});
});
}
}
}
|
Java | UTF-8 | 3,468 | 2.265625 | 2 | [] | no_license | package train;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import utils.StringIntegerList;
import utils.StringIntegerList.StringInteger;
import utils.StringDoubleList;
import utils.StringDoubleList.StringDouble;
public class GetProbMapred {
public static class GetProbMapper extends
Mapper<Text, Text, Text, Text> {
public static Map<String, Integer> professionCount = new HashMap<String, Integer>();
public static Integer totalCount = 0;
protected void setup(Mapper<Text, Text, Text, Text>.Context context)
throws IOException, InterruptedException {
// TODO: load articleCount, articlePerProfessionCounts
InputStream is = this.getClass().getResourceAsStream("ArticleCounts");
BufferedReader br = new BufferedReader(new InputStreamReader(is)); //Open text
String line;
while ((line = br.readLine()) != null) {
String[] splitter = line.split("\t");
professionCount.put(splitter[0], Integer.parseInt(splitter[1]));
totalCount += Integer.parseInt(splitter[1]);
}
super.setup(context);
}
public void map(Text profession, Text LemmaList, Context context)
throws IOException, InterruptedException {
StringIntegerList list = new StringIntegerList();
list.readFromString(LemmaList.toString());
Map<String, Double> lemmaProb = new HashMap<String, Double>();
lemmaProb.put("__LABEL__", (double)totalCount/professionCount.get(profession.toString()));
for (StringInteger stringInt : list.getIndices()) {
String lemma = stringInt.getString();
Integer count = stringInt.getValue();
double probability = (double)count / professionCount.get(profession.toString());
lemmaProb.put(lemma, probability);
}
StringDoubleList sdl = new StringDoubleList(lemmaProb);
context.write(new Text(profession.toString()), new Text(sdl.toString()));
}
}
public static void main(String[] args)
throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: GetProbMapred <input-filepath> <output-filepath>");
System.exit(2);
}
Job job = Job.getInstance(conf, "get lemma probabilities per profession");
job.setJarByClass(GetProbMapred.class);
job.setMapperClass(GetProbMapper.class);
//job.setNumReduceTasks(0);
job.setInputFormatClass(KeyValueTextInputFormat.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
job.getConfiguration().set("mapreduce.job.queuename", "hadoop14");
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
} |
PHP | UTF-8 | 696 | 3.140625 | 3 | [
"MIT"
] | permissive | <?php
/*
* Client-side Request
*
* This script will make a request to google.com and output the response.
*/
// Include the autoload script.
require_once('../vendor/autoload.php');
use pjdietz\WellRESTed\Request;
// Make a requst to Google in one line:
$rqst = new Request();
$rqst->uri = 'https://www.google.com/search?q=my+search+terms';
// You could also set the members individually, like this:
//$rqst->protocol = 'https';
//$rqst->hostname = 'www.google.com';
//$rqst->path = '/search';
//$rqst->query = array('q' => 'my search terms');
// Make the request and obtain an Response instance.
$resp = $rqst->request();
// Output the response body and exit.
print $resp->body;
exit;
|
PHP | UTF-8 | 2,353 | 2.546875 | 3 | [] | no_license | <?php
/**
* Import Links from csv-file.
*/
class MaintenanceShell extends Shell {
var $uses = array('Hit', 'User', 'Link');
function startup() {
$this->out(str_repeat("-", 72));
$this->out(Configure::read('Site.Title').'-Maintenance');
$this->out(str_repeat("-", 72));
$this->out('App : '. APP_DIR);
$this->out('Path: '. ROOT . DS . APP_DIR);
$this->out(str_repeat("-", 72));
$this->out('');
}
function main() {
$out = "\t - ClearHits [-days 12]\t defaults to value from config/app.php\n";
$out .= "\t - ClearApplicants [-days 12]\tdefaults to 14 days\n";
$out .= "\t - favicons";
$this->out($out);
}
function ClearHits() {
$old = (key_exists('days', $this->params)) ? (int) $this->params['days']:Configure::read('Clicks.NoCountPeriod');
$out = "Deleting hits older then ".$old." days from hits-table.";
$this->out($out);
$this->Hit->query('DELETE FROM hits WHERE (TO_DAYS(NOW()) - TO_DAYS(created)) > '.$old);
}
function favicons() {
App::import('Vendor', 'favicon', array('file'=>'favicon.php'));
$conditions = array(array('or'=>array(array('Link.status'=>ACTIVE),
array('Link.status'=>WARNING))));
$links = $this->Link->find('all', array('conditions'=>$conditions,
'fields'=>array('id', 'url'),
'recursive'=>-1));
foreach ($links as $link) {
$icon = new favicon($link['Link']['url'], $link['Link']['id']);
if ($icon->has_icon) {
$icon->save();
$this->out('ok');
} else {
$this->out('no icon');
}
unset($icon);
}
}
function ClearApplicants() {
$old = (key_exists('days', $this->params)) ? (int) $this->params['days']:14;
$out = "Deleting applicants older then ".$old." days from users-table.";
$this->out($out);
$this->Hit->query('DELETE FROM users WHERE group_id = 1 AND (TO_DAYS(NOW()) - TO_DAYS(created)) > '.$old);
}
}
?>
|
C# | UTF-8 | 802 | 2.90625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BS_CS_Challenge_Game
{
class CECS105 : CardInterface
{
string thisImage;
public CECS105()
{
thisImage = "CECS 105";
}
public override string Play(Player p)
{
if(p.getCurrentRoom() == 14 || p.getCurrentRoom() == 17)
{
p.addLChip(1);
return (p.getPlayerName() + " played " + thisImage + " for 1 learning chip");
}
return (p.getPlayerName() + " played " + thisImage + " FAILED");
}
public override string getImage()
{
return thisImage;
}
}
}
|
C++ | UTF-8 | 905 | 2.875 | 3 | [] | no_license | #include"Snake.h"
#include<algorithm>
#include<iostream>
#include<FL/Fl.H>
#include<FL/Fl_Box.H>
#include<FL/fl_draw.H>
using namespace std;
static const int CELL_SIZE = 8;
Snake::Snake(int x, int y): Fl_Box(x, y, 300,300, "my snake"){
x0_ = x;
y0_ = y;
for(int i = 0; i < 5; i++){
s_.push_back(Point(15+i, 15));
}
checkGameStatus_();
}
Snake::~Snake(){
}
void Snake::draw(){
Fl_Box::draw();
cout<<"draw"<<endl;
int x, y;
// draw grid
for(int i = 0; i< 30; i++){
for(int j = 0; j < 30; j++){
x = x0_ + i * CELL_SIZE;
y = y0_ + j * CELL_SIZE;
fl_draw_box(FL_UP_BOX, x, y,CELL_SIZE, CELL_SIZE,FL_GRAY);
cout<<"5"<<endl;
}
}
// draw snake
for(auto i : s_){
x = x0_ + i.x;
y = y0_ + i.y;
fl_draw_box(FL_UP_BOX, x, y, CELL_SIZE, CELL_SIZE, FL_DARK1);
}
}
int Snake::handle(int event){
}
void Snake::checkGameStatus_(){
this->redraw();
}
|
Java | UTF-8 | 710 | 1.6875 | 2 | [] | no_license | package defpackage;
/* renamed from: cfx reason: default package */
final /* synthetic */ class cfx implements android.view.View.OnClickListener {
private final com.google.android.libraries.onegoogle.accountmenu.internal.SelectedAccountHeaderView a;
cfx(com.google.android.libraries.onegoogle.accountmenu.internal.SelectedAccountHeaderView selectedAccountHeaderView) {
this.a = selectedAccountHeaderView;
}
public final void onClick(android.view.View view) {
com.google.android.libraries.onegoogle.accountmenu.internal.SelectedAccountHeaderView selectedAccountHeaderView = this.a;
selectedAccountHeaderView.k.c().d().a(view, selectedAccountHeaderView.n.c());
}
}
|
Python | UTF-8 | 583 | 3.921875 | 4 | [] | no_license | import math
def f(x):
return x**3 + 4 * x**2 - 10
def g(x):
return math.sqrt(10/(x+4))
def fixedPoint(xa, iter, tol):
fx = f(xa)
cont = 0
error = tol + 1
xn = 0
while((fx != 0) and error > tol and cont < iter):
xn = g(xa)
fx = f(xn)
error = abs(xn - xa)
xa = xn
cont += 1
if fx == 0:
print("Xa: ", xa, " is a root")
elif error < tol :
print("Xa: ", xa, " approximate root with tolerance: ", tol)
else:
print("Fail in iteration: ", iter)
fixedPoint(1.5, 11, 0.000000005) |
Markdown | UTF-8 | 1,485 | 2.515625 | 3 | [
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ---
---
---
title: 一九三二年
---
无题[447]
血沃中原肥劲草,寒凝大地发春华。
英雄多故谋夫病,泪洒崇陵噪暮鸦。[448]
一月
偶成[449]
文章如土欲何之,翘首东云惹梦思。
所恨芳林寥落甚,春兰秋菊不同时。
三月
赠蓬子[450]
蓦地飞仙降碧空,云车双辆挈灵童。
可怜蓬子非天子,逃去逃来吸北风。[451]
三月三十一日
一·二八战后作[452]
战云暂敛残春在,重炮清歌两寂然。
我亦无诗送归棹,但从心底祝平安。
七月十一日
教授杂咏[453]
作法不自毙,悠然过四十。
何妨赌肥头,抵当辩证法。[454]
其二
可怜织女星,化为马郎妇。
乌鹊疑不来,迢迢牛奶路。[455]
其三
世界有文学,少女多丰臀。
鸡汤代猪肉,北新遂掩门。[456]
其四
名人选小说,入线云有限。
虽有望远镜,无奈近视眼。[457]
十二月
所闻[458]
华灯照宴敞豪门,娇女严装侍玉樽。
忽忆情亲焦土下,佯看罗袜掩啼痕。
十二月
无题二首[459]
故乡黯黯锁玄云,遥夜迢迢隔上春。[460]
岁暮何堪再惆怅,且持卮酒食河豚。
其二
皓齿吴娃唱柳枝,酒阑人静暮春时。[461]
无端旧梦驱残醉,独对灯阴忆子规。[462]
答客诮[463]
无情未必真豪杰,怜子如何不丈夫。
知否兴风狂啸者,回眸时看小於菟。[464]
十二月 |
PHP | UTF-8 | 855 | 2.890625 | 3 | [
"MIT-0",
"MIT"
] | permissive | <?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Metadata;
use PHPExiftool\Driver\TagInterface;
use PHPExiftool\Driver\Value\ValueInterface;
/**
* Metadata Object for mapping a Tag to a value
*
* @author Romain Neutron - imprec@gmail.com
* @license http://opensource.org/licenses/MIT MIT
*/
class Metadata
{
protected $tag;
protected $value;
public function __construct(TagInterface $tag, ValueInterface $value)
{
$this->tag = $tag;
$this->value = $value;
return $this;
}
public function getTag()
{
return $this->tag;
}
public function getValue()
{
return $this->value;
}
}
|
Java | UTF-8 | 2,509 | 2.828125 | 3 | [] | no_license | package org.kotemaru.android.filemanager.model;
import android.net.Uri;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public abstract class LinkedFolderNode extends BaseNode {
protected List<Node> mChildren = new ArrayList<Node>();
protected String mName;
public LinkedFolderNode(Node parent, String name) {
super(parent);
mName = name;
}
public void removeChild(Node node) {
Iterator<Node> ite = mChildren.iterator();
while (ite.hasNext()) {
Node child = ite.next();
if (child.getOrigin() == node.getOrigin()) ite.remove();
}
}
public boolean isLinkedChild(Node node) {
for (Node child : mChildren) {
if (child.eq(node)) return true;
}
return false;
}
@Override
public Node getOrCreateChild(CharSequence name) throws IOException {
for (Node child : mChildren) {
if (name.equals(child.getName())) return child;
}
throw new IOException("Cant create child.");
}
@Override
public List<Node> getChildren(boolean isShowNotReadable, boolean isFolderOnly) {
return mChildren;
}
@Override
public boolean eq(Node node) {
return this == node;
}
@Override
public boolean hasChildren() {
return true;
}
@Override
public Uri getUri() {
return null;
}
@Override
public String getAbsName() {
return mName;
}
@Override
public String getName() {
return mName;
}
@Override
public boolean isReadable() {
return true;
}
@Override
public boolean isWritable() {
return true;
}
@Override
public void rename(CharSequence newName) throws IOException {
mName = newName.toString();
}
@Override
public void delete() throws IOException {
try {
LinkedFolderNode parent = (LinkedFolderNode) getParent();
parent.removeChild(this);
} catch (ClassCastException e) {
throw new IOException(e);
}
}
@Override
public InputStream getInputStream() throws IOException {
throw new IOException("Cant open link folder");
}
@Override
public OutputStream getOutputStream() throws IOException {
throw new IOException("Cant open link folder");
}
}
|
PHP | UTF-8 | 952 | 3.015625 | 3 | [
"MIT"
] | permissive | <?php
namespace Hexarchium\CoreDomain\UseCase\CreateUseCase;
use Hexarchium\CoreDomain\Model\Domain\DomainId;
use Hexarchium\CoreDomain\Model\Domain\UseCase\UseCaseId;
class Command
{
/** @var UseCaseId */
private $useCaseId;
/** @var DomainId */
private $domainId;
/** @var string */
private $type;
/**
* Command constructor.
*
* @param UseCaseId $useCaseId
* @param DomainId $domainId
* @param string $type
*/
public function __construct(UseCaseId $useCaseId, DomainId $domainId, string $type)
{
$this->useCaseId = $useCaseId;
$this->domainId = $domainId;
$this->type = $type;
}
public function getDomainId(): DomainId
{
return $this->domainId;
}
public function getUseCaseId(): UseCaseId
{
return $this->useCaseId;
}
public function getUseCaseType(): string
{
return $this->type;
}
}
|
C# | UTF-8 | 981 | 3.53125 | 4 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCode.Solutions.Solutions.Easy.RemoveElement
{
/// <summary>
/// https://leetcode.com/problems/remove-element/
/// </summary>
public class RemoveElementSolution
{
public int RemoveElement(int[] nums, int val)
{
var replace = -1;
var replaceCount = 0;
for (var i = 0; i < nums.Length - replaceCount; i++)
{
if (val == nums[i])
{
nums[i] = replace;
replaceCount++;
for (var j = i; j < nums.Length - 1; j++)
{
nums[j] = nums[j + 1];
nums[j + 1] = replace;
}
i--;
}
}
return nums.Count(x => x != replace);
}
}
}
|
PHP | UTF-8 | 1,064 | 2.546875 | 3 | [] | no_license | <?php
namespace CsrDelft\repository\groepen\leden;
use CsrDelft\entity\groepen\AbstractGroep;
use CsrDelft\entity\groepen\Lichting;
use CsrDelft\entity\groepen\LichtingsLid;
use CsrDelft\repository\AbstractGroepLedenRepository;
use CsrDelft\repository\ProfielRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* @author G.J.W. Oolbekkink <g.j.w.oolbekkink@gmail.com>
* @since 06/05/2017
*/
class LichtingLedenRepository extends AbstractGroepLedenRepository {
public function __construct(ManagerRegistry $managerRegistry) {
parent::__construct($managerRegistry, LichtingsLid::class);
}
/**
* Create LichtingLid on the fly.
*
* @param Lichting $lichting
* @param string $uid
* @return LichtingsLid|false
*/
public function get(AbstractGroep $lichting, $uid) {
$profiel = ProfielRepository::get($uid);
if ($profiel AND $profiel->lidjaar === $lichting->lidjaar) {
$lid = $this->nieuw($lichting, $uid);
$lid->door_uid = null;
$lid->door_profiel = null;
$lid->lid_sinds = $profiel->lidjaar . '-09-01 00:00:00';
return $lid;
}
return false;
}
}
|
Java | UTF-8 | 209 | 2.015625 | 2 | [] | no_license | package docxToPdf;
public class DocxToPdfApplication {
public static void main(String[] args) {
}
public void converter(String origem, String destino) {
DocToPDF.ConvertToPDF(origem, destino);
}
}
|
Python | UTF-8 | 5,424 | 2.703125 | 3 | [] | no_license | class LFM_topN:
def __init__(self,classcount=10,itercount=30,alpha=0.01,lamda=0.03,ratio=1):
self.classcount = classcount
self.itercount = itercount
self.alpha = alpha
self.lamda = lamda
self.ratio = ratio
def getUserNegativeItem(self,userId,positiveItemList):
ret = dict()
for i in positiveItemList['User_list'][userId]:
ret[i] = 1
n = 0
for i in range(0, len(positiveItemList['User_list'][userId]) * 10):
item = self.items_pool[np.random.randint(0, len(self.items_pool) - 1)]
if item in ret:
continue
ret[item] = 0
n += 1
if n > self.ratio*len(positiveItemList['User_list'][userId]):
break
negativeItemList = []
for i in ret:
if ret[i] == 0:
negativeItemList.append(i)
return negativeItemList
def get_user_item(self,data):
item_based = data.pivot_table(index=self.movie_feature, columns=self.user_feature, values=self.rating_feature)
positiveItemList = pd.DataFrame(index=item_based.columns,columns=['User_list'])
for i in item_based.columns:
positiveItemList['User_list'][i] = item_based[i].dropna().index.values
positiveItemList = positiveItemList.to_dict()
user_item = {}
for user_Id in item_based.columns.values:
negativeItemList = self.getUserNegativeItem(user_Id, positiveItemList)
user_item[user_Id] = [positiveItemList['User_list'][user_Id],negativeItemList]
return user_item
def initPara(self,data,userId,itemId):
self.p = np.random.rand(len(userId), self.classcount)/np.sqrt(self.classcount)
self.q = np.random.rand(len(itemId), self.classcount)/np.sqrt(self.classcount)
self.user_list = {}
self.movie_list = {}
j = 0
for i in userId:
self.user_list[i] = j
j+=1
j = 0
# print(176 in itemId)
for i in itemId:
self.movie_list[i] = j
j+=1
def lfmPredict(self,user,movie):
p_q = np.dot(self.p[self.user_list[user]],self.q[self.movie_list[movie]])
predict = self.sigmoid(p_q)
return predict
def sigmoid(self,x):
return 1.0/(1+np.exp(-x))
def fit(self,data,feature_name):
self.user_feature = feature_name[0]
self.movie_feature = feature_name[1]
self.rating_feature = feature_name[2]
movie_list = list(set(data[self.movie_feature].values))
user_list = list(set(data[self.user_feature].values))
self.initPara(data,user_list,movie_list)
self.items_pool = list(data.movieId.values)
self.user_item = self.get_user_item(data)
for step in range(self.itercount):
print(step)
for user in self.user_item:
for movie in self.user_item[user][0]:
eui = 1 - self.lfmPredict(user,movie)
du = self.alpha * (eui * self.q[self.movie_list[movie]] - self.lamda * self.p[self.user_list[user]])
di = self.alpha * (eui * self.p[self.user_list[user]] - self.lamda * self.q[self.movie_list[movie]])
self.p[self.user_list[user]] += du
self.q[self.movie_list[movie]] += di
for movie in self.user_item[user][1]:
eui = 0 - self.lfmPredict(user,movie)
du = self.alpha * (eui * self.q[self.movie_list[movie]] - self.lamda * self.p[self.user_list[user]])
di = self.alpha * (eui * self.p[self.user_list[user]] - self.lamda * self.q[self.movie_list[movie]])
self.p[self.user_list[user]] += du
self.q[self.movie_list[movie]] += di
self.alpha *= 0.9
def recommend(self,userID,TopN=10):
predict_movie = {}
for movie in self.movie_list:
predict_movie[movie] = self.lfmPredict(userID,movie)
sort_predict_movie = sorted(predict_movie.items(), key = lambda item:item[1],reverse=True)[:150]
predict_list = []
for index in sort_predict_movie:
if index[0] not in self.user_item[userID][0]:
predict_list.append(index[0])
if len(predict_list) == TopN:
break
return predict_list
def calculate_Fscore(self,test_data,topN):
self.precision = []
self.recall = []
self.Fscore = []
test_data = test_data[['userId','movieId']]
for user in set(test_data.userId):
if user not in self.user_item:
continue
top_N = self.recommend(user,topN)
test_set = test_data.loc[test_data['userId']==user,'movieId'].values
if len(test_set)==0:
continue
inter = len(np.intersect1d(top_N,test_set))
precision = inter/topN
#recall = inter/len(test_set)
#fscore = (1+0.25)*(precision*recall)/(0.25*precision+recall)
self.precision.append(precision)
#self.recall.append(recall)
# self.Fscore.append(fscore)
|
Ruby | UTF-8 | 256 | 2.75 | 3 | [] | no_license | class CraneMover9001
def apply(state, move_values)
qty, src, dest = move_values
crate = state[src].pop(qty)
# pp "DEBUG: crate #{crate}, state[#{src}]: #{state[src]}"
state[dest] << crate
state[dest].flatten!
state
end
end |
Java | UTF-8 | 8,472 | 2.375 | 2 | [] | no_license | package com.aneedo.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class StopwordRecognizer {
private static final String DEFAULT_STOP_WORDS = "a,a's,able,about,above,according,accordingly,across,actually,after,"
+ "afterwards,again,against,ain't,all,allow,allows,almost,alone,along,already,also,"
+ "although,always,am,among,amongst,an,and,another,any,anybody,anyhow,anyone,anything,include,including,"
+ "anyway,anyways,anywhere,apart,appear,appreciate,appropriate,are,aren't,around,as,aside,ask,"
+ "asking,associated,at,available,away,awfully,b,be,became,because,become,becomes,becoming,been,"
+ "before,beforehand,behind,being,believe,below,beside,besides,best,better,between,beyond,both,brief,"
+ "but,by,c,c'mon,c's,came,can,can't,cannot,cant,cause,causes,certain,certainly,changes,clearly,co,"
+ "com,come,comes,concerning,consequently,consider,considering,contain,containing,contains,"
+ "corresponding,could,couldn't,course,currently,d,definitely,described,despite,did,didn't,different,"
+ "do,does,doesn't,doing,don't,done,down,downwards,during,e,each,edu,eg,eight,either,else,elsewhere,"
+ "enough,entirely,especially,et,etc,even,ever,every,everybody,everyone,everything,everywhere,ex,"
+ "exactly,example,except,f,far,few,fifth,first,five,followed,following,follows,for,former,formerly,"
+ "forth,four,from,further,furthermore,g,get,gets,getting,given,gives,go,goes,going,gone,got,gotten,"
+ "greetings,h,had,hadn't,happens,hardly,has,hasn't,have,haven't,having,he,he's,hello,hence,"
+ "her,here,here's,hereafter,hereby,herein,hereupon,hers,herself,hi,him,himself,his,hither,"
+ "hopefully,how,howbeit,however,i,i'd,i'll,i'm,i've,ie,if,ignored,immediate,in,inasmuch,inc,"
+ "indeed,indicate,indicated,indicates,inner,insofar,instead,into,inward,is,isn't,it,it'd,it'll,"
+ "it's,its,itself,j,just,k,keep,keeps,kept,know,knows,known,l,last,lately,later,latter,latterly,least,less,"
+ "lest,let,let's,like,liked,likely,little,look,looking,looks,ltd,m,mainly,many,may,maybe,me,mean,meanwhile,"
+ "merely,might,more,moreover,mostly,much,must,most,my,myself,n,name,namely,nd,near,nearly,necessary,need,needs,"
+ "neither,never,nevertheless,new,next,nine,no,nobody,non,none,noone,nor,normally,not,nothing,novel,now,nowhere,o,"
+ "obviously,of,off,often,oh,ok,okay,old,on,once,one,ones,only,onto,or,other,others,otherwise,ought,our,ours,ourselves,"
+ "out,outside,over,overall,own,p,particular,particularly,per,perhaps,placed,please,plus,possible,presumably,probably,"
+ "provides,q,que,quite,qv,r,rather,rd,re,really,reasonably,regarding,regardless,regards,relatively,respectively,right,s,"
+ "said,same,saw,say,saying,says,second,secondly,see,seeing,seem,seemed,seeming,seems,seen,self,selves,sensible,sent,"
+ "serious,seriously,seven,several,shall,she,should,shouldn't,since,six,so,some,somebody,somehow,someone,something,sometime,"
+ "sometimes,somewhat,somewhere,soon,sorry,specified,specify,specifying,still,sub,such,sup,sure,t,t's,take,taken,tell,"
+ "tends,th,than,thank,thanks,thanx,that,that's,thats,the,their,theirs,them,themselves,then,thence,there,there's,thereafter,"
+ "thereby,therefore,therein,theres,thereupon,these,they,they'd,they'll,they're,they've,think,third,this,thorough,"
+ "thoroughly,those,though,three,through,throughout,thru,thus,to,together,too,took,toward,towards,tried,tries,truly,"
+ "try,trying,twice,two,u,un,under,unfortunately,unless,unlikely,until,unto,up,upon,us,use,used,useful,uses,using,"
+ "usually,uucp,v,value,various,very,via,viz,vs,w,want,wants,was,wasn't,way,we,we'd,we'll,we're,we've,welcome,well,"
+ "went,were,weren't,what,what's,whatever,when,whence,whenever,where,where's,whereafter,whereas,whereby,wherein,"
+ "whereupon,wherever,whether,which,while,whither,who,who's,whoever,whole,whom,whose,why,will,willing,wish,"
+ "with,within,without,won't,wonder,would,would,wouldn't,x,y,yes,yet,you,you'd,you'll,you're,you've,your,"
+ "yours,yourself,yourselves,z,zero,a,about,above,across,after,again,against,all,almost,alone,along,already,"
+ "also,although,always,among,an,and,another,any,anybody,anyone,anything,anywhere,are,area,areas,around,as,"
+ "ask,asked,asking,asks,at,away,b,back,backed,backing,backs,be,became,because,become,becomes,been,before,"
+ "began,behind,being,beings,best,better,between,both,but,by,c,came,can,cannot,case,cases,certain,certainly,"
+ "clear,clearly,come,could,d,did,differ,different,differently,do,does,done,down,down,downed,downing,downs,during,"
+ "e,each,early,either,end,ended,ending,ends,enough,even,evenly,ever,every,everybody,everyone,everything,"
+ "everywhere,f,face,faces,fact,facts,far,felt,few,find,finds,first,for,four,from,full,fully,further,furthered,"
+ "furthering,furthers,g,gave,general,generally,get,gets,give,given,gives,go,going,got,greater,"
+ "greatest,grouped,grouping,groups,h,had,has,have,having,he,her,here,herself,higher,"
+ "highest,him,himself,his,how,however,i,if,in,interest,interested,interests,"
+ "into,is,it,its,itself,j,just,k,keep,keeps,kind,knew,know,known,knows,largely,last,later,"
+ "latest,least,less,let,lets,like,likely,longer,longest,m,made,make,making,man,many,may,me,"
+ "men,might,more,most,mostly,mr,mrs,much,must,my,myself,n,necessary,need,needed,"
+ "needing,needs,never,new,new,newer,newest,next,no,nobody,non,noone,not,nothing,now,nowhere,number,"
+ "numbers,o,of,off,often,old,older,oldest,on,once,one,only,open,opened,opening,opens,or,order,ordered,"
+ "ordering,orders,other,others,our,out,over,p,part,parted,parting,parts,per,perhaps,place,places,point,"
+ "pointed,pointing,points,possible,present,presented,presenting,presents,problem,problems,put,puts,q,"
+ "quite,r,rather,really,right,right,room,rooms,s,said,same,saw,say,says,second,seconds,see,seem,seemed,"
+ "seeming,seems,sees,several,shall,she,should,show,showed,showing,shows,side,sides,since,smaller,"
+ "smallest,so,some,somebody,someone,something,somewhere,state,states,still,still,such,sure,t,take,taken,"
+ "than,that,the,their,them,then,there,therefore,these,they,thing,things,think,thinks,this,those,though,"
+ "thought,thoughts,three,through,thus,to,today,together,too,took,toward,turn,turned,turning,turns,two,u,"
+ "under,until,up,upon,us,use,used,uses,v,very,w,want,wanted,wanting,wants,was,way,ways,we,well,wells,went,"
+ "were,what,when,where,whether,which,while,who,whole,whose,why,will,with,within,without,work,worked,"
+ "works,would,x,y,year,years,yet,you,younger,youngest,your,yours,z,"
+ "a,about,add,ago,after,all,also,an,and,another,any,are,as,at,be,"
+ "because,been,before,being,between,both,but,by,came,can,come,"
+ "could,did,do,does,due,each,else,end,far,few,for,from,get,got,had,"
+ "has,have,he,her,here,him,himself,his,how,if,in,into,is,it,its,"
+ "just,let,lie,like,low,make,many,me,might,more,much,must,"
+ "my,never,no,nor,not,now,of,off,old,on,only,or,other,our,out,over,"
+ "per,pre,put,re,said,same,see,she,should,since,so,some,still,such,"
+ "take,than,that,the,their,them,then,there,these,they,this,those,"
+ "through,to,too,under,up,use,very,via,want,was,way,we,well,were,"
+ "what,when,where,which,while,who,will,with,would,yes,yet,you,your,based,base,widely";
private Set<String> stopwords = new HashSet<String>();
private static final StopwordRecognizer stopWordRecog = new StopwordRecognizer();
private StopwordRecognizer() {
init();
}
public static StopwordRecognizer getInstance() {
return stopWordRecog;
}
public void init() {
if (stopwords.size() == 0) {
String[] stopwordArray = DEFAULT_STOP_WORDS.split(",");
stopwords.addAll(Arrays.asList(stopwordArray));
}
}
public List<String> removeStopWords(List<String> tokens) {
List<String> recognizedTokens = new ArrayList<String>();
for (String token : tokens) {
if (!stopwords.contains(token.toLowerCase())) {
//System.out.print(token +" ");
recognizedTokens.add(token);
}
}
//System.out.println("After removing stop words ....");
return recognizedTokens;
}
public boolean isStopWordForType(String word) {
if("a".equals(word) ||"".equals(word.trim())) {
return false;
}
return isStopWord(word);
}
public boolean isStopWord(String word) {
return stopwords.contains(word);
}
}
|
Java | UTF-8 | 231 | 1.664063 | 2 | [] | no_license | package fi.bizhop.kiekkohamsteri.dto.v2.in;
import lombok.Builder;
import lombok.Value;
import lombok.extern.jackson.Jacksonized;
@Value
@Builder
@Jacksonized
public class PlasticCreateDto {
Long manufacturerId;
String name;
}
|
JavaScript | UTF-8 | 1,369 | 2.84375 | 3 | [] | no_license | 'use strict';
class MongoModel {
constructor(schema) {
this.schema = schema;
}
get(id) {
console.log('Using mongo GET')
return this.schema.find().then(result => {
let data = { rows: result, rowCount: result.length };
return new Promise(resolve => resolve([data]));
});
}
post(body) {
console.log('Using mongo POST');
let {title, author, isbn, image_url, description} = body;
let record = { title, author, isbn, image_url, description};
let newBook = new this.schema(record);
return newBook.save().then(book => {
let data = { rows: [book], rowCount: [book].length };
return new Promise(resolve => resolve(data));
});
}
put(body, id) {
console.log('Using mongo PUT');
let { title, author, isbn, image_url, description, bookshelf_id } = body;
return this.schema
.findByIdAndUpdate(id, { title, author, isbn, image_url, description, bookshelf_id })
.then(book => {
let data = { rows: [book], rowCount: [book].length };
return new Promise(resolve => resolve(data));
});
}
delete(id) {
console.log('Using mongo DELETE');
return this.schema.findByIdAndDelete(id).then(book => {
let data = { rows: [book], rowCount: [book].length };
return new Promise(resolve => resolve(data));
});
}
}
module.exports = MongoModel;
|
JavaScript | UTF-8 | 640 | 3.25 | 3 | [] | no_license | const fetch = require('node-fetch');
async function sunsetTime(date) {
const resp = await fetch(`http://api.sunrise-sunset.org/json?lat=32.095&lng=34.847&formatted=0&date=${date}`)
const result = await resp.json();
return new Date(result.results.sunset);
}
async function *getSunsets() {
for (let day = 1; day <= 31; day++) {
yield await sunsetTime('2017-03-' + day);
}
}
async function main() {
console.log('Hello Dev.IL 😊 !\n\n');
for await (let sunset of getSunsets()) {
console.log('Sunset time for', sunset.toDateString(),
'is at', sunset.toTimeString());
}
}
main();
|
Java | UTF-8 | 295 | 2.078125 | 2 | [] | no_license | package com.cmstop.jstt.event;
public class PayResultEvent {
private int resultCode;
public PayResultEvent(int code){
this.resultCode = code;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
}
|
Python | UTF-8 | 514 | 3.609375 | 4 | [] | no_license | #!/usr/bin/python3
# Bullet point adder
# Adds markdown bullet points to start of each line of text in clipboard
import pyperclip
text = pyperclip.paste()
# Separate lines and add stars
lines = text.split('\n')
for i in range(len(lines)):
# loop through all indexes in the 'lines' list
lines[i] = '* ' + lines[i] # add star to each string in list
# Join lines back together into one string
text = '\n'.join(lines)
pyperclip.copy(text)
print('Bullet points have been added to the lines in your clipboard')
|
Java | UTF-8 | 9,840 | 1.835938 | 2 | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"Python-2.0",
"BSD-2-Clause"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.accumulo.columns;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.hive.accumulo.AccumuloHiveConstants;
import org.apache.hadoop.hive.accumulo.serde.TooManyAccumuloColumnsException;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
import org.junit.Assert;
import org.junit.Test;
import com.google.common.base.Joiner;
/**
*
*/
public class TestColumnMapper {
@Test
public void testNormalMapping() throws TooManyAccumuloColumnsException {
List<String> rawMappings = Arrays.asList(AccumuloHiveConstants.ROWID, "cf:cq", "cf:_",
"cf:qual");
List<String> columnNames = Arrays.asList("row", "col1", "col2", "col3");
List<TypeInfo> columnTypes = Arrays.<TypeInfo> asList(TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo);
ColumnMapper mapper = new ColumnMapper(
Joiner.on(AccumuloHiveConstants.COMMA).join(rawMappings), ColumnEncoding.STRING.getName(),
columnNames, columnTypes);
List<ColumnMapping> mappings = mapper.getColumnMappings();
Assert.assertEquals(rawMappings.size(), mappings.size());
Assert.assertEquals(mappings.size(), mapper.size());
// Compare the Mapper get at offset method to the list of mappings
Iterator<String> rawIter = rawMappings.iterator();
Iterator<ColumnMapping> iter = mappings.iterator();
for (int i = 0; i < mappings.size() && iter.hasNext(); i++) {
String rawMapping = rawIter.next();
ColumnMapping mapping = iter.next();
ColumnMapping mappingByOffset = mapper.get(i);
Assert.assertEquals(mapping, mappingByOffset);
// Ensure that we get the right concrete ColumnMapping
if (AccumuloHiveConstants.ROWID.equals(rawMapping)) {
Assert.assertEquals(HiveAccumuloRowIdColumnMapping.class, mapping.getClass());
} else {
Assert.assertEquals(HiveAccumuloColumnMapping.class, mapping.getClass());
}
}
Assert.assertEquals(0, mapper.getRowIdOffset());
Assert.assertTrue(mapper.hasRowIdMapping());
}
@Test(expected = IllegalArgumentException.class)
public void testMultipleRowIDsFails() throws TooManyAccumuloColumnsException {
new ColumnMapper(AccumuloHiveConstants.ROWID + AccumuloHiveConstants.COMMA
+ AccumuloHiveConstants.ROWID, null, Arrays.asList("row", "row2"),
Arrays.<TypeInfo> asList(TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo));
}
@Test
public void testGetMappingFromHiveColumn() throws TooManyAccumuloColumnsException {
List<String> hiveColumns = Arrays.asList("rowid", "col1", "col2", "col3");
List<TypeInfo> columnTypes = Arrays.<TypeInfo> asList(TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo);
List<String> rawMappings = Arrays.asList(AccumuloHiveConstants.ROWID, "cf:cq", "cf:_",
"cf:qual");
ColumnMapper mapper = new ColumnMapper(
Joiner.on(AccumuloHiveConstants.COMMA).join(rawMappings), null, hiveColumns, columnTypes);
for (int i = 0; i < hiveColumns.size(); i++) {
String hiveColumn = hiveColumns.get(i), accumuloMapping = rawMappings.get(i);
ColumnMapping mapping = mapper.getColumnMappingForHiveColumn(hiveColumns, hiveColumn);
Assert.assertEquals(accumuloMapping, mapping.getMappingSpec());
}
}
@Test
public void testGetTypesString() throws TooManyAccumuloColumnsException {
List<String> hiveColumns = Arrays.asList("rowid", "col1", "col2", "col3");
List<String> rawMappings = Arrays.asList(AccumuloHiveConstants.ROWID, "cf:cq", "cf:_",
"cf:qual");
List<TypeInfo> columnTypes = Arrays.<TypeInfo> asList(TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo);
ColumnMapper mapper = new ColumnMapper(
Joiner.on(AccumuloHiveConstants.COMMA).join(rawMappings), null, hiveColumns, columnTypes);
String typeString = mapper.getTypesString();
String[] types = StringUtils.split(typeString, AccumuloHiveConstants.COLON);
Assert.assertEquals(rawMappings.size(), types.length);
for (String type : types) {
Assert.assertEquals(serdeConstants.STRING_TYPE_NAME, type);
}
}
@Test
public void testDefaultBinary() throws TooManyAccumuloColumnsException {
List<String> hiveColumns = Arrays.asList("rowid", "col1", "col2", "col3", "col4");
List<String> rawMappings = Arrays.asList(AccumuloHiveConstants.ROWID, "cf:cq", "cf:_#s",
"cf:qual#s", "cf:qual2");
List<TypeInfo> columnTypes = Arrays.<TypeInfo> asList(TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo);
ColumnMapper mapper = new ColumnMapper(
Joiner.on(AccumuloHiveConstants.COMMA).join(rawMappings), ColumnEncoding.BINARY.getName(),
hiveColumns, columnTypes);
List<ColumnMapping> mappings = mapper.getColumnMappings();
Assert.assertEquals(5, mappings.size());
Assert.assertEquals(ColumnEncoding.BINARY, mappings.get(0).getEncoding());
Assert.assertEquals(columnTypes.get(0).toString(), mappings.get(0).getColumnType());
Assert.assertEquals(ColumnEncoding.BINARY, mappings.get(1).getEncoding());
Assert.assertEquals(columnTypes.get(1).toString(), mappings.get(1).getColumnType());
Assert.assertEquals(ColumnEncoding.STRING, mappings.get(2).getEncoding());
Assert.assertEquals(columnTypes.get(2).toString(), mappings.get(2).getColumnType());
Assert.assertEquals(ColumnEncoding.STRING, mappings.get(3).getEncoding());
Assert.assertEquals(columnTypes.get(3).toString(), mappings.get(3).getColumnType());
Assert.assertEquals(ColumnEncoding.BINARY, mappings.get(4).getEncoding());
Assert.assertEquals(columnTypes.get(4).toString(), mappings.get(4).getColumnType());
}
@Test
public void testMap() throws TooManyAccumuloColumnsException {
List<String> hiveColumns = Arrays.asList("rowid", "col1", "col2", "col3");
List<TypeInfo> columnTypes = Arrays.<TypeInfo> asList(TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.getMapTypeInfo(TypeInfoFactory.stringTypeInfo,
TypeInfoFactory.stringTypeInfo), TypeInfoFactory.getMapTypeInfo(
TypeInfoFactory.stringTypeInfo, TypeInfoFactory.stringTypeInfo),
TypeInfoFactory.stringTypeInfo);
List<String> rawMappings = Arrays.asList(AccumuloHiveConstants.ROWID, "cf1:*", "cf2:2*",
"cq3:bar\\*");
ColumnMapper mapper = new ColumnMapper(
Joiner.on(AccumuloHiveConstants.COMMA).join(rawMappings), ColumnEncoding.BINARY.getName(),
hiveColumns, columnTypes);
List<ColumnMapping> mappings = mapper.getColumnMappings();
Assert.assertEquals(4, mappings.size());
Assert.assertEquals(HiveAccumuloRowIdColumnMapping.class, mappings.get(0).getClass());
Assert.assertEquals(HiveAccumuloMapColumnMapping.class, mappings.get(1).getClass());
Assert.assertEquals(HiveAccumuloMapColumnMapping.class, mappings.get(2).getClass());
Assert.assertEquals(HiveAccumuloColumnMapping.class, mappings.get(3).getClass());
HiveAccumuloRowIdColumnMapping row = (HiveAccumuloRowIdColumnMapping) mappings.get(0);
Assert.assertEquals(ColumnEncoding.BINARY, row.getEncoding());
Assert.assertEquals(hiveColumns.get(0), row.getColumnName());
Assert.assertEquals(columnTypes.get(0).toString(), row.getColumnType());
HiveAccumuloMapColumnMapping map = (HiveAccumuloMapColumnMapping) mappings.get(1);
Assert.assertEquals("cf1", map.getColumnFamily());
Assert.assertEquals("", map.getColumnQualifierPrefix());
Assert.assertEquals(ColumnEncoding.BINARY, map.getEncoding());
Assert.assertEquals(hiveColumns.get(1), map.getColumnName());
Assert.assertEquals(columnTypes.get(1).toString(), map.getColumnType());
map = (HiveAccumuloMapColumnMapping) mappings.get(2);
Assert.assertEquals("cf2", map.getColumnFamily());
Assert.assertEquals("2", map.getColumnQualifierPrefix());
Assert.assertEquals(ColumnEncoding.BINARY, map.getEncoding());
Assert.assertEquals(hiveColumns.get(2), map.getColumnName());
Assert.assertEquals(columnTypes.get(2).toString(), map.getColumnType());
HiveAccumuloColumnMapping column = (HiveAccumuloColumnMapping) mappings.get(3);
Assert.assertEquals("cq3", column.getColumnFamily());
Assert.assertEquals("bar*", column.getColumnQualifier());
Assert.assertEquals(ColumnEncoding.BINARY, column.getEncoding());
Assert.assertEquals(hiveColumns.get(3), column.getColumnName());
Assert.assertEquals(columnTypes.get(3).toString(), column.getColumnType());
}
}
|
Python | UTF-8 | 1,613 | 4.0625 | 4 | [] | no_license | """Min Groups Module"""
def min_groups(points, max_segment_length):
"""Minimum Groups
Divides a set of points of segments of MaxSegmentLength
returns the count of minimum groups
Uses Greedy Approach
"""
group_count = 0 # the count of groups
segments = [] # The map of segments
cur_segment = False # The starting value of cur_segment
for point in points:
# Check if the point 'p' belong to the current segment
if not cur_segment or point > cur_segment:
# 'p' doesn't belong to current segment
# Create a new segment with 'p' in it
cur_segment = point + max_segment_length
segments.append([point])
group_count += 1
else:
# 'p' belongs to current segment
# Add p to the current segment
segments[group_count - 1].append(point)
return {
"segments" : segments,
"group_count" : group_count
}
def test():
"""Test function """
test_points = [
[0.5, 0.6, 0.7, 1, 1.2, 2, 2.8, 3.4, 5, 6, 6.9],
[0.5],
[]
]
max_segment_length = 1
print_sep()
groups = min_groups(test_points[0], max_segment_length)
print(groups)
print_sep()
groups = min_groups(test_points[1], max_segment_length)
print(groups)
print_sep()
groups = min_groups(test_points[2], max_segment_length)
print(groups)
print_sep()
def print_sep():
"""Print Seperator"""
print("")
if __name__ == "__main__":
test()
|
Java | UTF-8 | 7,722 | 1.859375 | 2 | [] | no_license | /**
* Project Name:iotgp-common-db
* File Name:CdSoftWareInfoDaoImpl.java
* Package Name:cn.inovance.iotgp.common.domain
* Date:2014-7-22下午4:24:02
* Copyright (c) 2014, Shenzhen Inovance technology Co., Ltd All Rights Reserved.
*
*/
package cn.inovance.iotgp.common.dao.impl;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.hibernate.Query;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import cn.inovance.iotgp.common.dao.BaseDao;
import cn.inovance.iotgp.common.dao.CdSoftWareInfoDao;
import cn.inovance.iotgp.common.dao.SoftWareInfoDao;
import cn.inovance.iotgp.common.dao.SoftWareUpdateJobDetailsDao;
import cn.inovance.iotgp.common.domain.CdSoftwareInfo;
import cn.inovance.iotgp.common.domain.SoftwareInfo;
import cn.inovance.iotgp.common.domain.SoftwareUpdateDetails;
import cn.inovance.iotgp.common.filter.HqlFilter;
import cn.inovance.iotgp.common.status.StatusEnum;
/**
* ClassName:CdSoftWareInfoDaoImpl <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON. <br/>
* Date: 2014-7-22 下午4:24:02 <br/>
* @author w1898
* @version
* @since JDK 1.7
* @see
*/
@Repository
public class CdSoftWareInfoDaoImpl extends BaseDaoImpl<CdSoftwareInfo> implements CdSoftWareInfoDao {
@Autowired
private SoftWareInfoDao softWareInfoDao;
@Autowired
private SoftWareUpdateJobDetailsDao softwareUpdateDetailsDao;
@Override
public List<CdSoftwareInfo> findBySql(CdSoftwareInfo data,int rows, int page,String sort,String order) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT tmcsi.* ,tmsud.version new_version FROM t_mms_cd_software_info tmcsi ");
sql.append("left join t_mms_software_update_details tmsud ");
sql.append("on tmsud.soft_name=tmcsi.name and tmsud.update_result='"+ StatusEnum.SOFTWARE_UPDATE_DETAILS_NOT_UPDATE.value+ "' ") ;
if(StringUtils.isNotBlank(data.getCdRegCode())){
sql.append("and tmsud.cd_reg_code='"+ data.getCdRegCode()+ "' ") ;
}
//sql.append("left join t_mms_software_info tmsi on tmsi.name=tmcsi.name ") ;
sql.append("where 1=1 ");
//sql.append("and tmsi.soft_type='"+ StatusEnum.SOFTWARE_UPDATE_JOB_TYPE_CD.value +"' ");
if(StringUtils.isNotBlank(data.getCdRegCode())){
sql.append("and tmcsi.cd_reg_code='" + data.getCdRegCode() + "' ");
}
sql.append("order by tmcsi.update_time desc ");
if(rows > 0 && page > 0 ){
sql.append("limit " + (page - 1) * rows + "," + rows);
}
List<Map> list = findBySql(sql.toString());
StringBuilder jobSql=new StringBuilder(200);
StringBuilder softInfoSql=new StringBuilder(200);
jobSql.append("select i.create_time as createTime from t_mms_software_info i where 1=1 "
+ " and i.name=:name and i.version=:version ");
softInfoSql.append("select d.update_time as updateTime from t_mms_software_update_details d where 1=1 "
+ " and d.cd_reg_code=:cdRegCode and d.soft_name=:name and d.version=:version ");
Map<String, Type> jobResultValueTypeMap=new HashMap<String, Type>();
Map<String, Type> softResultValueTypeMap=new HashMap<String, Type>();
softResultValueTypeMap.put("updateTime", StandardBasicTypes.TIMESTAMP);
jobResultValueTypeMap.put("createTime", StandardBasicTypes.TIMESTAMP);
Map<String, Object> jobParams=new HashMap<String,Object>();
Map<String, Object> softInfoParams=new HashMap<String,Object>();
List<CdSoftwareInfo> tdsoftwares = new ArrayList<CdSoftwareInfo>(0);
//SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for(Map map:list){
CdSoftwareInfo obj = new CdSoftwareInfo();
if(map.get("id")!= null ){
obj.setId(map.get("id").toString());
}
if(map.get("cd_reg_code")!= null ){
obj.setCdRegCode(map.get("cd_reg_code").toString());
softInfoParams.put("cdRegCode", map.get("cd_reg_code").toString());
}
if(map.get("name")!= null ){
obj.setName(map.get("name").toString());
jobParams.put("name", map.get("name").toString());
softInfoParams.put("name", map.get("name").toString());
}
if(map.get("version")!= null ){
obj.setVersion(map.get("version").toString());
jobParams.put("version", map.get("version").toString());
softInfoParams.put("version", map.get("version").toString());
}
try {
if(map.get("create_time")!= null ){
//obj.setCreateTime(sdf.parse(map.get("create_time").toString()));
obj.setCreateTime(DateUtils.parseDate(map.get("create_time").toString(), "yyyy-MM-dd HH:mm:ss.S"));
}
if(map.get("update_time")!= null ){
//obj.setUpdateTime(sdf.parse(map.get("update_time").toString()));
obj.setUpdateTime(DateUtils.parseDate(map.get("update_time").toString(), "yyyy-MM-dd HH:mm:ss.S"));
}
} catch (ParseException e) {
e.printStackTrace();
}
if(map.get("new_version")!= null ){
obj.setNewVersion(map.get("new_version").toString());
}
List<SoftwareInfo> jobList=softWareInfoDao.findObjListBySql(jobSql.toString(),jobParams , jobResultValueTypeMap , SoftwareInfo.class);
List<SoftwareUpdateDetails> softList=softwareUpdateDetailsDao.findObjListBySql(softInfoSql.toString(), softInfoParams,softResultValueTypeMap,SoftwareUpdateDetails.class);
if (softList!=null && softList.size()>0) {
obj.setSoftUpdateDate(softList.get(0).getUpdateTime());
}
if (jobList!=null && jobList.size()>0) {
obj.setJobCreatDate(jobList.get(0).getCreateTime());
}
tdsoftwares.add(obj);
}
return tdsoftwares;
}
@Override
public long countfindBySql(CdSoftwareInfo data) {
StringBuilder sql = new StringBuilder();
sql.append("SELECT count(*) rows FROM t_mms_cd_software_info tmcsi ");
sql.append("left join t_mms_software_update_details tmsud ");
sql.append("on tmsud.soft_name=tmcsi.name and tmsud.update_result='"+ StatusEnum.SOFTWARE_UPDATE_DETAILS_NOT_UPDATE.value+ "' ") ;
if(StringUtils.isNotBlank(data.getCdRegCode())){
sql.append("and tmsud.cd_reg_code='"+ data.getCdRegCode()+ "' ") ;
}
//sql.append("left join t_mms_software_info tmsi on tmsi.name=tmcsi.name ") ;
sql.append("where 1=1 ");
// sql.append("and tmsi.soft_type='"+ StatusEnum.SOFTWARE_UPDATE_JOB_TYPE_CD.value +"' ");
if(data != null && StringUtils.isNotBlank(data.getCdRegCode())){
sql.append("and tmcsi.cd_reg_code='" + data.getCdRegCode() + "' ");
}
BigInteger size = countBySql(sql.toString());
return size.longValue();
}
@Override
public List<CdSoftwareInfo> queryCdsByCdRegCodeAndSoft(CdSoftwareInfo data) {
String hql = "select distinct cd " +
"from CdSoftwareInfo cd"+
" where cd.cdRegCode in ("+data.getCdRegCode() +") and cd.name = '"+ data.getName() + "' and cd.version = '" + data.getVersion() + "'";
List<CdSoftwareInfo> list =find(hql);
return list;
}
@Override
public List<CdSoftwareInfo> queryCdsByCdRegCodeAndSoftName(CdSoftwareInfo data) {
String hql = "select distinct cd " +
"from CdSoftwareInfo cd"+
" where cd.cdRegCode in ("+data.getCdRegCode() +") and cd.name = '"+ data.getName() + "'";
List<CdSoftwareInfo> list =find(hql);
return list;
}
@Override
public List<CdSoftwareInfo> queryListByCdRegCode(CdSoftwareInfo data) {
HqlFilter hqlFilter = new HqlFilter();
hqlFilter.addFilter("QUERY_t#cdRegCode_S_EQ", data.getCdRegCode());
return findByFilter(hqlFilter);
}
}
|
C | GB18030 | 825 | 3.640625 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int MissingNumber(int nums[], int sz) //ⷨ1֮ͼȥһĺͣӶ1-nǾn
{
int i = 0;
int j = 0;
int sum1 = 0;
int sum2 = 0;
int newlen = sz + 1;
for (i = 0; i < newlen; i++)
{
sum1 = sum1 + i; //0nĺ
}
for (j = 0; j < sz; j++)
{
sum2 = sum2 + nums[j]; //ĺ
}
return sum1 - sum2;
}
int MissingNumber(int nums[], int sz) //ⷨ2Ӷn+n+1=2n+1ôӶȾn
{
int x = 0;
int newlen = sz + 1;
int i = 0;
for (i = 0; i < newlen; i++)
{
x = x^i;
}
for (i = 0; i < sz; i++)
{
x = x^nums[i];
}
return x;
}
int main()
{
int nums[] = {0,1, 2, 3, 4, 6, 7 };
int sz = sizeof(nums) / sizeof(nums[0]);
int digit = MissingNumber(nums, sz);
printf("%d\n", digit);
} |
Java | UTF-8 | 4,773 | 2.65625 | 3 | [] | no_license | package com.greenlabs.crudsample.dao.impl;
import com.greenlabs.crudsample.DbConnection;
import com.greenlabs.crudsample.dao.MahasiswaDao;
import com.greenlabs.crudsample.entity.Mahasiswa;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kristiawan on 10/7/17.
*/
public class MahasiswaDaoImpl implements MahasiswaDao {
@Override
public Mahasiswa Save(Mahasiswa entity) {
String sql = "INSERT INTO mahasiswa VALUES(?, ?, ?, ?)";
try {
PreparedStatement statement = DbConnection.getInstance().getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
statement.setLong(1, entity.getId());
statement.setString(2, entity.getNim());
statement.setString(3, entity.getNama());
statement.setString(4, entity.getAlamat());
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
entity.setId(generatedKeys.getLong(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return entity;
}
@Override
public Mahasiswa update(Mahasiswa entity) {
String sql = "UPDATE mahasiswa SET " +
"nim = ?, " +
"nama = ?, " +
"alamat = ? " +
"WHERE id = ? ";
try {
PreparedStatement statement = DbConnection.getInstance().getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
statement.setString(1, entity.getNim());
statement.setString(2, entity.getNama());
statement.setString(3, entity.getAlamat());
statement.setLong(4, entity.getId());
statement.executeUpdate();
ResultSet generatedKeys = statement.getGeneratedKeys();
if (generatedKeys.next()) {
entity.setId(generatedKeys.getLong(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return entity;
}
@Override
public List<Mahasiswa> find(int offset, int limit) {
List<Mahasiswa> mahasiswas = new ArrayList<>();
String sql = "SELECT * FROM mahasiswa " +
"ORDER BY id DESC ";
if (offset != 0 && limit != 0) {
sql += "limit ?, ? ";
}
try {
PreparedStatement statement = DbConnection.getInstance().getConnection().prepareStatement(sql);
if (offset != 0 && limit != 0) {
statement.setInt(1, offset);
statement.setInt(2, limit);
}
ResultSet rs = statement.executeQuery();
while (rs.next()) {
Mahasiswa mahasiswa = new Mahasiswa();
mahasiswa.setId(rs.getInt("id"));
mahasiswa.setNim(rs.getString("nim"));
mahasiswa.setNama(rs.getString("nama"));
mahasiswa.setAlamat(rs.getString("alamat"));
mahasiswas.add(mahasiswa);
}
} catch (SQLException e) {
e.printStackTrace();
}
return mahasiswas;
}
@Override
public Mahasiswa findById(long id) {
Mahasiswa mahasiswa = new Mahasiswa();
String sql = "SELECT * FROM mahasiswa WHERE id = ? ";
try {
PreparedStatement statement = DbConnection.getInstance().getConnection().prepareStatement(sql);
statement.setLong(1, id);
statement.executeUpdate();
ResultSet rs = statement.executeQuery();
while (rs.next()) {
mahasiswa.setId(rs.getInt("id"));
mahasiswa.setNim(rs.getString("nim"));
mahasiswa.setNama(rs.getString("nama"));
mahasiswa.setAlamat(rs.getString("alamat"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return mahasiswa;
}
@Override
public String delete(long id) {
String sql = "DELETE FROM mahasiswa WHERE id = ? ";
String message;
try {
PreparedStatement statement = DbConnection.getInstance().getConnection().prepareStatement(sql);
statement.setLong(1, id);
int status = statement.executeUpdate();
if (status == 0) {
message = "Delete Failed!";
} else {
message = "Record is deleted!";
}
} catch (SQLException e) {
e.printStackTrace();
message = "Delete Failed!";
}
return message;
}
}
|
Java | UTF-8 | 426 | 2.265625 | 2 | [] | no_license | package com.bit.reflect.VO;
import java.lang.reflect.InvocationTargetException;
/**
* @Author: yd
* @Date: 2019/4/9 16:54
* @Version 1.0
*/
public class EmpAction {
private Emp emp=new Emp();
public void setValue(String value) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
BeanUtil.setBeanValue(this,value);
}
public Emp getEmp(){
return emp;
}
}
|
JavaScript | UTF-8 | 5,205 | 2.625 | 3 | [] | no_license | import React, { Component } from 'react';
import CurriculumElement from './CurriculumElement';
import fire from './../../fire';
import LoginRequired from '../Login/LoginRequired';
class Curriculums extends Component {
constructor(props) {
super(props);
this.state = {
origCurriculums: [],
updatedCurriculums: [],
name: "",
description: "",
link: "",
color: "",
formError: "",
};
this.addCurriculum = this.addCurriculum.bind(this);
this.filterList = this.filterList.bind(this);
}
addCurriculum() {
var self = this;
var curriculumsRef = fire.database().ref('/curriculums/');
// Get id for new curriculum
var id = curriculumsRef.push().path["pieces_"][1];
// Add curriculum object to firebase DB
fire.database().ref('/curriculums/' + id)
.set({
id: id,
name: self.state.name,
description: self.state.description,
link: self.state.link,
color: "#"+((1<<24)*Math.random()|0).toString(16) // Generate random color
}).catch(function(error) {
self.setState({ formError: error.code + ": " + error.message });
});
// Clear the data in the add modal
this.setState({
name: "",
description: "",
link: ""
});
}
filterList(event) {
var updatedList = this.state.origCurriculums;
updatedList = updatedList.filter(item =>
item.name.toLowerCase().search(event.target.value.toLowerCase()) !== -1);
this.setState({updatedCurriculums: updatedList});
}
componentDidMount() {
var self = this;
var curriculumRef = fire.database().ref("curriculums/");
curriculumRef.orderByChild("name").on("value", function(data) {
// Get list of curriculums
var curriculums = data.val() ? Object.values(data.val()) : [];
// Sort the curriculums
var sortedCurriculums = curriculums.sort((a, b) => {
var first_name = a.name.toUpperCase();
var second_name = b.name.toUpperCase();
return (first_name < second_name) ? -1 : (first_name > second_name) ? 1 : 0;
});
self.setState({
origCurriculums: sortedCurriculums,
updatedCurriculums: sortedCurriculums,
});
});
}
render() {
return (
<div className="Curriculums">
<div
className="modal fade"
id="addCurriculumModal"
tabIndex="-1"
role="dialog"
aria-labelledby="addCurriculumModal"
aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="addCurriculumModalTitle">Add Curriculum</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div className="modal-body">
<div className="form-group">
<label htmlFor="name">Name:</label>
<input
type="text"
name="name"
className="form-control"
onChange={event => this.setState({name: event.target.value})}
value={this.state.name} />
</div>
<div className="form-group">
<label htmlFor="description">Description:</label>
<textarea
className="form-control"
rows="5"
name="description"
onChange={event => this.setState({description: event.target.value})}
value={this.state.description}></textarea>
</div>
<div className="form-group">
<label htmlFor="link">Link:</label>
<input
type="text"
name="link"
className="form-control"
onChange={event => this.setState({link: event.target.value})}
value={this.state.link} />
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-success"
onClick={this.addCurriculum}
data-dismiss="modal">
Save
</button>
<button
type="button"
className="btn btn-danger"
data-dismiss="modal">
Cancel
</button>
</div>
</form>
</div>
</div>
</div>
<div className="container">
<div className="mod-opts">
<input
className="form-control"
placeholder="Search"
id="search"
onChange={this.filterList} />
<div className="mod-btns">
<LoginRequired minRole="admin">
<button
type="button"
className="btn btn-success"
data-toggle="modal"
data-target="#addCurriculumModal">
Add
</button>
</LoginRequired>
</div>
</div>
<div className="list-container">
{this.state.updatedCurriculums.map(curriculum =>
<CurriculumElement
key={curriculum.id}
id={curriculum.id}
name={curriculum.name}
description={curriculum.description}
link={curriculum.link}
grade_levels={curriculum.grade_levels ? Object.values(curriculum.grade_levels) : []}
color={curriculum.color} />
)}
</div>
</div>
<main>
{this.props.children}
</main>
</div>
);
}
}
export default Curriculums;
|
Python | UTF-8 | 433 | 2.625 | 3 | [] | no_license | from estimators.moyenne import Moyenne as M
from estimators.ecart_type import Ecart_type as E
class Normalisation():
def normalisation(self,data):
new_data = []
for liste in data[1:]:
l = []
for i in range(len(liste)):
l.append((float(liste[i]) - M().moyenne(data, data[0][i]))/E().ecart_type_corr(data, data[0][i]))
new_data.append(l)
return new_data |
PHP | UTF-8 | 2,892 | 3 | 3 | [] | no_license | <?php
/**
* @param array $tableau
*/
function debug($tableau)
{
echo '<pre style="height:200px;overflow-y: scroll;font-size: .7em;padding:10px;font-family: Consolas, Monospace; background-color: #000;color:#fff;">';
print_r($tableau);
echo '</pre>';
}
function imageMovie($movie)
{
return '<img src="posters/'.$movie['id'].'.jpg" alt="'.$movie['title'].'">';
}
function cleanXss(string $key)
{
return trim(strip_tags($_POST[$key]));
}
function getError($errors,$key){
return (!empty($errors[$key])) ? $errors[$key] : '';
}
function getValue($key,$data = null){
if(!empty($_POST[$key])) {
return $_POST[$key];
} else {
if(!empty($data)) {
return $data;
}
}
return '';
}
// Validation formulaire
function validText($errors,$data,$key,$min =2,$max = 50)
{
if(!empty($data)) {
if(mb_strlen($data) < $min) {
$errors[$key] = 'min '.$min.' caractères';
} elseif(mb_strlen($data) > $max) {
$errors[$key] = 'max '.$max.' caractères';
}
} else {
$errors[$key] = 'Veuillez renseigner ce champ';
}
return $errors;
}
function validEmail($errors,$data,$key)
{
if(!empty($data)) {
if (!filter_var($data, FILTER_VALIDATE_EMAIL)) {
$errors[$key] = 'Veuillez renseigner un email valide';
}
} else{
$errors[$key] = 'Veuillez renseigner un email';
}
return $errors;
}
/**
* @param string $data
* @param string $format
* @return string
*/
function dateFormat($data, string $format = 'd/m/Y à H:i') : string
{
if($data == null) {
return '';
}
return date($format,strtotime($data));
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function getArticleById($id)
{
global $pdo;
$sql = "SELECT * FROM articles WHERE id = :id";
$query = $pdo->prepare($sql);
$query->bindValue(':id',$id,PDO::PARAM_INT);
$query->execute();
return $query->fetch();
}
function isLogged()
{
if(!empty($_SESSION['user'])) {
if(!empty($_SESSION['user']['id'])) {
if(!empty($_SESSION['user']['pseudo'])) {
if(!empty($_SESSION['user']['email'])) {
if(!empty($_SESSION['user']['role'])) {
if(!empty($_SESSION['user']['ip'])) {
if($_SESSION['user']['ip'] == $_SERVER['REMOTE_ADDR']) {
return true;
}
}
}
}
}
}
}
return false;
}
|
JavaScript | UTF-8 | 315 | 2.640625 | 3 | [
"MIT"
] | permissive | import moment from 'moment'
export default (events) => {
let monthEvents = {}
events.forEach(item => {
let startDate = moment(item.start).format('YYYY-MM-DD')
if (monthEvents[startDate])
monthEvents[startDate].push(item)
else
monthEvents[startDate] = [item]
})
return monthEvents
}
|
JavaScript | UTF-8 | 483 | 4.53125 | 5 | [] | no_license | //O(N)
// Given an array of strings, capitalize the first letter of ecah string in the array
function capitalizeFirst(array) {
if (array.length === 1) {
return [ array[0][0].toUpperCase() + array[0].substr(1) ];
}
const res = capitalizeFirst(array.slice(0, -1));
const string = array.slice(array.length - 1)[0][0].toUpperCase() + array.slice(array.length - 1)[0].substr(1);
res.push(string);
return res;
}
console.log(capitalizeFirst([ 'car', 'taco', 'banana' ]))
|
Python | UTF-8 | 2,407 | 4.125 | 4 | [] | no_license | #!/usr/bin/python
# Greedy Algorithm for minimizing the weighted sum of completion times
# This file describes a set of jobs with positive and integral weights and lengths. It has the format
#
# [number_of_jobs]
# [job_1_weight] [job_1_length]
# [job_2_weight] [job_2_length]
#
# For example, the third line of the file is "74 59", indicating that the second job has weight 74 and length 59.
#
# You should NOT assume that edge weights or lengths are distinct.
#
# Your task in this problem is to run the greedy algorithm that schedules jobs in decreasing order
# of the difference (weight - length). Recall from lecture that this algorithm is not always optimal.
# IMPORTANT: if two jobs have equal difference (weight - length), you should schedule the job with
# higher weight first. Beware: if you break ties in a different way, you are likely to get the wrong
# answer. You should report the sum of weighted completion times of the resulting schedule --- a positive integer.
# load contents of text file into a list numList
NUMLIST_FILENAME = "data/mwsct.txt" # diff: 69119377652
# NUMLIST_FILENAME = "data/tests/mwsct-test-1.txt" # diff: 31814
# NUMLIST_FILENAME = "data/tests/mwsct-test-2.txt" # diff: 61545
# NUMLIST_FILENAME = "data/tests/mwsct-test-3.txt" # diff: 688647
inFile = open(NUMLIST_FILENAME, 'r')
jobs = []
num_jobs = 0
for f in inFile:
if(num_jobs == 0):
num_jobs = int(f.strip())
else:
weight, length = map(int, f.split())
jobs.append([weight, length, weight - length])
def sumWeightedCompletionTimes():
global jobs
'''given a list with format [job_weight, job_length, weight - length]
it uses two sorts, one to order them by decreasing order of weight
and the other to order them in decreasing order of weight - length.
Cause sorted function is stable we keep the equal comparision ordered
by decreasing weight as required. Return the sum of completion times.'''
jobs = sorted(jobs, key=lambda x: x[0], reverse=True)
jobs = sorted(jobs, key=lambda x: x[2], reverse=True)
completion_time = 0
sum_weighted_completion_time = 0
for job in jobs:
completion_time += job[1]
sum_weighted_completion_time += job[0] * completion_time
return sum_weighted_completion_time
sum_weighted_completion_time = sumWeightedCompletionTimes()
print 'result: ' + str(sum_weighted_completion_time)
|
Markdown | UTF-8 | 601 | 2.59375 | 3 | [] | no_license | ## Lame 库PCM转成mp3函数
```
public byte[] getMp3(byte[] pcm){
byte[] _mp3OutputBuf = new byte[1024 * 10];
int mp3BufLen = Lame.encode(pcm, pcm, pcm.length / 2, _mp3OutputBuf, _mp3OutputBuf.length);
if(mp3BufLen < 0){
LogBuffer.ONE.e(TAG, "mp3 encoder error:" + mp3BufLen);
return null;
}
byte[] ret = new byte[mp3BufLen];
System.arraycopy(_mp3OutputBuf, 0, ret, 0, mp3BufLen);
Log.e(TAG, "mp3 length:" + ret.length);
return ret;
}
```
调用之前调用Lame.initializeEncoder(16000, 1)初始化一下
|
JavaScript | UTF-8 | 219 | 3.359375 | 3 | [] | no_license |
const meowFunction = function() {
let hey = 8;
let meow = ["peaas", "cars"];
}
console.log("yes");
var someArray = [1, 4, 6, 2, 17];
someArray.forEach(/* pass in function here*/);
document.querySelector();
|
SQL | UTF-8 | 919 | 2.875 | 3 | [] | no_license | delimiter $
create Trigger Check_Cap
before insert on room
for each row
begin
if(new.capacity<0||new.capacity>30) then
signal sqlstate '10101'
set message_text='Capacity ranges from 0 to 30';
end if;
end;$
delimiter ;
***************************************************************************
mysql> source Triggers.sql
Query OK, 0 rows affected (0.01 sec)
mysql> insert into room values('A160',-13,'A');
ERROR 1644 (42000): Capacity ranges from 0 to 30
mysql> select * from room;
+---------+----------+----------+
| room_no | capacity | building |
+---------+----------+----------+
| A104 | 30 | A |
| B203 | 30 | B |
| C302 | 30 | C |
| C304 | 30 | C |
| C306 | 30 | C |
| C404 | 30 | C |
+---------+----------+----------+
6 rows in set (0.00 sec)
|
Shell | UTF-8 | 2,193 | 3.90625 | 4 | [] | no_license | #!/bin/bash
VERSION=2.0.0
export HVM="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
export PATH=$PATH:$HVM/bin
PATH_PREFIX=$HVM/bin
source $HVM/config.sh
hvm_get_haxe_versions() {
HAXE_VERSIONS=()
local VERSIONS=`curl --silent https://haxe.org/download/list/ 2>&1 | grep -oE 'version\/[^/]+' | cut -d / -f 2 | awk '!a[$0]++'`
for VERSION in $VERSIONS; do
HAXE_VERSIONS+=($VERSION)
done
}
hvm_get_neko_versions() {
NEKO_VERSIONS=("1.8.1" "1.8.2" "2.0.0" "2.1.0" "2.2.0")
}
hvm_valid_version() {
if [ "$1" == "dev" ]; then
return 0
fi
local e
for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
echo "version $1 was not one of ${@:2}"
return 1
}
hvm_save_current() {
rm -f $HVM/current.sh
echo "export NEKO=$NEKO" >> $HVM/current.sh
echo "export HAXE=$HAXE" >> $HVM/current.sh
}
hvm() {
case $1 in
"use" )
case $2 in
"haxe" )
HAXE=$3
if [ "$HAXE" == "latest" ]; then
rm -rf $HVM/versions/haxe/dev
HAXE="dev"
fi
hvm_get_haxe_versions
hvm_valid_version $HAXE ${HAXE_VERSIONS[@]} && hvm_save_current
source $HVM/config.sh
;;
"neko" )
NEKO=$3
if [ "$NEKO" == "latest" ]; then
rm -rf $HVM/versions/neko/dev
NEKO="dev"
fi
hvm_get_neko_versions
hvm_valid_version $NEKO ${NEKO_VERSIONS[@]} && hvm_save_current
source $HVM/config.sh
;;
* )
echo "binary \"$2\" was not one of (neko haxe)"
return
;;
esac
;;
"install" )
mkdir -p $HVM/bin
ln -sf $HVM/haxe.sh $PATH_PREFIX/haxe
ln -sf $HVM/haxelib.sh $PATH_PREFIX/haxelib
ln -sf $HVM/neko.sh $PATH_PREFIX/neko
ln -sf $HVM/nekotools.sh $PATH_PREFIX/nekotools
ln -sf $HVM/nekoc.sh $PATH_PREFIX/nekoc
ln -sf $HVM/nekoml.sh $PATH_PREFIX/nekoml
source $HVM/config.sh
;;
"versions" )
case $2 in
"haxe" )
hvm_get_haxe_versions
for VERSION in "${HAXE_VERSIONS[@]}"; do
echo "$VERSION"
done
;;
"neko" )
hvm_get_neko_versions
for VERSION in "${NEKO_VERSIONS[@]}"; do
echo "$VERSION"
done
;;
* )
echo "binary \"$2\" was not one of (neko haxe)"
return
;;
esac
;;
"help" | * )
echo "Haxe Version Manager $VERSION"
echo "Usage: hvm use (neko|haxe) (latest|dev|1.2.3)"
;;
esac
}
|
Python | UTF-8 | 910 | 2.765625 | 3 | [] | no_license | import unittest
import l457
class testSolution(unittest.TestCase):
def setUp( self ):
self.s = l457.Solution()
def test_solution( self ):
got = self.s.firstMissingPositive([1,2,0])
self.assertEqual(got, 3)
got = self.s.firstMissingPositive([3,4,-1,1])
self.assertEqual(got, 2)
got = self.s.firstMissingPositive([7,8,9,11,12])
self.assertEqual(got, 1)
got = self.s.firstMissingPositive([7,5,4,3,2,1])
self.assertEqual(got, 6)
got = self.s.firstMissingPositive([7,5,4,3,2,1])
self.assertEqual(got, 6)
got = self.s.firstMissingPositive([0,-1,-2])
self.assertEqual(got, 1)
got = self.s.firstMissingPositive([1,-1,-2])
self.assertEqual(got, 2)
got = self.s.firstMissingPositive([1,1,2])
self.assertEqual(got, 3)
if __name__ == "__main__":
unittest.main()
|
Java | UTF-8 | 777 | 2.328125 | 2 | [] | no_license | package com.project.polishedlms.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.widget.Toast;
public class Utility {
public static boolean checkNetwork(Context context) {
ConnectivityManager ConnectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = ConnectionManager.getActiveNetworkInfo();
{
if (networkInfo != null && networkInfo.isConnected() == true)
return true;
}
return false;
}
public static void showToast(Context context, String msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}
|
C++ | UTF-8 | 799 | 3.84375 | 4 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include "stack.h"
/* stack.h
namespace Stack {
void push(char) ;
char pop() ;
}
*/
namespace Stack {
const int MAX_SIZE = 10 ;
char v[MAX_SIZE] ;
int top = 0 ;
class Overflow {} ;
void push( char c ) {
cout << "Push " << c << "\n" ;
if (top==MAX_SIZE)
throw Overflow() ;
v[top++] = c ;
}
char pop() {
cout << "Popping...\n" ;
return v[--top] ;
}
}
void test1() {
char ch ;
Stack::push('c') ;
ch = Stack::pop() ;
if ( ch != 'c' )
cout << "Impossible!" ;
else
cout << "Got: " << ch ;
}
void test2() {
try {
for(;;) {
Stack::push('c') ;
}
}
catch (Stack::Overflow) {
cout << "Caught Overflow Exception...\n" ;
}
}
int main() {
//test1() ;
test2() ;
}
|
Java | UTF-8 | 429 | 3.15625 | 3 | [] | no_license | package com.lrh.mediation;
public class Colleague2 {
private AbstractMediator abstractMediator;
public Colleague2(AbstractMediator abstractMediator) {
this.abstractMediator = abstractMediator;
}
public void doSomeThing2(){
System.out.println("同事2完成事2");
}
public void doSomeThingNeedAssist(){
System.out.println("同事2处理需要中介协助的事情");
this.abstractMediator.doSomeThing1();
}
}
|
C# | UTF-8 | 2,119 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | using nValid.Utilities.Formatting;
namespace nValid.Framework
{
public class BrokenRule
{
private readonly IRule rule;
private readonly object validatedInstance;
private readonly string propertyName;
private readonly object invalidValue;
private readonly string propertyKey;
public string Message
{
get
{
string message = null;
// Try and get message template from resource
if (!string.IsNullOrEmpty(rule.Resource))
message = ValidationContext.GetResourceString(rule.Resource);
// If no resource, get message template from rule
if (string.IsNullOrEmpty(message))
message = rule.Message;
// Format message template
message = message.HaackFormat(new
{
Instance = validatedInstance,
Value = invalidValue,
Property = propertyName
});
return message;
}
}
public string PropertyKey
{
get { return propertyKey; }
}
public string PropertyDisplayName
{
get { return propertyName; }
}
public object InvalidInstance
{
get { return validatedInstance; }
}
public object InvalidValue
{
get { return invalidValue; }
}
public BrokenRule(IRule rule, object validatedInstance, string propertyKey, string propertyName, object invalidValue)
{
this.rule = rule;
this.validatedInstance = validatedInstance;
this.propertyKey = propertyKey;
this.propertyName = propertyName;
this.invalidValue = invalidValue;
}
}
} |
TypeScript | UTF-8 | 13,607 | 2.53125 | 3 | [
"MIT"
] | permissive | import {
LitElement,
html,
css,
property,
customElement,
CSSResult,
TemplateResult,
query,
internalProperty,
} from 'lit-element';
import {classMap} from 'lit-html/directives/class-map';
import {styleMap} from 'lit-html/directives/style-map';
import {ifDefined} from 'lit-html/directives/if-defined';
import {INPUT_LINE_HEIGHT_RATIO} from './includes/helpers';
enum Severity {
DEFAULT = 'default',
INFO = 'info',
WARNING = 'warning',
ERROR = 'error',
}
type InputType =
| 'color'
| 'date'
| 'datetime-local'
| 'email'
| 'file'
| 'month'
| 'number'
| 'password'
| 'tel'
| 'text'
| 'time'
| 'url'
| 'week';
const LINE_HEIGHT = 17;
const PADDING = 4;
const BORDER_WIDTH = 1;
const calcHeightFromLines = (lines: number) => {
return BORDER_WIDTH * 2 + PADDING * 2 + lines * LINE_HEIGHT;
};
/**
* @attr {narrow|wide} variant - The sizes are borrowed from the VSCode settings page. The narrow size is typically used for the numeric values and the wide size for the text.
* @attr name - Name which is used as a variable name in the data of the form-container.
*
* @cssprop --vscode-scrollbarSlider-background
* @cssprop --vscode-scrollbarSlider-hoverBackground
* @cssprop --vscode-scrollbarSlider-activeBackground
* @cssprop --vscode-input-background
* @cssprop --vscode-settings-textInputBorder
* @cssprop --vscode-input-foreground
* @cssprop --vscode-input-placeholderForeground
* @cssprop --vscode-focusBorder
* @cssprop --vscode-panelInput-border
* @cssprop --vscode-focusBorder
* @cssprop --vscode-inputValidation-infoBackground
* @cssprop --vscode-inputValidation-infoBorder
* @cssprop --vscode-inputValidation-warningBackground
* @cssprop --vscode-inputValidation-warningBorder
* @cssprop --vscode-inputValidation-errorBackground
* @cssprop --vscode-inputValidation-errorBorder
* @cssprop --vscode-editor-background
*/
@customElement('vscode-inputbox')
export class VscodeInputbox extends LitElement {
@property()
label = '';
@property({type: Boolean})
multiline = false;
@property({type: String})
message = '';
@property({type: String})
set severity(val: string) {
const oldVal = this._severity;
switch (val) {
case Severity.INFO:
case Severity.WARNING:
case Severity.ERROR:
this._severity = val;
break;
default:
this._severity = Severity.DEFAULT;
}
this.requestUpdate('messageSeverity', oldVal);
}
get severity(): string {
return this._severity;
}
/**
* @deprecated
* @attr panelInput
*/
@property({type: Boolean})
panelInput = false;
/**
* Text-like input types
* @attr type
* @type {"color"|"date"|"datetime-local"|"email"|"file"|"month"|"number"|"password"|"tel"|"text"|"time"|"url"|"week"}
*/
@property({type: String})
type: InputType = 'text';
@property({type: Boolean, reflect: true})
focused = false;
@property({type: String})
value = '';
@property({type: String})
placeholder = '';
@property({type: Number})
lines = 2;
@property({type: Number})
maxLines = 5;
@property({type: Number})
min: number | undefined = undefined;
@property({type: Number})
minLength: number | undefined = undefined;
@property({type: Number})
max: number | undefined = undefined;
@property({type: Number})
maxLength: number | undefined = undefined;
@property({type: Boolean})
multiple = false;
@property({type: Boolean})
readonly = false;
@property({type: Number})
step: number | undefined = undefined;
/* @property({reflect: true, type: Number})
tabindex = 0; */
@query('.content-measurer')
private _measurerEl!: HTMLDivElement;
@query('.input-element')
private _inputElement!: HTMLInputElement | HTMLTextAreaElement;
@internalProperty()
private _textareaHeight = 0;
private _severity: Severity;
private _textareaDefaultCursor = false;
constructor() {
super();
this._severity = Severity.DEFAULT;
}
connectedCallback(): void {
super.connectedCallback();
this.resizeTextareaIfRequired();
}
updated(
changedProperties: Map<string, undefined | string | boolean | number>
): void {
if (changedProperties.has('value')) {
this.resizeTextareaIfRequired();
}
}
get focusElement(): HTMLInputElement | HTMLTextAreaElement {
return this._inputElement;
}
focus(): void {
this._inputElement.focus();
}
toString(): string {
return '[object VscodeInputbox]';
}
private onInputFocus = () => {
this.focused = true;
};
private onInputBlur = () => {
this.focused = false;
};
private onInputInput = (event: InputEvent) => {
const eventTarget = <HTMLInputElement | HTMLTextAreaElement>event.target;
this.value = eventTarget.value;
this.dispatchEvent(
new CustomEvent('vsc-input', {
detail: eventTarget.value,
bubbles: true,
composed: true,
})
);
this.resizeTextareaIfRequired();
};
private onInputChange = (event: InputEvent) => {
const eventTarget = <HTMLInputElement | HTMLTextAreaElement>event.target;
this.dispatchEvent(
new CustomEvent('vsc-change', {
detail: eventTarget.value,
bubbles: true,
composed: true,
})
);
};
private onTextareaMouseMove = (event: MouseEvent) => {
const br = this.getBoundingClientRect();
const x = event.clientX;
const SCROLLBAR_WIDTH = 10;
this._textareaDefaultCursor =
x <= br.left + br.width &&
x >= br.left + br.width - SCROLLBAR_WIDTH - BORDER_WIDTH * 2;
this.requestUpdate();
};
private resizeTextareaIfRequired = (): void => {
if (!this._measurerEl || !this.multiline) {
return;
}
const {height} = this._measurerEl.getBoundingClientRect();
if (height === 0) {
this._textareaHeight = calcHeightFromLines(this.lines);
this._measurerEl.style.minHeight = `${calcHeightFromLines(this.lines)}px`;
} else {
this._textareaHeight = height;
}
};
static get styles(): CSSResult {
return css`
:host {
display: inline-block;
max-width: 100%;
width: 320px;
}
:host([size-variant="narrow"]) {
width: 200px;
}
:host([size-variant="wide"]) {
width: 500px;
}
.container {
position: relative;
}
.cursor-default {
cursor: default;
}
textarea {
left: 0;
overflow: visible;
position: absolute;
resize: none;
top: 0;
}
.content-measurer::-webkit-scrollbar,
textarea::-webkit-scrollbar {
cursor: default;
width: 10px;
}
.content-measurer::-webkit-scrollbar-button,
textarea::-webkit-scrollbar-button {
display: none;
}
textarea::-webkit-scrollbar-track {
background-color: transparent;
width: 10px;
}
.content-measurer::-webkit-scrollbar-track {
width: 10px;
}
textarea::-webkit-scrollbar-thumb {
background-color: transparent;
}
textarea:hover::-webkit-scrollbar-thumb {
background-color: var(--vscode-scrollbarSlider-background);
}
textarea:hover::-webkit-scrollbar-thumb:hover {
background-color: var(--vscode-scrollbarSlider-hoverBackground);
}
textarea:hover::-webkit-scrollbar-thumb:active {
background-color: var(--vscode-scrollbarSlider-activeBackground);
}
input,
textarea {
background-color: var(--vscode-input-background);
border-color: var(--vscode-settings-textInputBorder, rgba(0, 0, 0, 0));
border-style: solid;
border-width: 1px;
box-sizing: border-box;
color: var(--vscode-input-foreground);
display: block;
font-family: var(--vscode-font-family);
font-size: var(--vscode-font-size);
line-height: ${INPUT_LINE_HEIGHT_RATIO};
outline: none;
padding: 4px;
width: 100%;
}
input::placeholder,
textarea::placeholder {
color: var(--vscode-input-placeholderForeground);
}
input::selection,
textarea::selection {
background-color: var(--vscode-editor-selectionBackground);
}
input:focus,
textarea:focus {
border-color: var(--vscode-focusBorder);
}
.container.panel-input input,
.container.panel-input textarea {
border-color: var(--vscode-panelInput-border);
}
.container.default input,
.container.default textarea,
.container.panel-input.default input,
.container.panel-input.default textarea {
border-color: var(--vscode-focusBorder);
}
.container.info input,
.container.info textarea,
.container.panel-input.info input,
.container.panel-input.info textarea {
border-color: var(--vscode-inputValidation-infoBorder);
}
.container.warning input,
.container.warning textarea,
.container.panel-input.warning input,
.container.panel-input.warning textarea {
border-color: var(--vscode-inputValidation-warningBorder);
}
.container.error input,
.container.error textarea,
.container.panel-input.error input,
.container.panel-input.error textarea {
border-color: var(--vscode-inputValidation-errorBorder);
}
.message {
border-style: solid;
border-width: 1px;
box-sizing: border-box;
display: none;
font-size: 12px;
line-height: 17px;
margin-top: -1px;
overflow: hidden;
padding: 0.4em;
position: absolute;
user-select: none;
top: 100%;
text-align: left;
width: 100%;
word-wrap: break-word;
}
.focused:not(.default) .message {
display: block;
}
.message.default {
background-color: var(--vscode-editor-background);
border-color: var(--vscode-focusBorder);
}
.message.info {
background-color: var(--vscode-inputValidation-infoBackground);
border-color: var(--vscode-inputValidation-infoBorder);
}
.message.warning {
background-color: var(--vscode-inputValidation-warningBackground);
border-color: var(--vscode-inputValidation-warningBorder);
}
.message.error {
background-color: var(--vscode-inputValidation-errorBackground);
border-color: var(--vscode-inputValidation-errorBorder);
}
.content-measurer {
background-color: green;
border: 1px solid transparent;
box-sizing: border-box;
font-family: var(--vscode-font-family);
font-size: var(--vscode-font-size);
left: 0;
line-height: ${INPUT_LINE_HEIGHT_RATIO};
overflow: auto;
padding: 4px;
text-align: left;
top: 0;
visibility: hidden;
word-break: break-all;
}
`;
}
render(): TemplateResult {
const minHeight = calcHeightFromLines(this.lines);
const maxHeight = calcHeightFromLines(this.maxLines);
const measurerStyles = styleMap({
minHeight: `${minHeight}px`,
maxHeight: `${maxHeight}px`,
});
const textareaStyles = styleMap({
height: `${this._textareaHeight}px`,
});
const containerClasses = classMap({
container: true,
severity: this.severity !== Severity.DEFAULT,
focused: this.focused,
});
const measurerContent = this.value
? this.value
.split('\n')
.map((line) =>
line ? html`<div>${line}</div>` : html`<div> </div>`
)
: html` `;
const textarea = html`
<textarea
@focus="${this.onInputFocus}"
@blur="${this.onInputBlur}"
@input="${this.onInputInput}"
@change="${this.onInputChange}"
@mousemove="${this.onTextareaMouseMove}"
class="${classMap({
'cursor-default': this._textareaDefaultCursor,
'input-element': true,
})}"
minlength="${ifDefined(this.minLength)}"
maxlength="${ifDefined(this.maxLength)}"
placeholder="${this.placeholder}"
?readonly="${this.readonly}"
style="${textareaStyles}"
.value="${this.value}"
></textarea>
<div class="content-measurer" style="${measurerStyles}">
${measurerContent}
</div>
`;
const input = html`
<input
type="${this.type}"
@focus="${this.onInputFocus}"
@blur="${this.onInputBlur}"
@input="${this.onInputInput}"
@change="${this.onInputChange}"
placeholder="${this.placeholder}"
min="${ifDefined(this.min)}"
minlength="${ifDefined(this.minLength)}"
max="${ifDefined(this.max)}"
maxlength="${ifDefined(this.maxLength)}"
?multiple="${this.multiple}"
?readonly="${this.readonly}"
step="${ifDefined(this.step)}"
.value="${this.value}"
class="input-element"
/>
`;
const message = html`
<div class="message ${this.severity}">${this.message}</div>
`;
return html`
<div class="${containerClasses}">
<div class="helper"><slot name="helper"></slot></div>
<div class="input-wrapper">
${this.multiline ? textarea : input} ${this.message ? message : ''}
</div>
</div>
`;
}
}
declare global {
interface HTMLElementTagNameMap {
'vscode-inputbox': VscodeInputbox;
}
}
|
Java | UTF-8 | 1,918 | 2.5625 | 3 | [] | no_license | package com.example.android.taskdo;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.android.taskdo.Tabs.FridayFragment;
import com.example.android.taskdo.Tabs.MondayFragment;
import com.example.android.taskdo.Tabs.NotesFragment;
import com.example.android.taskdo.Tabs.SaturdayFragment;
import com.example.android.taskdo.Tabs.SundayFragment;
import com.example.android.taskdo.Tabs.ThursdayFragment;
import com.example.android.taskdo.Tabs.TuesdayFragment;
import com.example.android.taskdo.Tabs.WednesdayFragment;
public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
public SimpleFragmentPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public Fragment getItem(int position) {
switch (position)
{
case 0: return new NotesFragment(0);
case 1: return new MondayFragment(1);
case 2: return new TuesdayFragment(2);
case 3: return new WednesdayFragment(3);
case 4: return new ThursdayFragment(4);
case 5: return new FridayFragment(5);
case 6: return new SaturdayFragment(6);
case 7: return new SundayFragment(7);
default: return null;
}
}
@Override
public int getCount() {
return 8;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
switch (position)
{
case 0: return "NOTE";
case 1: return "LUN";
case 2: return "MAR";
case 3: return "MER";
case 4: return "GIO";
case 5: return "VEN";
case 6: return "SAB";
case 7: return "DOM";
default: return "DEF_PAGE_TITLE";
}
}
}
|
Java | UTF-8 | 586 | 1.648438 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | package org.inbloom.portal;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* Created By: paullawler
*/
@Configuration
@EnableAutoConfiguration
@EnableWebMvc
@ComponentScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
Python | UTF-8 | 1,286 | 2.8125 | 3 | [] | no_license | __import__('pkg_resources').declare_namespace(__name__)
from meta import DictValidatorMeta
from exceptions import *
class DictValidator(object):
__metaclass__ = DictValidatorMeta
def __init__(self, dictionary):
validation_errors = []
if not isinstance(dictionary, dict):
validation_errors.append(
Exception('DictValidator attempted to validate non-dict type'))
else:
for fname in self._fields:
field = self._fields[fname]
# first check if it exists and add an error if it is absent
exists = fname in dictionary
if not exists:
if field.required:
validation_errors.append(FieldAbsentException(fname))
else:
setattr(self, fname, None)
continue
# now that we know its there, validate it
try:
setattr(self, fname, self._fields[fname](dictionary[fname]))
except DictValidationException as e:
validation_errors.append(e)
is_valid = len(validation_errors) == 0
if not is_valid:
raise DictValidationException(validation_errors) |
Java | UTF-8 | 7,290 | 2.375 | 2 | [] | no_license | package com.flipkart.billsharing.service;
import com.flipkart.billsharing.common.BillStatus;
import com.flipkart.billsharing.common.MemberBillStatus;
import com.flipkart.billsharing.common.SplitMethod;
import com.flipkart.billsharing.dao.BillDao;
import com.flipkart.billsharing.dao.GroupDao;
import com.flipkart.billsharing.dao.UserDao;
import com.flipkart.billsharing.dao.entities.Bill;
import com.flipkart.billsharing.dao.entities.Group;
import com.flipkart.billsharing.dao.entities.MemberBillDetails;
import com.flipkart.billsharing.dao.entities.User;
import com.flipkart.billsharing.service.dto.BillMemberDetails;
import com.flipkart.billsharing.service.dto.CreateBillDTO;
import com.flipkart.billsharing.service.dto.CreateGroupDTO;
import com.flipkart.billsharing.service.vo.CreateBillVO;
import com.flipkart.billsharing.service.vo.CreateGroupVO;
import com.flipkart.billsharing.service.vo.UserDashboardVO;
import java.util.*;
import java.util.stream.Collectors;
public class BillSharingService implements IBillSharingService{
private BillDao billDao;
private GroupDao groupDao;
public UserDao userDao;
private BillSharingService(){
this.billDao = new BillDao();
this.groupDao = new GroupDao();
this.userDao = new UserDao();
}
@Override
public CreateGroupVO createGroup(CreateGroupDTO createGroupDTO) throws Exception {
Group group = convertDTOToEntity(createGroupDTO);
String groupID = groupDao.createGroup(group);
addMembersToGroup(createGroupDTO.getMemberIds(), group);
return CreateGroupVO.builder().groupId(groupID).build();
}
@Override
public CreateBillVO createBill(CreateBillDTO createBillDTO) throws Exception {
Bill bill = convertDTOToEntity(createBillDTO);
String billId = billDao.createBill(bill);
updateUserTotalBalance(bill);
return CreateBillVO.builder().billId(billId).build();
}
@Override
public UserDashboardVO getUserDashBoard(String userId) throws Exception {
User user = userDao.getUser(userId);
return UserDashboardVO.builder()
.totalBalance(user.getTotalBalance())
.build();
}
private void addMembersToGroup(List<String> memberIds, Group group) {
memberIds.forEach(memberId-> userDao.addUserToGroup(memberId,group));
}
private void updateUserTotalBalance(Bill bill) {
bill.getMemberBillDetails().forEach(billMember-> {
userDao.addToTotalBalance(billMember.getUser().getId(),billMember.getTotalAmountDue());
userDao.addUserBalanceMapping(bill.getPaidBy().getId(),billMember.getUser().getId(),billMember.getTotalAmountDue());
groupDao.addUserGroupBalance(bill.getGroup().getId(),billMember.getUser().getId(),billMember.getTotalAmountDue());
});
}
private Bill convertDTOToEntity(CreateBillDTO createBillDTO) throws Exception {
return Bill.builder()
.id(UUID.randomUUID().toString())
.paidBy(userDao.getUser(createBillDTO.getPaidByUserId()))
.splitMethod(createBillDTO.getSplitMethod())
.status(BillStatus.CREATED)
.group(groupDao.getGroup(createBillDTO.getGroupId()))
.totalAmount(createBillDTO.getTotalAmount())
.memberBillDetails(getBillMemberDetails(createBillDTO.getBillMembers(),createBillDTO.getSplitMethod(), createBillDTO.getTotalAmount()))
.build();
}
private List<MemberBillDetails> getBillMemberDetails(List<BillMemberDetails> billMembers, SplitMethod splitMethod, int totalAmount) throws Exception {
switch (splitMethod) {
case PROPORTIONAL:
int perPersonAmount = totalAmount/(billMembers.size()+1);
int remainingPerPersonAmount = (totalAmount - perPersonAmount)/billMembers.size();
return billMembers.stream().map(billMemberDetails -> MemberBillDetails.builder()
.memberBillStatus(MemberBillStatus.NOT_SETTLED)
.totalAmountDue(remainingPerPersonAmount)
.user(userDao.getUser(billMemberDetails.getUserId())).build()).collect(Collectors.toList());
case NON_PROPORTIONAL:
return billMembers.stream().map(billMemberDetails -> MemberBillDetails.builder()
.memberBillStatus(MemberBillStatus.NOT_SETTLED)
.totalAmountDue(billMemberDetails.getAmountDue())
.user(userDao.getUser(billMemberDetails.getUserId())).build()).collect(Collectors.toList());
}
throw new Exception("Invalid SplitMethod");
}
private Group convertDTOToEntity(CreateGroupDTO createGroupDTO) throws Exception {
validateRequest(createGroupDTO);
List<User> members = createGroupDTO.getMemberIds().stream().map(memberId-> userDao.getUser(memberId)).collect(Collectors.toList());
Group group = Group.builder()
.id(UUID.randomUUID().toString())
.createdBy(userDao.getUser(createGroupDTO.getCreatorId()))
.members(members)
.groupBills(new ArrayList<>())
.userGroupBalance(new HashMap<>())
.build();
return group;
}
private void validateRequest(CreateGroupDTO createGroupDTO) throws Exception {
if(Objects.isNull(userDao.getUser(createGroupDTO.getCreatorId()))){
throw new Exception("Invalid User");
}
if(createGroupDTO.getMemberIds().isEmpty()){
throw new Exception("Invalid number of members");
}
}
public static void main(String[] args) throws Exception {
BillSharingService billSharingService = new BillSharingService();
User user1 = new User();
user1.setId(UUID.randomUUID().toString());
user1.setName("Diwakar Bhatt");
User user2 = new User();
user2.setId(UUID.randomUUID().toString());
user2.setName("Akash");
User user3 = new User();
user3.setId(UUID.randomUUID().toString());
user3.setName("Nishant");
System.out.println(billSharingService.userDao.createUser(user1));
System.out.println(billSharingService.userDao.createUser(user2));
System.out.println(billSharingService.userDao.createUser(user3));
CreateGroupDTO createGroupDTO = CreateGroupDTO.builder()
.creatorId(user1.getId())
.memberIds(Arrays.asList(user2.getId(),user3.getId()))
.name("Random Group")
.build();
CreateGroupVO createGroupVO = billSharingService.createGroup(createGroupDTO);
System.out.println(createGroupVO);
CreateBillDTO createBillDTO = CreateBillDTO.builder()
.groupId(createGroupVO.getGroupId())
.totalAmount(1500)
.splitMethod(SplitMethod.PROPORTIONAL)
.paidByUserId(user1.getId())
.billMembers(Arrays.asList(BillMemberDetails.builder().userId(user3.getId()).build()))
.build();
CreateBillVO createBillVO = billSharingService.createBill(createBillDTO);
System.out.println(createBillVO);
}
}
|
C++ | UTF-8 | 380 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int n, m;
int a = 1000, b = 1000;
int main() {
cin >> n >> m;
for(int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
a = min(x, a);
b = min(y, b);
}
if(a > (6 * b)) {
a = 6 * b;
}
if((n % 6) * b > a) {
cout << ((n / 6) * a) + a << endl;
}
else {
cout << ((n / 6) * a) + ((n % 6) * b) << endl;
}
} |
Java | UTF-8 | 1,352 | 3.234375 | 3 | [] | no_license | package Przyklad2_JDBC;
import java.sql.*;
public class Person {
public Person(String imie, String nazwisko, String pesel, int wiek,
Date dataZapisu) {
super();
this.imie = imie;
this.nazwisko = nazwisko;
this.pesel = pesel;
this.wiek = wiek;
this.dataZapisu = dataZapisu;
}
private String imie;
private String nazwisko;
private String pesel;
private int wiek;
private Date dataZapisu;
public String getImie() {
return imie;
}
public String getNazwisko() {
return nazwisko;
}
public String getPesel() {
return pesel;
}
public int getWiek() {
return wiek;
}
public Date getDataZapisu() {
return dataZapisu;
}
public String toString() {
return "Person [imie=" + imie + ", nazwisko=" + nazwisko + ", pesel="
+ pesel + ", wiek=" + wiek + ", dataZapisu=" + dataZapisu + "]";
}
public static int addPerson(Connection con, Person p) throws SQLException {
PreparedStatement ps = null;
try{
ps = con.prepareStatement("INSERT INTO PERSONS (PESEL, IMIE, NAZWISKO, WIEK, DATA_ZAPISU) VALUES (?,?,?,?,?)");
ps.setString(1, p.getPesel());
ps.setString(2, p.getImie());
ps.setString(3, p.getNazwisko());
ps.setInt(4, p.getWiek());
ps.setDate(5, p.getDataZapisu());
return ps.executeUpdate();
} finally
{
if (ps != null)
ps.close();
}
}
}
|
Java | UTF-8 | 3,103 | 3.265625 | 3 | [] | no_license | package com.company;
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import static com.company.IOModule.teacherList;
public class Teacher {
String number;
String name;
String academy;
String major;
Course[] courses = new Course[5]; //Default length of score array is 5.
int courseNumber = 0;
File outputFile = new File("D://teacherOutput.txt");
static File inputFile = new File("D://teacherInput.txt");
Teacher(String number, String name, String academy, String major){
this.number = number;
this.name = name;
this.academy = academy;
this.major = major;
}
void setTeacher(String number, String name, String academy, String major){
this.number = number;
this.name = name;
this.academy = academy;
this.major = major;
}
@Override
public String toString(){
return String.format("teacher number: %s\n" +
"name: %s\n" + "academy: %s\n" + "major: %s\n"
, number, name, academy, major);
}
//Using multi output stream to make operate easily as soon as fast.
public void save(){
try(BufferedWriter output = new BufferedWriter(new FileWriter(outputFile, true))){
output.write(number);
output.write(name);
output.write(academy);
output.write(major);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void load() throws EOFException {
Teacher teacher = null;
try(BufferedReader input = new BufferedReader(new FileReader(inputFile))) {
String teacherInformation = null;
while ((teacherInformation = input.readLine()) != null) {
String[] splited = teacherInformation.split(" ");
teacher = new Teacher(splited[0], splited[1], splited[2], splited[3]);
teacherList.add(teacher);
}
} catch (IOException e) {
e.printStackTrace();
}
}
//Need to be finished...
public void teacherInquire(){
if(courses[0] == null)
System.out.println("You didn't have any course yet...\n");
else
System.out.println("Here are your courses information: ");
com.company.PrintModule.print(courses);
}
public void addCourse(){
Scanner scanner = new Scanner(System.in);
System.out.println("Please input course's number, name, credit and period.");
Course course = new Course(scanner.next(), scanner.next(), Integer.parseInt(scanner.next()), Integer.parseInt(scanner.next()));
//If there is no more space for adding a new course, double the length of studentCourse.
if(courses.length == this.courseNumber){
courses = Arrays.copyOf(courses, courses.length*2);
}
courses[courseNumber] = course;
courseNumber++;
System.out.println("Add successfully.\n");
}
}
|
C | UTF-8 | 1,109 | 3.703125 | 4 | [] | no_license | #include <stdio.h>
#include <math.h>
#define PI 3.1415
// Check for built in C99 stuff instead of this struct
typedef struct ComplexNum
{
double real;
double imag;
} ComplexNum;
void dft(ComplexNum* in, ComplexNum* out, int insize, int outsize)
{
int i;
for (i = 0; i < outsize; i++)
{
ComplexNum sum;
sum.real = 0;
sum.imag = 0;
int t;
for (t = 0; t < insize; t++)
{
double angle = 2 * PI * t * i / insize;
sum.real += in[t].real * cos(angle) + in[t].imag * sin(angle);
sum.imag += -in[t].real * sin(angle) + in[t].imag * cos(angle);
}
out[i].real = sum.real;
out[i].imag = sum.imag;
}
}
int main(int args, char** argv)
{
ComplexNum input[] = {
{.real = 1},
{.real = 0},
{.real = -1},
{.real = 0}
};
ComplexNum output[12];
dft(input, output, 4, 12);
int i;
for (i = 0; i < 12; i++)
printf("%.3lf\n", sqrt(output[i].real*output[i].real + output[i].imag*output[i].imag));
return 0;
}
|
Java | UTF-8 | 950 | 2.359375 | 2 | [] | no_license | package com.simoncherry.cookbook.mvp.presenter;
import com.simoncherry.cookbook.ui.BaseView;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
/**
* Created by Simon on 2017/4/23.
*/
public class RxPresenter<T extends BaseView> implements BasePresenter<T> {
protected T mView;
protected CompositeDisposable mCompositeDisposable;
protected void addSubscribe(Disposable subscription) {
if (mCompositeDisposable == null) {
mCompositeDisposable = new CompositeDisposable();
}
mCompositeDisposable.add(subscription);
}
protected void unSubscribe() {
if (mCompositeDisposable != null) {
mCompositeDisposable.dispose();
}
}
@Override
public void attachView(T view) {
this.mView = view;
}
@Override
public void detachView() {
this.mView = null;
unSubscribe();
}
}
|
Markdown | UTF-8 | 4,951 | 2.6875 | 3 | [
"MIT"
] | permissive | ---
type: scenario
acronym: pschmitz
title: Aufgabe zu DevOps
persona: pschmitz
scenarioTypes:
- main
- alternative
- negative
responsible:
- jlü
source:
- [interview, nnProf3]
history:
v1:
date: 2021-06-17
comment: initially created
v2:
date: 2021-07-12
comment: Hinzufügen von Szenarien
v3:
date: 2021-07-23
comment: refactor regarding the issues from the review
v4:
date: 2021-07-28
comment: rework scenarios addressing given todos
todo:
---
### Hauptszenario
Das Semester neigt sich dem Ende zu und die Klausuren stehen an. Aufgrund von Online Klausuren befürchtet Paul, dass die
Studierenden die Klausuraufgaben nicht selbstständig lösen. In der Vergangenheit hat er die Erfahrung gemacht, dass gerade die
Betrugsprävention bei Online-Klausuren sehr schwierig ist. Er sucht nun eine Möglichkeit, Klausuren zu individualisieren, um
diesem Problem vorzubeugen.
Die Klausur dreht sich um die Erstellung eines Docker-Containers und dem anschließend automatischen Deployment
in eine Cloudlösung. Während der Klausur sollen die Studierenden einen Docker Container erstellen und zum Laufen bringen.
Nach dem erfolgreichen Erstellen der Docker Container, werden die Images der Student*innen auf Github gepushed und alle automatisiert ausgeführt.
Einige vordefinierten Tests, welche den Zustand des Docker Containers überprüfen, liefern Paul bereits kurz nach der Klausur einen
guten Überblick über die Leistungen der Student*innen, sodass er bereits kurz nach der Klausur zufrieden sein kann, dass viele Student*innen
gut abgeschnitten haben.
Eine Woche nach der Klausur pulled Paul alle eingereichten Klausurlösungen und überprüft diese manuell, da er sicher gehen will, dass eine
faire Notenbewertung zu stande kommt. Sein erster positiver Eindruck der eingereichten Lösungen bestätigt sich.
Paul möchte aufgrund der positiven Erfahrungen in Zukunft weiter auf das DiveKit zur Stellung von DevOps bezogenen Klausuraufgaben setzten und denkt darüber nach
nicht nur die Erstellung von Docker Containern mithilfe des DiveKits in Klausuren zu prüfen.
### Alternativszenario
Paul möchte, dass die Studierenden in den Übungen möglichst viel lernen. Allerdings hat er in der
Vergangenheit oft die Erfahrung gemacht, dass einige Studierende die Lösung abschreiben und so schlecht für die Klausuren
vorbereitet sind. Der Fokus der Aufgaben liegt dabei in der Erstellung eines Google Cloud Clusters. Konkret soll jede*r
Student*in ein eigenes Cluster aufsetzten und dabei individuelle Aspekte berücksichtigen.
Um Paul die Arbeit zu erleichtern, setzt er auf das DiveKit zur Erstellung, Individualisierung und der vollständig automatisierten Auswertung
der Übungsaufgaben.
Während der Übung erstellen alle Student*innen ihre Cluster und pushen die dazugehörigen Dateien in ihr individuelles Repository.
Nach kurzer Zeit erhalten die Student*innen einen guten Überblick über ihren aktuellen Lernstatus.
Da dies nur eine unbenotete Übung ist, verzichtet Paul explizit auf eine manuelle Überprüfung der eingereichten Lösungen, sondern nutzt
lediglich vordefinierte Tests, welche den Zustand des Google Cloud Clusters auf Vollständigkeit und Korrektheit validieren.
Neben den Übungsaufgaben bietet Paul seinen Student*innen an, das DiveKit und die damit erstellten Aufgaben zur individuellen
Prüfungsvorbereitung zu nutzen. Die Aufgaben werden nach dem Push in das DiveKit Repository automatisch mit den vorgegebenen Tests validiert
und anschließend automatisch auf eine zentrale Google Cloud der Hochschule deployt, sodass sich die Studierenden andere Lösungen anschauen können.
Paul hat in diesem Jahr besonders gute Klausurergebnisse nach der praxisnahen Vorbereitung erhalten und auch das Feedback der Student*innen
ist sehr positiv ausgefallen.
Paul möchte auch in Zukunft auf das DiveKit setzten und seine bereits umgesetzten Aufgaben zu DevOps ausbauen.
### Negativszenario
Die Student*innen arbeiten mitten in der Klausur an ihrer Aufgabe zum Aufsetzen eines Google Cloud Clusters. Neben dem Deployment einer kleinen Anwendung, sollen die Student*innen
eine Datenbank anbinden.
Nach der Hälfte der Zeit läuft die Lizenz der Hochschule für das Google Cloud System aus und alle Student*innen können an den
Aufgaben nicht mehr weiterarbeiten.
Eine kurzfristige Erneuerung der Lizenz ist nicht möglich, sodass die Klausur für alle Teilnehmer*innen abgebrochen werden muss und
zu einem neuen Termin erneut durchgeführt werden muss.
Leider sind aufgrund dieses Vorfalls einige Student*innen verängstigt, dass ähnliche Vorfälle nochmals vorkommen können und
das Vertrauen in das DiveKit sinkt. Einige Dozent*innen ziehen zudem nun in Betracht ihre Klausuren wieder auf eine klassische Klausur umzustellen und abstand
vom Gebrauch des DiveKits zu nehmen.
|
C# | UTF-8 | 2,505 | 2.890625 | 3 | [] | no_license | using Library.Entities;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library.DataAccess
{
public class MemberBookListDAL
{
DbHelper helper;
public MemberBookListDAL()
{
helper = new DbHelper();
}
public int Insert(MemberBookList bookList)
{
helper.CommandText = "insert into MemberBookList (BookID,MemberID) values(@bookID,@memberID)";
helper.Parameters.Clear();
helper.Parameters.Add("@bookID", bookList.BookID);
helper.Parameters.Add("@memberID", bookList.MemberID);
return helper.ExecuteQuery();
}
public int Delete(int listID)
{
helper.CommandText = "DELETE FROM MemberBookList WHERE ListID=@listID";
helper.Parameters.Clear();
helper.Parameters.Add("@listID", listID);
return helper.ExecuteQuery();
}
public List<MemberBookList> MemberBookList(int memberID)
{
helper.CommandText = @"select b.BookName
from MemberBookList mbl
join Books b
on b.BookID = mbl.BookID
join Members m
on m.MemberID = mbl.MemberID
where mbl.MemberID = @memberID";
helper.Parameters.Clear();
helper.Parameters.Add("@memberID", memberID);
List<MemberBookList> books = new List<MemberBookList>();
MemberBookList bookList = null;
SqlDataReader reader = helper.GetEntity();
while (reader.Read())
{
bookList = MapBook(reader);
books.Add(bookList);
}
reader.Close();
return books;
}
private MemberBookList MapBook(SqlDataReader reader) // book özelliklerini okurken kullanılan metot
{
MemberBookList booklist = new MemberBookList();
//booklist.ListID = (int)reader["ListID"];
//booklist.BookID = (int)reader["BookID"];
//booklist.MemberID = (int)reader["MemberID"];
booklist.book = new Book() { BookID = booklist.BookID, BookName = reader["BookName"].ToString() };
return booklist;
}
}
}
|
C++ | UTF-8 | 1,927 | 3.625 | 4 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
template<typename T>
struct Node
{
int info;
Node *right;
Node *left;
};
template <typename T>
class Create
{
protected:
Node<T> *first,*last;
public:
Create()
{
first=NULL;
last=NULL;
}
template <typename S>
friend ostream& operator << (ostream &myout,Create<S> main)
{ Node<T> *curse=main.first;
while(curse)
{
cout<<curse->info<<" ";
curse=curse->right;
}
return myout;
}
void addfront(int num)
{
Node<T> *temp ;
temp = new Node<T>;
temp->info=num;
temp->left=NULL;
temp->right=first;
if(first==NULL)
{
last=temp;
}
else
{
first->left=temp;
}
first=temp;
}
void addbefore(int num, Node<T> *x)
{
Node<T> *temp;
temp=new Node<T>;
temp->info=num;
temp->right=x;
temp->left=x->left;
if(x->left==NULL)
{
first=temp;
}
}
void addafter(int num, Node<T> *x)
{
Node<T> *temp;
temp=new Node<T>;
temp->info=num;
temp->left=x;
temp->right=x->right;
x->right=temp;
if(x->right==NULL)
{
last=temp;
}
}
void addend(int num)
{
Node<T> *temp;
temp=new Node<T>;
temp->info=num;
temp->right=NULL;
temp->left=last;
if(last==NULL)
{
first=temp;
}
else
{
last->right=temp;
}
last=temp;
}
void deletenode(Node<T> *x)
{
if(x->left==NULL)
{
first=x->right;
first->left=NULL;
}
else if(x->right==NULL)
{
last=x->left;
last->right=NULL;
}
delete(x);
}
void forward_traverse()
{
Node<T> *trav;
trav = first;
while(trav != NULL)
{
cout<<trav->info<<endl;
trav = trav->right;
}
}
void backward_traverse()
{
Node<T> *trav;
trav = first;
while(trav != NULL)
{
cout<<trav->info<<endl;
trav = trav->left;
}
}
};
int main()
{
Create<int> B;
int num;
cout<<"Enter a number ending with -99"<<endl;
cin>>num;
while(num!=-99)
{
Node<int> *x1;
x1= new Node<int>;
B.addafter(num,x1);
cin>>num;
}
cout<<B;
return 0;
}
|
Python | UTF-8 | 2,949 | 3.125 | 3 | [] | no_license | import sys
sys.path.append('../')
from lstore.query import *
from lstore.table import *
from lstore.db import *
database = Database()
database.create_table("Students", 6, 0)
table = database.get_table("Students")
query = Query(table)
def test(test_name, expression, expected_result):
print('\n\n++++TEST RESULT++++')
if expression != expected_result :
print(f'\n!!!!\n{test_name}:FAILED\n\texpected:{expected_result}\n\treceived:{expression}\n!!!!\n')
else:
print(f'{test_name} SUCCESSFUL')
print('++++END RESULT++++\n\n')
# insert a row to test select with
query.insert(*[1,2,3,4,5,6])
# attempt to insert a record with a duplicate key
# this appears to fail quietly, because the first test passes
query.insert(*[1,12,13,14,15,16])
# find the record we inserted with a key of 1
ret_record = query.select(1,0,[1, 1, 1, 1, 1, 1])
test('find record we inserted with a key of 1',
ret_record[0].user_data,
[1, 2, 3, 4, 5, 6])
ret_record = query.select(1,0,[0, 1, 0, 1, 0, 1])
test('find specific columns of record with key 1',
ret_record[0].user_data,
[None, 2, None, 4, None, 6])
test('try to find record we did not insert',
query.select(99999,0,[1,1,1,1,1,1]),
False)
# attempt to insert a record with a negative number
query.insert(*[2,-22,-23,-24,-25,-26])
ret_record = query.select(2,0,[1, 1, 1, 1, 1, 1])
test('stops us from inserting negative numbers',ret_record,False)
# attempt to insert a ridiculously massive number
query.insert(*[3,696969696969696969696969420,32,33,34,35])
ret_record = query.select(3,0,[1, 1, 1, 1, 1, 1])
test('stops us from inserting massive numbers',ret_record,False)
# update a record, see if the update has flushed
query.update(1,*[None, 69, None, None, None, None])
ret_record = query.select(1,0,[1, 1, 1, 1, 1, 1])
test('try to find record 1 after its been updated',
ret_record[0].user_data,
[1, 69, 3, 4, 5, 6])
query.update(1,*[None, None, 69, None, None, None])
ret_record = query.select(1,0,[1, 1, 1, 1, 1, 1])
test('try to find record 1 after its been updated a second time',
ret_record[0].user_data,
[1, 69, 69, 4, 5, 6])
query.update(1,*[None, None, None, 69, None, None])
ret_record = query.select(1,0,[1, 1, 1, 1, 1, 1])
test('try to find record 1 after its been updated a third time',
ret_record[0].user_data,
[1, 69, 69, 69, 5, 6])
query.insert(*[2,2,3,4,5,6])
query.insert(*[3,2,3,4,5,6])
query.insert(*[4,2,3,4,5,6])
test('test sum',query.sum(1,4,0),10)
'''
THESE TESTS FAIL
'''
query.insert(*[5,2,3,4,5,6])
# this updates the key of a record
did_update = query.update(5,*[69, None, None, None, None, None])
ret_record = query.select(5,0,[1, 1, 1, 1, 1, 1])
test('check that record 5 did not successfully update the primary key',
did_update,
False)
ret_record = query.select(69,0,[1, 1, 1, 1, 1, 1])
test('try to find record 69 which should not exist if update failed',
ret_record,
False)
|
Java | UTF-8 | 1,478 | 2.15625 | 2 | [] | no_license | package invenio.wf.items.vis.query;
import invenio.visual.LabelRenderer;
import invenio.visual.VisualGraphSession;
import prefuse.action.assignment.ColorAction;
import prefuse.util.ColorLib;
import prefuse.visual.VisualItem;
public class QueryGraphSession extends VisualGraphSession {
// color
private ColorAction stroke = new ColorAction("graph.nodes", VisualItem.STROKECOLOR, ColorLib.gray(200));
private TempBehaviorColorAction fill = new TempBehaviorColorAction("graph.nodes", VisualItem.FILLCOLOR);
private ColorAction text = new ColorAction("graph.nodes", VisualItem.TEXTCOLOR, ColorLib.gray(0));
private ColorAction edges = new ColorAction("graph.edges", VisualItem.STROKECOLOR, ColorLib.gray(200));
public QueryGraphSession() {
// setLayoutManager(new ClusterLayoutManager());
// LabelRenderer r = new invenio.visual.LabelRenderer("id");
// prefuse.render.LabelRenderer r = new prefuse.render.LabelRenderer("jung.io.PajekNetReader.LABEL");
LabelRenderer r = new LabelRenderer("id");
r.setRoundedCorner(8, 8); // round the corners
setRenderer( r );
}
protected void resetPainterToDefault(){
// create an action list containing all color assignments
painter.putAction("stroke", stroke);
painter.putAction("fill", fill);
painter.putAction("text", text);
painter.putAction("edges", edges);
// painter.putAction("enlarge", new SizeAction("graph.nodes", 3));
}
}
|
Java | UTF-8 | 473 | 2.0625 | 2 | [] | no_license | package br.com.customerapi.customer.dto;
import br.com.customerapi.customer.predicate.CustomerPredicate;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class CustomerFilters {
private Integer id;
private String name;
private String document;
public CustomerPredicate toPredicate() {
return new CustomerPredicate()
.withId(id)
.withName(name)
.withDocument(document);
}
}
|
TypeScript | UTF-8 | 7,399 | 2.671875 | 3 | [
"MIT",
"CC-BY-4.0"
] | permissive | import path from "path";
import slug from "slug";
import { Octokit } from "@octokit/rest"
import { createKoreFile, createGitHubAdaptor, KoreFile } from "korefile"
const normalizeNewLine = (input: string): string => {
return input.replace(/\r\n/g, '\n');
};
const slugTitle = (title: string) => {
const tenTitle = title.replace(/、/g, "-");
return slug(tenTitle, {
remove: null,
lower: true
});
};
interface EmbedHeadlineParams {
content: string;
headline?: string;
}
const embedHeadline = ({ content, headline }: EmbedHeadlineParams): string => {
if (!headline) {
console.log("headline is not defined");
return content;
}
console.log("# headline")
console.log(headline);
console.log("# content")
console.log(content);
const replacedContent = content.replace(/---\s+JSer\.info #(\d+)[\s\S]*?----\s+<h1/, `---
JSer.info #$1 - ${headline}
----
{% include inline-support.html %}
----
<h1`);
console.log("# replaced");
console.log(replacedContent);
return normalizeNewLine(replacedContent);
}
/**
*
* @param {*} robot
* @param koreFile
* @param {string} owner
* @param {string} repo
* @param {string} branch
* @returns {Promise<void>}
*
* https://medium.com/@obodley/renaming-a-file-using-the-git-api-fed1e6f04188
* http://www.levibotelho.com/development/commit-a-file-with-the-github-api/
*/
const renameCommit = async (koreFile: KoreFile, { originalFileName, renameFn }: {
originalFileName: string,
renameFn: (oldFileName: string, content: string) => { newFileName: string, newContent: string }
}) => {
console.log("start rename(delete and create)", originalFileName);
// get content
// http://octokit.github.io/rest.js/#api-Repos-getContent
const originalContent = await koreFile.readFile(originalFileName);
const { newFileName, newContent } = renameFn(originalFileName, originalContent);
if (originalFileName === newFileName && originalContent === newContent) {
console.log(`No need to commit: ${originalFileName}`);
return;
}
if (originalFileName === newFileName) {
console.log("Update Content");
// Update Content
// https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#create-or-update-file-contents
await koreFile.writeFile(originalFileName, newContent);
console.log("Updated ", originalFileName)
} else {
console.log(`Rename: ${originalFileName} -> ${newFileName}`);
// update file
// https://docs.github.com/en/free-pro-team@latest/rest/reference/repos#create-or-update-file-contents
await koreFile.writeFile(newFileName, newContent);
console.log("Create", newContent);
// remove original file
await koreFile.deleteFile(originalFileName);
console.log("Delete", originalFileName);
}
return {
status: "ok"
};
};
const RENAME_TARGET = /(_i18n\/ja\/_posts\/\d+)\/(.*?\.md$)/;
const canRename = (originalFilePath: string) => {
return RENAME_TARGET.test(originalFilePath);
};
/**
* PR title -> content:title
* replace content:title to newTitle
* @returns {*}
*/
const replaceContentTitle = (content: string, newTitle: string) => {
const titlePattern = /title: "(\d{4})-(\d{2})-(\d{2})のJS:(.*)"/;
if (!titlePattern.test(content)) {
return content;
}
return content.replace(titlePattern, `title: "${newTitle}"`);
};
/**
* PR title -> file newm
* @returns {*}
*/
const renameFilePathWithNewTitle = (originalFilePath: string, newTitle: string) => {
if (!RENAME_TARGET.test(originalFilePath)) {
return originalFilePath;
}
const titlePattern = /^(\d{4})-(\d{2})-(\d{2})のJS:(.*)/;
if (!titlePattern.test(newTitle)) {
return originalFilePath;
}
// @ts-ignore
const [_, year, month, day, keyword] = newTitle.match(titlePattern);
const trimmedKeyword = keyword.trim();
// Title is empty
if (trimmedKeyword.length === 0) {
return originalFilePath;
}
const newSlug = slugTitle(trimmedKeyword);
const ext = path.extname(originalFilePath);
return originalFilePath.replace(RENAME_TARGET, (_all, pathname) => {
return `${pathname}/${year}-${month}-${day}-${newSlug}${ext}`;
});
};
/**
* title: ** -> file name
* content's title to file name
* @param originalFilePath
* @param content https://developer.github.com/v3/repos/contents/#get-contents
* @returns {*}
*/
const renamePattern = (originalFilePath: string, content: string) => {
if (!RENAME_TARGET.test(originalFilePath)) {
return originalFilePath;
}
const titlePattern = /title: "(\d{4})-(\d{2})-(\d{2})のJS:(.*)"/;
if (!titlePattern.test(content)) {
return originalFilePath;
}
// @ts-ignore
const [_, year, month, day, keyword] = content.match(titlePattern);
const trimmedKeyword = keyword.trim();
// Title is empty
if (trimmedKeyword.length === 0) {
return originalFilePath;
}
const newSlug = slugTitle(trimmedKeyword);
const ext = path.extname(originalFilePath);
return originalFilePath.replace(RENAME_TARGET, (_all, pathname) => {
return `${pathname}/${year}-${month}-${day}-${newSlug}${ext}`;
});
};
export const rename = async (payload: {
owner: string;
repo: string;
// if exits, title based rename
forceFitToTitle?: string
// headline from body
headline?: string;
head: {
ref: string;
sha: string;
}
base: {
ref: string;
sha: string
},
GITHUB_TOKEN: string
}) => {
const koreFile = createKoreFile({
adaptor: createGitHubAdaptor({
owner: payload.owner,
repo: payload.repo,
ref: `heads/${payload.head.ref}`,
token: payload.GITHUB_TOKEN
})
});
const octokit = new Octokit({
auth: payload.GITHUB_TOKEN
});
const newTitle = payload.forceFitToTitle;
const compare = await octokit.repos.compareCommits(
{
owner: payload.owner,
repo: payload.repo,
base: payload.base.sha,
head: payload.head.sha
}
);
const promises = compare.data.files
.filter(file => {
return file.status === "added" || file.status === "modified";
})
.filter(file => {
const originalFileName = file.filename;
return canRename(originalFileName);
})
.map(file => {
return renameCommit(koreFile, {
originalFileName: file.filename,
renameFn: (fileName, content) => {
// Update Pull Request title
// if newTitle exists, replace fileName and content:title with newTitle
const newContent = newTitle
? replaceContentTitle(content, newTitle)
: content;
return {
newFileName: newTitle
? renameFilePathWithNewTitle(fileName, newTitle)
: renamePattern(fileName, content),
newContent: embedHeadline({ content: newContent, headline: payload.headline })
};
}
});
});
return Promise.all(promises);
};
|
PHP | UTF-8 | 656 | 2.515625 | 3 | [] | no_license | <?php
$quanLiDanhSachSV = array(
array(
'tensanpham' => 'kem',
'ngayban' => '20/4/2018',
'giaban' => '5,000',
),
array(
'tensanpham' => 'kem',
'ngayban' => '20/4/2018',
'giaban' => '5,000',
),
array(
'tensanpham' => 'kem',
'ngayban' => '20/4/2018',
'giaban' => '5,000',
),
);
echo '<ul>';
foreach($quanLiDanhSachSV as $key1 =>$a){
echo '<li>';
echo 'Tên sản phẩm : '.$a['tensanpham'].'<br/>';
echo 'Ngày bán : '.$a['ngayban'].'<br/>';
echo 'Giá bán : '.$a['giaban'].'<br/>';
echo '</li>';
}
echo '</ul>';
?>
|
Python | UTF-8 | 462 | 3.296875 | 3 | [] | no_license | import os
import glob
os.chdir('c:/webDev/pyworks') # webDev 폴더로 이동
dir = os.popen('dir') # 'dir' 명령 실행
#print(dir.read())
#glob 모듈로 file_io의 파일 이름 알아내기 - txt파일 읽어오기
data=glob.glob('c:/webDev/pyworks/day28/file_io/*.txt')
print(data) #리스트 형태로 반환
#animal.txt 읽기
with open('c:/webDev/pyworks/day28/file_io/animal.txt','r') as content:
date = content.read()
print(date) |
Python | UTF-8 | 3,495 | 3.546875 | 4 | [] | no_license | # This creates an interactive GUI for users to play with images and parameters for K-means.
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from kmeans import *
from GMM import *
class App:
def __init__(self, master):
# Create container
frame = Frame(master)
# Create buttons
self.method = Button(frame, text="K-means/GMM", command=self.method_change)
self.method.pack(side="left")
self.dataset = Button(frame, text="Change Dataset", command=self.dataset_change)
self.dataset.pack(side="left")
self.k_value = Button(frame, text="Increase K", command=self.k_increase)
self.k_value.pack(side="left")
self.k_value = Button(frame, text="Decrease K", command=self.k_decrease)
self.k_value.pack(side="left")
self.images = ['data/Bird.png', 'data/Landscape.png', 'data/City.png']
self.dataset_index = 0
self.image = self.images[self.dataset_index]
self.K = 1
self.method_name = 'kmeans'
self.fig = Figure(figsize=(15, 6))
self.ax1 = self.fig.add_subplot(121)
self.ax2 = self.fig.add_subplot(122)
self.draw()
self.canvas = FigureCanvasTkAgg(self.fig, master=master)
self.canvas.show()
self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
frame.pack()
def method_change(self):
self.n = 1
self.K = 1
if self.method_name == 'kmeans':
self.method_name = 'gmm'
else:
self.method_name = 'kmeans'
self.draw()
self.canvas.draw()
def dataset_change(self):
self.K = 1
self.dataset_index = (self.dataset_index + 1) % 3
self.image = self.images[self.dataset_index]
self.draw()
self.canvas.draw()
def k_increase(self):
self.K += 1
self.draw()
self.canvas.draw()
def k_decrease(self):
if self.K >= 2:
self.K -= 1
self.draw()
self.canvas.draw()
def draw(self):
if self.method_name == 'kmeans':
self.ax1.cla()
self.ax2.cla()
image_values = image_to_matrix(self.image)
new_image = k_means_segment(image_values, k=self.K)
self.ax1.set_title('Segmented Image with %d K-means Clusters' % self.K)
self.ax2.set_title('Original Image')
self.ax1.imshow(new_image)
self.ax2.imshow(image_values)
else:
self.ax1.cla()
self.ax2.cla()
original_image_matrix = image_to_matrix(self.image) # Save original image
image_matrix = original_image_matrix.reshape(-1, 3) # collapse the dimension
_, best_seg = best_segment(image_matrix, self.K, iters=10)
new_image = best_seg.reshape(*original_image_matrix.shape) # reshape collapsed matrix to original size
# Show the image
self.ax1.set_title('Segmented Image with %d GMM Clusters' % self.K)
self.ax2.set_title('Original Image')
self.ax1.imshow(new_image)
self.ax2.imshow(original_image_matrix)
def main():
root = Tk()
app = App(root)
root.title("K-means and GMM on image clustering")
root.mainloop()
if __name__ == '__main__':
main()
|
Shell | UTF-8 | 1,357 | 3.71875 | 4 | [
"GPL-1.0-or-later",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #!/bin/bash
#
# /etc/rc.d/init.d/calico-felix
#
# chkconfig: 2345 08 92
# description: Starts and stops calico-felix
#
### BEGIN INIT INFO
# Provides: calico-felix
# Required-Start:
# Required-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop calico-felix
# Description: start and stop calico-felix
### END INIT INFO
# Source function library.
. /etc/init.d/functions
DAEMON=/usr/bin/calico-felix
PIDFILE=/var/run/calico/calico-felix.pid
start() {
echo -n "Starting calico-felix: "
mkdir -p /var/run/calico
daemon --pidfile=$PIDFILE " { $DAEMON > /dev/null 2>&1 & } ; echo \$! >| $PIDFILE "
retval=$?
touch /var/lock/subsys/calico-felix
return $retval
}
stop() {
echo -n "Shutting down calico-felix: "
killproc -p $PIDFILE $NAME
rm -f /var/lock/subsys/calico-felix
return $retval
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status -p $PIDFILE $NAME
;;
restart)
stop
start
;;
reload)
kill -HUP $PIDFILE
;;
condrestart)
[ -f /var/lock/subsys/calico-felix ] && restart || :
;;
*)
echo "Usage: calico-felix {start|stop|status|reload|restart}"
exit 1
;;
esac
exit $?
|
Java | UTF-8 | 1,157 | 2.4375 | 2 | [
"MIT"
] | permissive | package startup;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.AgentController;
import jade.wrapper.ContainerController;
public class Launcher {
Runtime rt;
ContainerController container;
public void initRemoteContainer(String host, String port){
System.out.println("Connecting to Remote JADE platform...");
this.rt = Runtime.instance();
Profile prof = new ProfileImpl();
prof.setParameter(Profile.MAIN_HOST, host);
prof.setParameter(Profile.MAIN_PORT, port);
prof.setParameter(Profile.MAIN, "false");
this.container = rt.createAgentContainer(prof);
rt.setCloseVM(true);
}
public void startAgentInPlatform(String name, String classpath){
try {
AgentController ac = container.createNewAgent(name, classpath, new Object[0]);
ac.start();
} catch (Exception e) {
e.printStackTrace();
}
}
// Launch Remote connections
public static void main(String args[]) {
Launcher mc = new Launcher();
mc.initRemoteContainer( "192.168.1.21", "1099");
mc.startAgentInPlatform("SensorName", "agents.IslabSound");
}
}
|
Markdown | UTF-8 | 1,871 | 2.796875 | 3 | [] | no_license | ## ERR_CONTENT_LENGTH_MISMATCH解决方法
### 问题描述
前端页面加载css,和js文件的时候,经常出现`ERR_CONTENT_LENGTH_MISMATCH`的报错情况。
### 定位问题
在单独打开`hearder`中css,js的网络地址是能打开的,所以排除了最简单的地址错误。前端项目是由nginx代理的,所以可以查看nginx的日志,看看有无线索。
进入`${NGINX_HOME}\logs`,查看`error.log`,得到如下信息:
```shell
2018/07/13 14:22:49 [crit] 275197#0: *1543 open() "/usr/local/nginx/proxy_temp/4/30/0000000304" failed (13: Permission denied) while reading upstream, client: 192.168.75.11, server: xxxx.xxxx.com, request: "GET /model-web/static/js/vendor.7e49e6e8578e1e242c55.js.map HTTP/1.1", upstream: "http://xxx.xxx.xxx:8080/model-web/static/js/vendor.7e49e6e8578e1e242c55.js", host: "xxx.xxx.xxx.xxx:8081"
```
线索很明显,在请求`vendor.7e49e6e8578e1e242c55.js`的时候,nginx在尝试访问`/usr/local/nginx/proxy_temp/4/30/0000000304`,结果因为没有权限,导致了请求失败。
那么,为什么nginx要访问`proxy_temp`文件夹呢,因为`proxy_temp`是nginx的缓存文件夹,我的css和js文件过大了,所以nginx一般会从缓存里面去拿,而不是每次都去原地址直接加载。
### 分析原因
1. 进入`/usr/local/nginx/proxy_temp`,查看文件权限。拥有者为root
2. 查看现在nginx的使用者,发现是nginx
3. 那么,导致没有权限的原因也查清了,就是文件的所有者和访问者不是同一用户
### 解决办法
1. 改变文件夹所有者,把文件夹及文件夹下所有文件的所有者改为当前nginx的使用者,`chown -R root:root ./*`。
2. 增加权限,给其他用户增加可读权限。
3. 修改nginx配置文件,声明使用者(推荐)。
4. 重启nginx,`./nginx -s reload`,问题解决 |
Java | UTF-8 | 24,327 | 1.9375 | 2 | [] | no_license | package com.clean.space;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.clean.space.protocol.ExportedImageItem;
import com.clean.space.protocol.FileItem;
import com.clean.space.protocol.ItemComparator;
import com.clean.space.protocol.SimilarImageItem;
import com.clean.space.statistics.StatisticsUtil;
import com.clean.space.ui.listener.AdapterListener;
import com.clean.space.util.FileUtil;
import com.clean.space.util.FileUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
public class ThumbnailAdapter extends ArrayAdapter<Object> implements
OnScrollListener {
private static final String TAG = ThumbnailAdapter.class.getSimpleName();
public static final int TYPE_CLEAR = 1;
public static final int TYPE_SIMILAR = 2;
public static final int TYPE_ALBUM = 3;
private Context mContext;
private int mResource;
private int mType;
private List<Object> mList;
private Map<String, Boolean> mSelectedMap;
private List<String> mClickedList;
private boolean mIsMultiple;
private int mItemWidth;
private int mItemHeight;
private AdapterListener mListener;
private boolean mIsLongClick;
private static ImageLoader mImageLoader;
private static DisplayImageOptions mOptions;
public ThumbnailAdapter(Context context, int resource, int type) {
super(context, resource);
mContext = context;
mResource = resource;
mType = type;
mList = new ArrayList<Object>();
mSelectedMap = new HashMap<String, Boolean>();
mClickedList = new ArrayList<String>();
mIsMultiple = false;
mIsLongClick = false;
initImageLoader(mContext);
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
public List<Object> getAllItems() {
return new ArrayList<Object>(mList);
}
private class ViewHolder {
ImageView selectMark;
ImageView image;
ImageView image_computer;
ImageView image_yun;
LinearLayout export;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = (View) LayoutInflater.from(mContext).inflate(
mResource, null);
viewHolder = new ViewHolder();
viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
viewHolder.selectMark = (ImageView) convertView
.findViewById(R.id.checkbox);
viewHolder.image_computer = (ImageView) convertView
.findViewById(R.id.export_computer);
viewHolder.image_yun = (ImageView) convertView
.findViewById(R.id.export_yun);
viewHolder.export = (LinearLayout) convertView
.findViewById(R.id.export);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final ImageView image = viewHolder.image;
final ImageView selectMark = viewHolder.selectMark;
final ImageView image_computer = viewHolder.image_computer;
final ImageView image_yun = viewHolder.image_yun;
final LinearLayout export = viewHolder.export;
final LayoutParams params = new LayoutParams(mItemWidth, mItemHeight);
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) {
String path = "";
switch (mType) {
case TYPE_CLEAR: {
ExportedImageItem item = (ExportedImageItem) mList
.get(position);
path = item.getPath();
break;
}
case TYPE_SIMILAR: {
SimilarImageItem item = (SimilarImageItem) mList
.get(position);
path = item.getPath();
break;
}
case TYPE_ALBUM: {
FileItem item = (FileItem) mList.get(position);
path = item.getPath();
break;
}
}
mListener.onItemLongClick(path, position, mType);
// statistics
String eventid = Constants.UMENG.ARRANGE_PHOTO.SHOW_BIG_PICTURE;
StatisticsUtil.getInstance(mContext,
StatisticsUtil.TYPE_UMENG).onEventCount(eventid);
}
// mIsLongClick = true;
// return false;
}
});
switch (mType) {
case TYPE_CLEAR: {
final ExportedImageItem item = (ExportedImageItem) mList
.get(position);
setImageThumbnail(image, item.getPath(), item);
params.setMargins(10, 10, 10, 10);
image.setLayoutParams(params);
export.setVisibility(View.VISIBLE);
if (item.isSaveOneDrive()) {
image_yun.setVisibility(View.VISIBLE);
} else {
image_yun.setVisibility(View.GONE);
}
if (item.isSavePcClient()) {
image_computer.setVisibility(View.VISIBLE);
} else {
image_computer.setVisibility(View.GONE);
}
if (mIsMultiple) {
selectMark.setVisibility(View.VISIBLE);
if (mSelectedMap.get(item.getPath())) {
selectMark
.setBackgroundResource(R.drawable.btn_checked_big);
} else {
selectMark
.setBackgroundResource(R.drawable.btn_checked_big_not);
}
} else {
selectMark
.setBackgroundResource(R.drawable.btn_checked_big_not);
// selectMark.setVisibility(View.GONE);
}
selectMark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (mIsLongClick) {
// mIsLongClick = false;
// return;
// }
setMultipleSelectMode(true);
itemClick(position);
if (mSelectedMap.get(item.getPath())) {
selectMark
.setBackgroundResource(R.drawable.btn_checked_big);
} else {
selectMark
.setBackgroundResource(R.drawable.btn_checked_big_not);
}
}
});
break;
}
case TYPE_SIMILAR: {
selectMark.setVisibility(View.VISIBLE);
final SimilarImageItem item = (SimilarImageItem) mList
.get(position);
setImageThumbnail(image, item.getPath(), item);
params.setMargins(10, 10, 10, 10);
image.setLayoutParams(params);
if (mSelectedMap.get(item.getPath())) {
selectMark.setImageResource(R.drawable.btn_checked_big);
} else {
selectMark
.setBackgroundResource(R.drawable.btn_checked_big_not);
}
selectMark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (mIsLongClick) {
// mIsLongClick = false;
// return;
// }
if (!mSelectedMap.get(item.getPath())) {
selectMark.setImageResource(R.drawable.btn_checked_big);
// selectMark.setVisibility(View.VISIBLE);
} else {
selectMark
.setImageResource(R.drawable.btn_checked_big_not);
// selectMark.setVisibility(View.GONE);
}
itemClick(position);
}
});
break;
}
case TYPE_ALBUM: {
selectMark.setVisibility(View.VISIBLE);
final FileItem item = (FileItem) mList.get(position);
setImageThumbnail(image, item.getPath(), item);
params.setMargins(10, 10, 10, 10);
image.setLayoutParams(params);
if (mSelectedMap.get(item.getPath()) == null) {
Log.i(TAG,
"path:" + item.getPath() + ", mlist size:"
+ mList.size() + ", map size:"
+ mSelectedMap.size());
}
if (mSelectedMap.get(item.getPath())) {
selectMark.setImageResource(R.drawable.btn_checked_big);
} else {
selectMark.setImageResource(R.drawable.btn_checked_big_not);
// selectMark.setVisibility(View.GONE);
}
selectMark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (mIsLongClick) {
// mIsLongClick = false;
// return;
// }
if (!mSelectedMap.get(item.getPath())) {
selectMark.setImageResource(R.drawable.btn_checked_big);
// selectMark.setVisibility(View.VISIBLE);
} else {
// selectMark.setVisibility(View.GONE);
selectMark
.setImageResource(R.drawable.btn_checked_big_not);
}
// Log.e(TAG, "date:" + item.getDate());
itemClick(position);
}
});
break;
}
}
return convertView;
}
private HashMap<Integer, View> viewMap;
private void initImageLoader(Context context) {
mImageLoader = ImageLoaderManager.getImageLoader(getContext());
mOptions = ImageLoaderManager.getImageOptions();
}
private void setImageThumbnail(ImageView imageView, String filePath,
FileItem item) {
try {
String path = "file://" + filePath;
if (FileUtils.isFileExist(filePath)) {
imageView.setScaleType(ScaleType.CENTER_CROP);
try {
// if (item.getRef() != null && item.getRef().get() != null) {
// imageView.setImageBitmap(item.getRef().get());
// } else {
mImageLoader.displayImage(path, imageView, mOptions,
new ImageLoadingListenerImpl(item));
// }
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.e(TAG, "file not exist:" + path);
imageView.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void setList(List<Object> objects) {
if (objects == null) {
return;
}
mList.clear();
// mList.addAll(objects);
mSelectedMap.clear();
switch (mType) {
case TYPE_CLEAR: {
for (int i = 0; i < objects.size(); i++) {
ExportedImageItem item = (ExportedImageItem) objects.get(i);
if (FileUtils.isFileExist(item.getPath())) {
mList.add(objects.get(i));
mSelectedMap.put(item.getPath(), false);
} else {
Log.e(TAG, "Clear, file not exist:" + item.getPath());
}
}
break;
}
case TYPE_SIMILAR: {
for (int i = 0; i < objects.size(); i++) {
SimilarImageItem item = (SimilarImageItem) objects.get(i);
if (FileUtils.isFileExist(item.getPath())) {
mList.add(objects.get(i));
mSelectedMap.put(item.getPath(), false);
} else {
Log.e(TAG, "Similar, file not exist:" + item.getPath());
}
}
break;
}
case TYPE_ALBUM: {
for (int i = 0; i < objects.size(); i++) {
FileItem item = (FileItem) objects.get(i);
if (FileUtils.isFileExist(item.getPath())) {
mList.add(objects.get(i));
mSelectedMap.put(item.getPath(), false);
} else {
Log.e(TAG, "Album, file not exist:" + item.getPath());
}
}
break;
}
}
notifyDataSetChanged();
}
public void addObjects(List<Object> objects) {
if (objects == null) {
return;
}
if (mList != null) {
mList.clear();
}
/*
* for (int i = 0; i < objects.size(); i++) { mList.add(objects.get(i));
* }
*/
switch (mType) {
case TYPE_CLEAR: {
for (int i = 0; i < objects.size(); i++) {
ExportedImageItem item = (ExportedImageItem) objects.get(i);
if (FileUtils.isFileExist(item.getPath())) {
mList.add(objects.get(i));
mSelectedMap.put(item.getPath(), false);
} else {
Log.e(TAG, "Clear, file not exist:" + item.getPath());
}
}
break;
}
case TYPE_SIMILAR: {
for (int i = 0; i < objects.size(); i++) {
SimilarImageItem item = (SimilarImageItem) objects.get(i);
if (FileUtils.isFileExist(item.getPath())) {
mList.add(objects.get(i));
mSelectedMap.put(item.getPath(), false);
} else {
Log.e(TAG, "Similar, file not exist:" + item.getPath());
}
}
break;
}
case TYPE_ALBUM: {
for (int i = 0; i < objects.size(); i++) {
FileItem item = (FileItem) objects.get(i);
if (FileUtils.isFileExist(item.getPath())) {
mList.add(objects.get(i));
mSelectedMap.put(item.getPath(), false);
} else {
Log.e(TAG, "Album, file not exist:" + item.getPath());
}
}
break;
}
}
// notifyDataSetChanged();
}
public void deleteSelectedPhoto() {
Iterator<Object> iteratorValue = mList.iterator();
boolean isDeleted = false;
while (iteratorValue.hasNext()) {
switch (mType) {
case TYPE_CLEAR: {
ExportedImageItem item = (ExportedImageItem) iteratorValue
.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
mSelectedMap.remove(item.getPath());
iteratorValue.remove();
isDeleted = true;
}
break;
}
case TYPE_SIMILAR: {
SimilarImageItem item = (SimilarImageItem) iteratorValue.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
mSelectedMap.remove(item.getPath());
iteratorValue.remove();
isDeleted = true;
}
break;
}
case TYPE_ALBUM: {
FileItem item = (FileItem) iteratorValue.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
mSelectedMap.remove(item.getPath());
iteratorValue.remove();
isDeleted = true;
}
break;
}
}
}
// if (isDeleted) {
notifyDataSetChanged();
// }
}
public void deletePhotoes(List<Object> list, boolean isNotify) {
Log.w(TAG, "delete size:" + list.size());
boolean isDeleted = false;
switch (mType) {
case TYPE_CLEAR: {
for (Object object : list) {
Iterator<Object> iterator = mList.iterator();
while (iterator.hasNext()) {
ExportedImageItem item = (ExportedImageItem) iterator
.next();
ExportedImageItem deleteItem = (ExportedImageItem) object;
if (item.getPath().equals(deleteItem.getPath())) {
Log.w(TAG, "delete file:" + deleteItem.getPath());
mSelectedMap.remove(deleteItem.getPath());
iterator.remove();
isDeleted = true;
break;
}
}
}
break;
}
case TYPE_SIMILAR: {
for (Object object : list) {
Iterator<Object> iterator = mList.iterator();
while (iterator.hasNext()) {
SimilarImageItem item = (SimilarImageItem) iterator.next();
SimilarImageItem deleteItem = (SimilarImageItem) object;
if (item.getPath().equals(deleteItem.getPath())) {
mSelectedMap.remove(deleteItem.getPath());
iterator.remove();
isDeleted = true;
break;
}
}
}
break;
}
case TYPE_ALBUM: {
for (Object object : list) {
Iterator<Object> iterator = mList.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
FileItem deleteItem = (FileItem) object;
if (item.getPath().equals(deleteItem.getPath())) {
mSelectedMap.remove(deleteItem.getPath());
iterator.remove();
isDeleted = true;
break;
}
}
}
break;
}
}
// if (isDeleted && isNotify) {
notifyDataSetChanged();
// }
}
public void deleteSimilarPhotoesById(List<String> list, boolean isNotify) {
boolean isDeleted = false;
for (String path : list) {
Iterator<Object> iterator = mList.iterator();
while (iterator.hasNext()) {
SimilarImageItem item = (SimilarImageItem) iterator.next();
if (item.getPath().equals(path)) {
iterator.remove();
mSelectedMap.remove(path);
isDeleted = true;
break;
}
}
}
// if (isDeleted && isNotify) {
notifyDataSetChanged();
// }
}
public long getSelectedSize() {
long totalSize = 0;
Iterator<Object> iteratorValue = mList.iterator();
while (iteratorValue.hasNext()) {
switch (mType) {
case TYPE_CLEAR: {
ExportedImageItem item = (ExportedImageItem) iteratorValue
.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
totalSize += item.getSize();
} else {
// Log.e(TAG, "false:" + item.getPath());
}
break;
}
case TYPE_SIMILAR: {
SimilarImageItem item = (SimilarImageItem) iteratorValue.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
totalSize += item.getSize();
}
break;
}
case TYPE_ALBUM: {
FileItem item = (FileItem) iteratorValue.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
totalSize += item.getSize();
}
break;
}
}
}
return totalSize;
}
public long getTotalSize() {
long totalSize = 0;
Iterator<Object> iteratorValue = mList.iterator();
while (iteratorValue.hasNext()) {
switch (mType) {
case TYPE_CLEAR: {
ExportedImageItem item = (ExportedImageItem) iteratorValue
.next();
totalSize += item.getSize();
break;
}
case TYPE_SIMILAR: {
SimilarImageItem item = (SimilarImageItem) iteratorValue.next();
totalSize += item.getSize();
break;
}
case TYPE_ALBUM: {
FileItem item = (FileItem) iteratorValue.next();
totalSize += item.getSize();
break;
}
}
}
return totalSize;
}
public int getSelectedCount() {
int count = 0;
Iterator<Entry<String, Boolean>> iterator = mSelectedMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, Boolean> entry = iterator.next();
if (entry.getValue()) {
count++;
}
}
return count;
}
public boolean isAllSelected() {
Iterator<Entry<String, Boolean>> iterator = mSelectedMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, Boolean> entry = iterator.next();
if (!entry.getValue()) {
return false;
}
}
return true;
}
public List<Object> getSelectedList() {
List<Object> list = new ArrayList<Object>();
Iterator<Object> iteratorValue = mList.iterator();
while (iteratorValue.hasNext()) {
switch (mType) {
case TYPE_CLEAR: {
ExportedImageItem item = (ExportedImageItem) iteratorValue
.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
list.add(item);
}
break;
}
case TYPE_SIMILAR: {
SimilarImageItem item = (SimilarImageItem) iteratorValue.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
list.add(item);
}
break;
}
case TYPE_ALBUM: {
FileItem item = (FileItem) iteratorValue.next();
boolean isSelected = mSelectedMap.get(item.getPath());
if (isSelected) {
list.add(item);
}
break;
}
}
}
return list;
}
public void setListener(AdapterListener listener) {
mListener = listener;
}
public void setItemSize(int width, int height) {
mItemWidth = width;
mItemHeight = height;
}
public void setMultipleSelectMode(boolean isMultiple) {
if (mIsMultiple == isMultiple) {
return;
}
mIsMultiple = isMultiple;
notifyDataSetChanged();
}
public void allSelected(boolean isSelected) {
Iterator<Entry<String, Boolean>> iterator = mSelectedMap.entrySet()
.iterator();
while (iterator.hasNext()) {
Entry<String, Boolean> entry = iterator.next();
entry.setValue(isSelected);
}
notifyDataSetChanged();
}
public boolean selectItemByPath(String path, boolean selected) {
if (path != null) {
if (mSelectedMap.containsKey(path)) {
if (mSelectedMap.get(path) == selected) {
return false;
}
Log.e(TAG, "select file:" + path + ", value:" + selected);
mSelectedMap.put(path, selected);
if (mVisibleItemCount == 0) {
notifyDataSetChanged();
} else {
int index = getItemIndex(path);
if ((index > (mFirstVisibleItem - 1))
&& (index < (mFirstVisibleItem + mVisibleItemCount + 1))) {
notifyDataSetChanged();
}
}
return true;
}
}
return false;
}
private int getItemIndex(String path) {
switch (mType) {
case TYPE_CLEAR: {
for (int i = 0; i < mList.size(); i++) {
ExportedImageItem item = (ExportedImageItem) mList.get(i);
if (item.getPath().equals(path)) {
return i;
}
}
break;
}
case TYPE_SIMILAR: {
for (int i = 0; i < mList.size(); i++) {
SimilarImageItem item = (SimilarImageItem) mList.get(i);
if (item.getPath().equals(path)) {
return i;
}
}
break;
}
case TYPE_ALBUM: {
for (int i = 0; i < mList.size(); i++) {
FileItem item = (FileItem) mList.get(i);
if (item.getPath().equals(path)) {
return i;
}
}
break;
}
}
return -1;
}
public void itemClick(int position) {
if (mList.size() - 1 < position) {
return;
}
String key = "";
switch (mType) {
case TYPE_CLEAR: {
ExportedImageItem item = (ExportedImageItem) mList.get(position);
key = item.getPath();
break;
}
case TYPE_SIMILAR: {
SimilarImageItem item = (SimilarImageItem) mList.get(position);
key = item.getPath();
break;
}
case TYPE_ALBUM: {
FileItem item = (FileItem) mList.get(position);
key = item.getPath();
break;
}
}
if (mSelectedMap.get(key)) {
mSelectedMap.put(key, false);
removeClickedItem(key);
} else {
mSelectedMap.put(key, true);
addClickedItem(key);
}
if (mListener != null) {
Log.e(TAG, "File path" + key);
mListener.onItemClick(position, mSelectedMap.get(key));
}
}
private void addClickedItem(String key) {
if (key == null) {
return;
}
for (String path : mClickedList) {
if (key.equals(path)) {
return;
}
}
mClickedList.add(key);
}
private void removeClickedItem(String key) {
if (key == null) {
return;
}
Iterator<String> iterator = mClickedList.iterator();
while (iterator.hasNext()) {
String path = iterator.next();
if (key.equals(path)) {
iterator.remove();
return;
}
}
}
public boolean isClickedItem() {
if (mClickedList.size() > 0) {
return true;
}
return false;
}
public List<Object> sort(int sortType) {
mList = ItemComparator.sort(mList, sortType);
notifyDataSetChanged();
return mList;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
private int mFirstVisibleItem = 0;
private int mVisibleItemCount = 0;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
mFirstVisibleItem = firstVisibleItem;
mVisibleItemCount = visibleItemCount;
}
/*
* private ImageLoadingListener mImageLoadingListener = new
* ImageLoadingListener() {
*
* @Override public void onLoadingStarted(String imageUri, View view) { }
*
* @Override public void onLoadingFailed(String imageUri, View view,
* FailReason failReason) { String fileName =
* FileUtil.getFileName(imageUri); if (FileUtil.isVideo(mContext, fileName))
* { // ((ImageView) // view).setImageResource(R.drawable.video_loading);
* String loacation = imageUri.substring(7); // start with file:// Bitmap
* thumBitmap = FileUtil.getImageThumbnail(mContext, loacation); if
* (thumBitmap != null) { ((ImageView) view).setImageBitmap(thumBitmap); }
* else { ((ImageView) view) .setImageResource(R.drawable.video_loading); }
* } }
*
* @Override public void onLoadingComplete(String imageUri, View view,
* Bitmap loadedImage) { }
*
* @Override public void onLoadingCancelled(String imageUri, View view) { }
* };
*/
class ImageLoadingListenerImpl implements ImageLoadingListener {
private FileItem item;
public ImageLoadingListenerImpl(FileItem item) {
this.item = item;
}
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String fileName = FileUtil.getFileName(imageUri);
if (FileUtil.isVideo(mContext, fileName)) {
// ((ImageView)
// view).setImageResource(R.drawable.video_loading);
String loacation = imageUri.substring(7); // start with file://
Bitmap thumBitmap = FileUtil.getImageThumbnail(mContext,
loacation);
if (thumBitmap != null) {
((ImageView) view).setImageBitmap(thumBitmap);
} else {
((ImageView) view)
.setImageResource(R.drawable.video_loading);
}
}
}
@Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (item != null) {
item.setRef(new WeakReference<Bitmap>(loadedImage));
}
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
}
}
}
|
PHP | UTF-8 | 519 | 2.703125 | 3 | [
"BSD-4-Clause-UC",
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"TCL",
"ISC",
"Zlib",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"blessing"
] | permissive | --TEST--
IntlCalendar::get() basic test
--SKIPIF--
<?php
if (!extension_loaded('intl'))
die('skip intl extension not enabled');
--FILE--
<?php
ini_set("intl.error_level", E_WARNING);
ini_set("intl.default_locale", "nl");
$intlcal = IntlCalendar::createInstance('UTC');
$intlcal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 4);
var_dump($intlcal->get(IntlCalendar::FIELD_DAY_OF_MONTH));
var_dump(intlcal_get($intlcal, IntlCalendar::FIELD_DAY_OF_MONTH));
?>
==DONE==
--EXPECT--
int(4)
int(4)
==DONE==
|
Rust | UTF-8 | 3,604 | 2.75 | 3 | [
"CC0-1.0"
] | permissive | //! Derivation path according to
//! BIP-44 <https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki>
//! and EIP-3 <https://github.com/ergoplatform/eips/blob/master/eip-0003.md>
use derive_more::FromStr;
use ergo_lib::wallet::derivation_path::ChildIndexError;
use ergo_lib::wallet::derivation_path::ChildIndexHardened;
use ergo_lib::wallet::derivation_path::ChildIndexNormal;
use ergo_lib::wallet::derivation_path::DerivationPath as InnerDerivationPath;
use wasm_bindgen::prelude::*;
use crate::error_conversion::to_js;
extern crate derive_more;
use derive_more::{From, Into};
/// According to
/// BIP-44 <https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki>
/// and EIP-3 <https://github.com/ergoplatform/eips/blob/master/eip-0003.md>
#[wasm_bindgen]
#[derive(PartialEq, Eq, Debug, Clone, From, Into, FromStr)]
pub struct DerivationPath(InnerDerivationPath);
#[wasm_bindgen]
impl DerivationPath {
/// Create derivation path for a given account index (hardened) and address indices
/// `m / 44' / 429' / acc' / 0 / address[0] / address[1] / ...`
/// or `m / 44' / 429' / acc' / 0` if address indices are empty
/// change is always zero according to EIP-3
/// acc is expected as a 31-bit value (32th bit should not be set)
pub fn new(acc: u32, address_indices: &[u32]) -> Result<DerivationPath, JsValue> {
let acc = ChildIndexHardened::from_31_bit(acc).map_err(to_js)?;
let address_indices = address_indices
.iter()
.map(|i| ChildIndexNormal::normal(*i))
.collect::<Result<Vec<ChildIndexNormal>, ChildIndexError>>()
.map_err(to_js)?;
Ok(DerivationPath(InnerDerivationPath::new(
acc,
address_indices,
)))
}
/// Create root derivation path
pub fn master_path() -> Self {
DerivationPath(InnerDerivationPath::master_path())
}
/// Returns the length of the derivation path
pub fn depth(&self) -> usize {
self.0.depth()
}
/// Returns a new path with the last element of the deriviation path being increased, e.g. m/1/2 -> m/1/3
/// Returns an empty path error if the path is empty (master node)
pub fn next(&self) -> Result<DerivationPath, JsValue> {
Ok(self.0.next().map_err(to_js)?.into())
}
/// String representation of derivation path
/// E.g m/44'/429'/0'/0/1
#[wasm_bindgen(js_name = toString)]
#[allow(clippy::inherent_to_string)]
pub fn to_string(&self) -> String {
self.0.to_string()
}
/// Create a derivation path from a formatted string
/// E.g "m/44'/429'/0'/0/1"
pub fn from_string(path: &str) -> Result<DerivationPath, JsValue> {
Ok(path.parse::<InnerDerivationPath>().map_err(to_js)?.into())
}
/// For 0x21 Sign Transaction command of Ergo Ledger App Protocol
/// P2PK Sign (0x0D) instruction
/// Sign calculated TX hash with private key for provided BIP44 path.
/// Data:
///
/// Field
/// Size (B)
/// Description
///
/// BIP32 path length
/// 1
/// Value: 0x02-0x0A (2-10). Number of path components
///
/// First derivation index
/// 4
/// Big-endian. Value: 44’
///
/// Second derivation index
/// 4
/// Big-endian. Value: 429’ (Ergo coin id)
///
/// Optional Third index
/// 4
/// Big-endian. Any valid bip44 hardened value.
/// ...
/// Optional Last index
/// 4
/// Big-endian. Any valid bip44 value.
///
pub fn ledger_bytes(&self) -> Vec<u8> {
self.0.ledger_bytes()
}
}
|
Python | UTF-8 | 1,771 | 2.8125 | 3 | [
"Apache-2.0"
] | permissive | """
Code for "Stability Analysis of Newton-MR Under Hessian Perturbations".
Authors: Yang Liu, Fred Roosta. ArXiv:1909.06224
Recover Figure 4 and 5. Stability comparison between full and sub-sampled
variants of Newton-MR and Newton-CG using s = 0.1n, 0.05n, 0.01n.
To seperate MR & CG plots
1, copy & paste the recording .txt files to showFig folder,
2, run showFigure.py with different options,
"""
from initialize import initialize
class learningRate():
def __init__(self, value):
self.value = value
class algPara():
def __init__(self, value):
self.value = value
#initialize methods
data = [
'mnist',
# 'hapt',
]
prob = [
'softmax', # realData
]
methods = [
'Newton_MR',
'Newton_CG',
]
regType = [
'None',
# 'Convex',
# 'Nonconvex',
]
#initial point
x0Type = [
# 'randn',
# 'rand',
# 'ones'
'zeros', # note: 0 is a saddle point for fraction problems
]
#initialize parameters
algPara.mainLoopMaxItrs = 15 #Set mainloop stops with Maximum Iterations
algPara.funcEvalMax = 1E6 #Set mainloop stops with Maximum Function Evaluations
algPara.innerSolverMaxItrs = 200
algPara.lineSearchMaxItrs = 50
algPara.gradTol = 1e-10 #If norm(g)<gradTol, minFunc loop breaks
algPara.innerSolverTol = 0.01 #Inexactness of inner solver
algPara.beta = 1E-4 #Line search para
algPara.beta2 = 0.4 #Wolfe's condition for L-BFGS
algPara.show = True
HProp_all = [0.1, 0.05, 0.01] # \leq 3 inputs
fullHessian = True #Run full Hessian cases for all methods
plotAll = True
## Initialize
initialize(data, methods, prob, regType, x0Type, HProp_all, 0,
algPara, learningRate, 1, fullHessian, plotAll)
|
Java | UTF-8 | 4,491 | 1.757813 | 2 | [] | no_license | package com.l9e.transaction.dao.impl;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.l9e.common.BaseDao;
import com.l9e.transaction.dao.CommonDao;
import com.l9e.transaction.vo.Worker;
@Repository("commonDao")
public class CommonDaoImpl extends BaseDao implements CommonDao {
public String querySysSettingByKey(String key) {
return (String) this.getSqlMapClientTemplate().queryForObject("common.querySysSettingByKey", key);
}
public Worker queryRandomWorker(Map<String,Object> map) {
return (Worker) this.getSqlMapClientTemplate().queryForObject("common.queryRandomWorker",map);
}
@SuppressWarnings("unchecked")
public List<Map<String, String>> queryWaitNotify() {
return this.getSqlMapClientTemplate().queryForList("common.queryWaitNotify");
}
public void updateRobotStartNotify(Map<String, String> map) {
this.getSqlMapClientTemplate().update("common.updateRobotStartNotify",map);
}
public List<Map<String, String>> queryLockOrderList() {
return this.getSqlMapClientTemplate().queryForList("common.queryLockOrderList");
}
public void addCpOrderHistory(Map<String, String> map) {
this.getSqlMapClientTemplate().insert("common.addCpOrderHistory",map);
}
public void updateCpOrderStatus(Map<String, String> map) {
this.getSqlMapClientTemplate().update("common.updateCpOrderStatus",map);
}
public void updateCpOrderNotify(Map<String, String> map) {
this.getSqlMapClientTemplate().update("common.updateCpOrderNotify",map);
}
public List<Map<String, String>> queryLockAlterOrderList() {
return this.getSqlMapClientTemplate().queryForList("common.queryLockAlterOrderList");
}
public void updateQunarRefundOrderStatus(Map<String, String> map) {
this.getSqlMapClientTemplate().update("common.updateQunarRefundOrderStatus",map);
}
public void update19eRefundOrderStatus(Map<String, String> map) {
this.getSqlMapClientTemplate().update("common.update19eRefundOrderStatus",map);
}
public List<String> queryPinganMessageList() {
return this.getSqlMapClientTemplate().queryForList("common.queryPinganMessageList");
}
public List<Map<String, String>> queryAccountSeatList(Map<String, String> param) {
return this.getSqlMapClientTemplate().queryForList("common.queryAccountSeatList",param);
}
public void updateAccountStatusFree(String acc_id) {
this.getSqlMapClientTemplate().update("common.updateAccountStatusFree",acc_id);
}
public int updateQunarSysNoticeStaus(Map<String, String> param) {
return this.getSqlMapClientTemplate().update("common.updateQunarSysNoticeStaus",param);
}
public List<Map<String, String>> queryExtMerchantList() {
return this.getSqlMapClientTemplate().queryForList("common.queryExtMerchantList");
}
public List<String> queryLockBookOrder(Map<String, String> param) {
return this.getSqlMapClientTemplate().queryForList("common.queryLockBookOrder",param);
}
public void updateCpOrderinfoNotify(Map<String, String> param) {
this.getSqlMapClientTemplate().update("common.updateCpOrderinfoNotify",param);
}
public void insertCpHistory(Map<String, String> param) {
this.getSqlMapClientTemplate().update("common.insertCpHistory",param);
}
public void updateElongRefundOrderStatus(Map<String, String> map) {
this.getSqlMapClientTemplate().update("common.updateElongRefundOrderStatus",map);
}
public int updateElongSysNoticeStaus(Map<String, String> paramElong) {
return this.getSqlMapClientTemplate().update("common.updateElongSysNoticeStaus",paramElong);
}
public Integer queryHeyanWorkNum(Integer worker_type) {
return (Integer) this.getSqlMapClientTemplate().queryForObject("common.queryHeyanWorkNum", worker_type);
}
public Map<String, String> queryElongSystemSetting(String setting_name) {
Object object = this.getSqlMapClientTemplate().queryForObject("common.queryElongSystemSetting", setting_name);
if(object != null){
return (Map<String, String>)object;
}else{
return null;
}
}
public Map<String, String> queryQunarSystemSetting(String setting_name) {
Object object = this.getSqlMapClientTemplate().queryForObject("common.queryQunarSystemSetting", setting_name);
if(object != null){
return (Map<String, String>)object;
}else{
return null;
}
}
public int updateBalance(Map<String, String> param) {
// TODO Auto-generated method stub
return this.getSqlMapClientTemplate().update("common.updateBalance",param);
}
}
|
C++ | UTF-8 | 474 | 2.9375 | 3 | [] | no_license | class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *slow=head,*fast=head;
while(fast and fast->next){
slow=slow->next;
fast=fast->next->next;
if(slow==fast){
slow=head;
while(slow!=fast){
slow=slow->next;
fast=fast->next;
}
return slow;
}
}
return NULL;
}
};
|
Python | UTF-8 | 91 | 3.109375 | 3 | [] | no_license | a=int(raw_input("Enter val 1:"))
b=int(raw_input("Enter val 2:"))
z= a + b
print z
|
Java | UTF-8 | 6,235 | 1.796875 | 2 | [] | no_license | package com.dongwukj.weiwei.ui.fragment;
import com.dongwukj.weiwei.R;
import com.dongwukj.weiwei.idea.enums.HeaderActivityType;
import com.dongwukj.weiwei.idea.request.AddToCartRequest;
import com.dongwukj.weiwei.idea.result.PhoneAddProductResult;
import com.dongwukj.weiwei.idea.result.UserResult;
import com.dongwukj.weiwei.net.ShoppingCartRequestClient;
import com.dongwukj.weiwei.net.ShoppingCartRequestClient.AddShoppingCartRequestClientCallback;
import com.dongwukj.weiwei.ui.activity.HomeHeaderActivity;
import com.dongwukj.weiwei.ui.activity.LoginActivity;
import com.dongwukj.weiwei.ui.widget.BadgeView;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public abstract class ShopCartMessageFragment extends AbstractHeaderFragment {
private BadgeView buyNumView;
private int buyNum;
private TextView list_header_rightbutton;
public void findView(View v,String title) {
TextView list_header_title = (TextView) v.findViewById(R.id.list_header_title);
list_header_title.setText(title);
LinearLayout list_header_leftbutton = (LinearLayout) v.findViewById(R.id.ll_left);
list_header_leftbutton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
activity.finish();
}
});
RelativeLayout rl=(RelativeLayout) v.findViewById(R.id.rl);
list_header_rightbutton = (TextView) v.findViewById(R.id.list_header_rightbutton);
list_header_rightbutton.setVisibility(View.VISIBLE);
list_header_rightbutton.setBackgroundResource(R.drawable.weiwei_gouwuche_checked);
buyNumView=new BadgeView(activity, rl);
buyNumView.setTextColor(Color.WHITE);
buyNumView.setTextSize(10);
buyNum = baseApplication.getCartCount();
setBadgeViewText(buyNum+"");
list_header_rightbutton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
openNewActivityWithHeader(HeaderActivityType.AddShopCart.ordinal(), true, false);
}
});
}
@Override
public void onResume() {
buyNum=baseApplication.getCartCount();
setBadgeViewText(buyNum+"");
super.onResume();
}
private void openNewActivityWithHeader(int type,boolean isneedlogin,boolean hasheader) {
Intent intent = new Intent(activity, HomeHeaderActivity.class);
intent.putExtra("type", type);
intent.putExtra("needLogin", isneedlogin);
intent.putExtra("hasHeader", hasheader);
intent.putExtra("isFromDetails", true);
startActivity(intent);
}
public void showdialog() {
final Dialog dialog = new Dialog(activity, R.style.Dialog);
//View view = View.inflate(activity, R.layout.ordercancle_dialog, null);
dialog.setContentView(R.layout.ordercancle_dialog);
dialog.setCancelable(false);
TextView tv_cancle = (TextView) dialog.findViewById(R.id.tv_cancle);
TextView tv_ok = (TextView) dialog.findViewById(R.id.tv_ok);
TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
WindowManager m = activity.getWindowManager();
Window dialogWindow = dialog.getWindow();
Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
p.height = (int) (d.getHeight() * 0.36); // 高度设置为屏幕的0.30
p.width = (int) (d.getWidth() * 0.80); // 宽度设置为屏幕的0.80
dialogWindow.setAttributes(p);
tv_title.setText("确认登录");
tv_ok.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
tv_cancle.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
Intent intent = new Intent(activity, LoginActivity.class);
startActivity(intent);
}
});
dialog.show();
}
public void checkedIsloginToBuy(int pmid,boolean iscombo){
if (isLogin()) {
addComBoToCart(pmid,iscombo);
}else {
showdialog();
}
}
private void addComBoToCart(int pmid,boolean iscombo) {
AddToCartRequest request = new AddToCartRequest();
if (iscombo) {
request.setGoodsNum("1");
request.setPmId(pmid+"");
}else {
request.setGoodsNum("1");
request.setGoodsId(pmid);
}
ShoppingCartRequestClient client=new ShoppingCartRequestClient(activity, baseApplication);
client.addCart(request, new AddShoppingCartRequestClientCallback() {
@Override
protected void listSuccess(PhoneAddProductResult result) {
if (getActivity()==null) {
return;
}
Toast.makeText(activity, "商品加到购物车成功!", Toast.LENGTH_SHORT).show();
setBadgeViewText(baseApplication.getCartCount()+"");
}
});
}
private void setBadgeViewText(String buyNum) {
if (Integer.parseInt(buyNum)>=99) {
buyNumView.setTextSize(9);
buyNumView.setText("99+");
}else {
buyNumView.setTextSize(12);
buyNumView.setText(buyNum);
}
//buyNumView.setText(buyNum);//
buyNumView.setBadgePosition(BadgeView.POSITION_TOP_RIGHT);
if (!buyNum.equals("0")) {
buyNumView.show();
}else {
buyNumView.hide();
}
}
private boolean isLogin() {
UserResult result = baseApplication.getUserResult();
if (result != null && result.getUserAccount() != null) {
return true;
} else {
return false;
}
}
}
|
Java | UTF-8 | 466 | 2.015625 | 2 | [] | no_license | package com.digital.wallet.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.digital.wallet.models.Customer;
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
Customer findByEmail(String str);
// @Query("SELECT c FROM Customer c WHERE c.email=:email")
// Iterable<Customer> findCustomerByEmail(@Param("email") String email);
}
|
Go | UTF-8 | 1,939 | 2.796875 | 3 | [] | no_license | package utils
import (
"os"
"path/filepath"
"sync"
"github.com/sirupsen/logrus"
)
type User struct {
Username string
Key string
BaseFilePath string
ConfigPath string
Objects map[string]FObject
ClientInstances map[string]ClientInstance
mux sync.Mutex
}
func (u *User) UpdateObject(obj FObject) {
u.mux.Lock()
u.Objects[obj.Relativepath] = obj
u.mux.Unlock()
}
func (u *User) GetObjects() map[string]FObject {
u.mux.Lock()
defer u.mux.Unlock()
return u.Objects
}
func (u *User) GetObject(key string) (FObject, bool) {
u.mux.Lock()
defer u.mux.Unlock()
if obj, ok := u.Objects[key]; ok {
return obj, true
}
return u.Objects[key], false
}
func (u *User) SetUp(c ConfigCloudStore) {
base_dir := filepath.Join(c.BasePath, u.Username, "files")
config_path := filepath.Join(c.BasePath, u.Username, "config.txt")
u.BaseFilePath = base_dir
logrus.Printf("Setting up Dirs for User: %v path:%v \n", u.Username, u.BaseFilePath)
if _, e := os.Lstat(base_dir); os.IsNotExist(e) {
os.MkdirAll(base_dir, 0777)
os.Create(config_path)
}
}
func (u *User) CreateUserDir(c ConfigCloudStore) {
os.Mkdir(filepath.Join(c.BasePath, u.Username, "files"), os.ModeDir)
}
func (u *User) CreateFile(c ConfigCloudStore, filename string) {
os.Create(filepath.Join(c.BasePath, u.Username, "file", filename))
}
func (u *User) SaveObject(f *FObject, data []byte) {
to_save_path := filepath.Join(u.BaseFilePath, f.Location)
to_save_dir := filepath.Dir(to_save_path)
if _, e := os.Lstat(to_save_dir); os.IsNotExist(e) {
os.MkdirAll(to_save_dir, 0777)
}
os.Create(to_save_path)
file, err := os.OpenFile(to_save_path, os.O_APPEND, 0755)
defer file.Close()
// buf := make([]byte, 1024)
if err != nil {
if l, err := file.Write(data); err != nil {
logrus.Printf("%v Bytes written to file %v", l, f.Name)
} else {
logrus.Printf("error in writing to file %v", err)
}
}
}
|
Java | UTF-8 | 4,036 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package com.gdufe.osc.scheduled;
import com.gdufe.osc.utils.gson.GsonUtils;
import com.gdufe.osc.utils.HttpHelper;
import com.gdufe.osc.utils.WeChatNoticeUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @author changwenbo
* @date 2020/9/14 10:11
*/
@Component
@Slf4j
public class CronTaskByStock {
private static final String stockUrl = "http://ipo.sseinfo.com/info/commonQuery.do?jsonCallBack=jsonpCallback79425&isPagination=true&sqlId=COMMON_SSE_IPO_ISSUE_L&stockType=0&pageHelp.pageSize=15&_=1616911664823";
private static final String bondUrl = "http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get?type=KZZ_LB2.0&token=70f12f2f4f091e459a279469fe49eca5&st=STARTDATE&sr=-1&p=1&ps=10";
private static final String format = "yyyy-MM-dd";
@Autowired
private WeChatNoticeUtils weChatNoticeUtils;
/** 每天9点执行 */
@Scheduled(cron = "0 0 9 * * ?")
public void notifyStockTime() {
executeStock();
executeBond();
}
private void executeBond() {
try {
String content = HttpHelper.get(bondUrl);
if (StringUtils.isEmpty(content)) {
log.error("e = {}", content);
weChatNoticeUtils.setMessage("债券爬取失败,请您及时排查问题..", content);
return;
}
JsonArray jsonArray = GsonUtils.toJsonArrayWithNullable(content);
log.info("jsonStr = {}", jsonArray.size());
StringBuilder name = new StringBuilder();
DateTime dateTime = DateTime.now();
String dt = dateTime.toString(format) + "T00:00:00";
boolean send = false;
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject json = jsonArray.get(i).getAsJsonObject();
String date = json.get("STARTDATE").getAsString();
String stockName = json.get("CORRESNAME").getAsString();
if (dt.equals(date)) {
send = true;
name.append(dt + " " + stockName);
name.append("\n");
log.info("date = {}, stockName = {}", date, stockName);
}
}
if (send) {
weChatNoticeUtils.setMessage("今天有如下债券申购,请及时申购:", name.toString());
}
} catch (Exception e) {
log.error("e = {}", e);
weChatNoticeUtils.setMessage("债券爬取失败,请您及时排查问题..", e.toString());
return;
}
}
private void executeStock() {
try {
String content = HttpHelper.get(stockUrl);
if (StringUtils.isEmpty(content) || !content.startsWith("jsonpCallback")) {
log.error("e = {}", content);
weChatNoticeUtils.setMessage("股票爬取失败,请您及时排查问题..", content);
return;
}
int start = content.indexOf("{");
int end = content.lastIndexOf("}");
String jsonStr = StringUtils.substring(content.substring(start, end + 1), 0, -1) + "}";
JsonObject jsonObject = GsonUtils.toJsonObjectWithNullable(jsonStr);
JsonArray jsonArray = jsonObject.get("result").getAsJsonArray();
log.info("jsonStr = {}", jsonArray.size());
StringBuilder name = new StringBuilder();
DateTime dateTime = DateTime.now();
String dt = dateTime.toString(format);
boolean send = false;
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject json = jsonArray.get(i).getAsJsonObject();
String date = json.get("ONLINE_ISSUANCE_DATE").getAsString();
String stockName = json.get("SECURITY_NAME").getAsString();
if (dt.equals(date)) {
send = true;
name.append(dt + " " + stockName);
name.append("\n");
log.info("date = {}, stockName = {}", date, stockName);
}
}
if (send) {
weChatNoticeUtils.setMessage("今天有如下股票申购,请及时申购:", name.toString());
}
} catch (Exception e) {
log.error("e = {}", e);
weChatNoticeUtils.setMessage("股票爬取失败,请您及时排查问题..", e.toString());
return;
}
}
}
|
JavaScript | UTF-8 | 425 | 3.4375 | 3 | [] | no_license | function fishTank(arg1, arg2, arg3, arg4) {
let length = Number(arg1);
let width = Number(arg2);
let height = Number(arg3);
let percentage = Number(arg4);
let totalVolume = length * width * height; // in cm3
let totalLitters = totalVolume / 1000; // in litters
let volume = totalLitters * (1 - percentage / 100);
console.log(volume);
}
fishTank("85", "75", "47", "17"); |
C++ | UTF-8 | 3,259 | 3.28125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "../Core.h"
#include "../Rendering/Drawable.h"
#include "../Physics/Transformable.h"
namespace Engine::Shapes
{
/// <summary>
/// Allows to display and move a rectangle on the screen. The rectangle has a position, a color and a velocity at which it moves.
/// <para>
/// Represents a wrapper for the SFML rectangle element.
/// </para>
/// </summary>
class ENGINE_API Rectangle : public Rendering::Drawable, public Physics::Transformable
{
public:
/// <summary>
/// Creates a rectangle at the given position with the given size and color.
/// </summary>
/// <param name="position">- The position of the rectangle in pixels.</param>
/// <param name="size">- The size of the rectangle in pixels.</param>
/// <param name="color">- The color of the rectangle.</param>
Rectangle(const Vector2& position, const Vector2& size, const Color& color);
/// <summary>
/// Draws the rectangle to the given RenderWindow.
/// </summary>
/// <param name="window">- The window to render to.</param>
/// <param name="stateBlending">- Allows the interpolation of variables to compensate stutter due to difference in System Framerates.</param>
void Draw(sf::RenderWindow* window, const float stateBlending) override;
/// <summary>
/// Sets the (fill) color of the rectangle.
/// </summary>
/// <param name="position">- The new color.</param>
void SetColor(const Color& position) override;
/// <summary>
/// Gets the (fill) color of the rectangle.
/// </summary>
const Color& GetColor() const override;
/// <summary>
/// Sets the size of the rectangle.
/// </summary>
/// <param name="size">- The new size in pixels.</param>
void SetSize(const Vector2& size);
/// <summary>
/// Gets the current size of the rectangle.
/// </summary>
const Vector2& GetSize() const;
/// <summary>
/// Transforms the rectangle, e.g. moves it with it's current velocity.
/// </summary>
/// <param name="fixedDeltaTime">- The fixed time step used for the transformation calculation.</param>
void Transform(const float fixedDeltaTime) override;
/// <summary>
/// Sets the position of the rectangle. This is instant, no interpolation will be applied.
/// </summary>
/// <param name="position">- The new position of the rectangle in pixels.</param>
void SetPosition(const Vector2& position) override;
/// <summary>
/// Gets the current position of the rectangle.
/// </summary>
const Vector2& GetPosition() const override;
/// <summary>
/// Sets the velocity of the rectangle.
/// </summary>
/// <param name="velocity">- The new velocity in pixels per second.</param>
void SetVelocity(const Vector2& velocity) override;
/// <summary>
/// Gets the current velocity of the rectangle.
/// </summary>
const Vector2& GetVelocity() const override;
private:
// The position of rectangle from the last frame.
Vector2 m_previousPosition;
// The current position of the rectangle.
Vector2 m_position;
// The velocity of the rectangle.
Vector2 m_velocity;
// The size of the rectangle.
Vector2 m_size;
// The (fill) color of the rectangle.
Color m_color;
// The internal SFML rectangle element.
sf::RectangleShape m_shape;
};
}
|
Java | UTF-8 | 1,900 | 2.28125 | 2 | [
"MIT"
] | permissive | package com.dstym.pharmaciesondutyattica.service;
import com.dstym.pharmaciesondutyattica.entity.Pharmacy;
import com.dstym.pharmaciesondutyattica.repository.PharmacyRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class PharmacyService {
private final PharmacyRepository pharmacyRepository;
@Cacheable(value = "pharmacyCache", key = "#theId")
public Pharmacy findById(Integer theId) {
var result = pharmacyRepository.findById(theId);
Pharmacy pharmacy;
if (result.isPresent()) {
pharmacy = result.get();
} else {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Did not find pharmacy with id: " + theId);
}
return pharmacy;
}
@Cacheable(value = "pharmaciesCache", key = "{#region, #pageable}")
public Page<Pharmacy> findAll(String region, Pageable pageable) {
region = Optional.ofNullable(region)
.map(r -> URLDecoder.decode(r.trim(), StandardCharsets.UTF_8))
.orElse(null);
var result = pharmacyRepository.findAll(region, pageable);
if (result.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Did not find pharmacies.");
}
return result;
}
public void save(Pharmacy pharmacy) {
pharmacyRepository.save(pharmacy);
}
public void deleteById(Integer theId) {
pharmacyRepository.deleteById(theId);
}
}
|
Python | UTF-8 | 1,164 | 3.84375 | 4 | [] | no_license |
'''
求出1~n的整数中1出现的次数?
1~13中包含1的数字有1、10、11、12、13因此共出现6次。
'''
class solution(object):
def frequence(self, num):
if type(num) != int or num < 1:
return None
num1 = num // 10
list1 = [num%10]
while num1 != 0:
num = num1
num1 = num1 //10
list1.append(num%10)
fre = 0
for i in range(1,len(list1)):
fre1 = 0
for j in range(i, len(list1)):
fre1 = fre1 + list1[j]*(10**(j-i))
if list1[i-1] < 1:
fre = fre + fre1
elif list1[i-1] == 1:
for j in range(i-1):
fre = fre + list1[j]*(10**j)
fre = fre + 1 + fre1*10**(i-1)
else:
fre = fre + (fre1+1)*10**(i-1)
if list1[i] < 1:
fre = fre
elif list1[i] == 1:
for j in range(i):
fre = fre + list1[j]*(10**j)
fre = fre + 1 + fre1*10**(i-1)
else:
fre = fre + 10**i
return fre
s = solution()
print(s.frequence(2134))
|
Python | UTF-8 | 805 | 3.84375 | 4 | [] | no_license | # -*- codign: itf-8 -*-
def char_not_repeat(word):
chars ={}
for i, char in enumerate(word):
if char not in chars:
chars[char] = (i,1)
else:
chars[char] = (chars[char][0],chars[char][1]+1)
final_chars = []
for key, value in chars.items():
if value[1]== 1:
final_chars.append((key,value[0]))
not_repeat_char = sorted(final_chars,key = lambda value:value[1])
if not_repeat_char:
return not_repeat_char[0][0]
else:
return '_'
if __name__ == '__main__':
word = str(input('Ingresa una palabra: '))
result = char_not_repeat(word)
if result == '_':
print('Todas las letras se repiten')
else:
print('El primer caracter no repetido es: {}'.format(result)) |
Markdown | UTF-8 | 2,815 | 3.640625 | 4 | [] | no_license | ## leetcode 91. Decode Ways
A message containing letters from A-Z is being encoded to numbers using the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Given a non-empty string containing only digits, determine the total number of ways to decode it.
The answer is guaranteed to fit in a 32-bit integer.
Example 1:
Input: s = "12"
Output: 2
Explanation: It could be decoded as "AB" (1 2) or "L" (12).
Example 2:
Input: s = "226"
Output: 3
Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
Example 3:
Input: s = "0"
Output: 0
Explanation: There is no character that is mapped to a number starting with '0'. We cannot ignore a zero when we face it while decoding. So, each '0' should be part of "10" --> 'J' or "20" --> 'T'.
Example 4:
Input: s = "1"
Output: 1
Constraints:
1 <= s.length <= 100
s contains only digits and may contain leading zero(s).
### Solution
- 使用dynamic programming,考虑当前位的数字str.charAt(i)与i-1位的数字是否能够组成一个介于(10, 26]之间的数值,如果可以的话,当前位的结果应该是memo[i-1] + memo[i-2] (不是memo[i-1] + 1)
- 由于可能需要取memo[i-2]的值,需要一个memo[0]的offset,且 i 对应的值为从1开始的序列值
- 这道题的edge cases全部与0有关
- “0123” 结果应该是0,所以对于memo[0]的取值要观察首位是否为0
- “2310” memo[4]的值应该等于memo[2]的值
- “2301” 结果应该是0,因为0不能mapping到任何字母上,30也不能
- "23001" 结果应该为0
- 所以我们应该以当前digit得到的数值是否为0,进而分别考虑memo[i]的取值
```java
class Solution {
//time complexity O(N) || space complexity O(N)
public int numDecodings(String s) {
int N = s.length();
if(s == null || N == 0)
return 0;
int[] memo = new int[N + 1];
// consider if the first character is zero
memo[0] = s.charAt(0) == '0' ? 0 : 1;
memo[1] = memo[0];
for(int i = 2; i <= N; i++){
String digit1 = s.substring(i - 1, i);
//two digits number
String digit2 = s.substring(i - 2, i);
int val1 = Integer.valueOf(digit1);
int val2 = Integer.valueOf(digit2);
if(val1 != 0){
if(val2 > 10 && val2 <=26)
memo[i] = memo[i - 1] + memo[i - 2];
else
memo[i] = memo[i - 1];
}else{
//the most significant bit cannot be zero; the value of two bit digits cannot be greater than 20
if(val2 > 20 || val2 == 0)
return 0;
else
memo[i] = memo[i - 2];
}
}
return memo[N];
}
}
```
|
C++ | UTF-8 | 2,672 | 3.34375 | 3 | [
"BSD-3-Clause"
] | permissive | #ifndef _VECTOR3_H_
#define _VECTOR3_H_
#include <math.h>
// added by sidmishraw
// #include <iostream>
// using namespace std;
class Vector3 {
public:
Vector3(){};
Vector3(float x, float y, float z) {
d[0] = x;
d[1] = y;
d[2] = z;
}
Vector3(const Vector3 &v) {
d[0] = v.d[0];
d[1] = v.d[1];
d[2] = v.d[2];
}
float x() const { return d[0]; }
float y() const { return d[1]; }
float z() const { return d[2]; }
float operator[](int i) const { return d[i]; }
float length() const { return sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); }
void normalize() {
float temp = length();
if (temp == 0.0) return; // 0 length vector
// multiply by 1/magnitude
temp = 1 / temp;
d[0] *= temp;
d[1] *= temp;
d[2] *= temp;
}
/////////////////////////////////////////////////////////
// Overloaded operators
/////////////////////////////////////////////////////////
Vector3 operator+(const Vector3 &op2) const { // vector addition
return Vector3(d[0] + op2.d[0], d[1] + op2.d[1], d[2] + op2.d[2]);
}
Vector3 operator-(const Vector3 &op2) const { // vector subtraction
return Vector3(d[0] - op2.d[0], d[1] - op2.d[1], d[2] - op2.d[2]);
}
Vector3 operator-() const { // unary minus
return Vector3(-d[0], -d[1], -d[2]);
}
Vector3 operator*(float s) const { // scalar multiplication
return Vector3(d[0] * s, d[1] * s, d[2] * s);
}
void operator*=(float s) {
d[0] *= s;
d[1] *= s;
d[2] *= s;
}
Vector3 operator/(float s) const { // scalar division
return Vector3(d[0] / s, d[1] / s, d[2] / s);
}
float operator*(const Vector3 &op2) const { // dot product
return d[0] * op2.d[0] + d[1] * op2.d[1] + d[2] * op2.d[2];
}
Vector3 operator^(const Vector3 &op2) const { // cross product
return Vector3(d[1] * op2.d[2] - d[2] * op2.d[1], d[2] * op2.d[0] - d[0] * op2.d[2],
d[0] * op2.d[1] - d[1] * op2.d[0]);
}
bool operator==(const Vector3 &op2) const { return (d[0] == op2.d[0] && d[1] == op2.d[1] && d[2] == op2.d[2]); }
bool operator!=(const Vector3 &op2) const { return (d[0] != op2.d[0] || d[1] != op2.d[1] || d[2] != op2.d[2]); }
bool operator<(const Vector3 &op2) const {
// added by sidmishraw
// cout << "d = " << d[0] << " " << d[1] << " " << d[2] << endl;
// cout << "op2 = " << op2.d[0] << " " << op2.d[1] << " " << op2.d[2] <<
// endl;
return (d[0] < op2.d[0] && d[1] < op2.d[1] && d[2] < op2.d[2]);
}
bool operator<=(const Vector3 &op2) const { return (d[0] <= op2.d[0] && d[1] <= op2.d[1] && d[2] <= op2.d[2]); }
private:
float d[3];
};
#endif // _VECTOR3_H_
|
Shell | UTF-8 | 6,915 | 3.453125 | 3 | [] | no_license | #!/bin/bash
# run.sh <corpus name>
# check the number of lines in the output, in case script failed
function check {
if [ `wc -l ../tmp/$1/$2 | awk '{print $1}'` -ne `wc -l ../../corpora/$1/$1.token | awk '{print $1}'` ]
then
echo "Truncated file - $3 failed."
popd > /dev/null
exit
fi
}
BASEDIR=$(dirname $0)
pushd $BASEDIR > /dev/null
mkdir ../tmp/$1
./fixHyphen.pl ../../corpora/$1/$1.token > ../tmp/$1/hyphen.txt
check $1 "hyphen.txt" "fixHyphen.pl"
./fixThough.pl ../tmp/$1/hyphen.txt > ../tmp/$1/though.txt
check $1 "though.txt" "fixThough.pl"
awk -F'\t' '{print $1}' ../tmp/$1/though.txt > ../tmp/$1/url.txt
awk -F'\t' '{print $2}' ../tmp/$1/though.txt > ../tmp/$1/sent.txt
./fixPunct.pl ../tmp/$1/sent.txt > ../tmp/$1/punct.txt
check $1 "punct.txt" "fixPunct.pl"
./fixNumbers.pl ../tmp/$1/punct.txt > ../tmp/$1/numbers.txt
check $1 "numbers.txt" "fixNumbers.pl"
./postag.sh ../tmp/$1/numbers.txt > ../tmp/$1/pos.txt
check $1 "pos.txt" "Tagger"
./fixWatch.pl ../tmp/$1/pos.txt > ../tmp/$1/watch.txt
check $1 "watch.txt" "fixWatch.pl"
./fixUH.pl ../tmp/$1/watch.txt > ../tmp/$1/UH.txt
check $1 "UH.txt" "fixUH.pl"
./fixing.pl ../tmp/$1/UH.txt > ../tmp/$1/ing.txt
check $1 "ing.txt" "fixing.pl"
./fixPPngram.pl ../tmp/$1/ing.txt > ../tmp/$1/ngram.txt
check $1 "ngram.txt" "fixPPngram.pl"
./fixStandNN.pl ../tmp/$1/ngram.txt 1> ../tmp/$1/stand.txt 2> ../tmp/$1/stand.log
check $1 "stand.txt" "fixStandNN.pl"
./fixIs.pl ../tmp/$1/stand.txt 1> ../tmp/$1/is.txt 2> ../tmp/$1/is.log
check $1 "is.txt" "fixIs.pl"
./forcePOS.pl ../tmp/$1/is.txt > ../tmp/$1/force.txt
check $1 "force.txt" "forcePOS.pl"
./fixNotDT-V.pl ../tmp/$1/force.txt > ../tmp/$1/notdt.txt
check $1 "notdt.txt" "fixNotDT-V.pl"
./fixBuilding.pl ../tmp/$1/notdt.txt > ../tmp/$1/building.txt
check $1 "building.txt" "fixBuilding.pl"
./fixTO-VBX.pl ../tmp/$1/building.txt > ../tmp/$1/to-vbx.txt
check $1 "to-vbx.txt" "fixTO-VBX.pl"
./fixV-TO.pl ../tmp/$1/to-vbx.txt > ../tmp/$1/v-to.txt
check $1 "v-to.txt" "fixV-TO.pl"
./fixTO-VB.pl ../tmp/$1/v-to.txt > ../tmp/$1/to-vb.txt
check $1 "to-vb.txt" "fixTO-VB.pl"
./fixAttempt.pl ../tmp/$1/to-vb.txt > ../tmp/$1/attempt.txt
check $1 "attempt.txt" "fixAttempt.pl"
./fixVerbPP.pl ../tmp/$1/attempt.txt > ../tmp/$1/vpp.txt
check $1 "vpp.txt" "fixVerbPP.pl"
./fixConverse.pl ../tmp/$1/vpp.txt > ../tmp/$1/cnv.txt
check $1 "cnv.txt" "fixConverse.pl"
./fixWearing.pl ../tmp/$1/cnv.txt > ../tmp/$1/wear.txt
check $1 "wear.txt" "fixWearing.pl"
./fixSled.pl ../tmp/$1/wear.txt 1> ../tmp/$1/sled.txt 2> ../tmp/$1/sled.log
check $1 "sled.txt" "fixSled.pl"
./fixSign.pl ../tmp/$1/sled.txt > ../tmp/$1/sign.txt
check $1 "sign.txt" "fixSign.pl"
./fixDown.pl ../tmp/$1/sign.txt > ../tmp/$1/down.txt
check $1 "down.txt" "fixDown.pl"
./joinCompoundNouns.pl ../tmp/$1/down.txt > ../tmp/$1/njoin.txt
check $1 "njoin.txt" "joinCompoundNouns.pl"
./fixLeft.pl ../tmp/$1/njoin.txt > ../tmp/$1/left.txt
check $1 "left.txt" "fixLeft.pl"
./joinCompoundVerbs.pl ../tmp/$1/left.txt > ../tmp/$1/vjoin.txt
check $1 "vjoin.txt" "joinCompoundVerbs.pl"
./chunker.sh ../tmp/$1/vjoin.txt > ../tmp/$1/chunk.txt
check $1 "chunk.txt" "chunker.sh"
./splitCompoundVerbs.pl ../tmp/$1/left.txt ../tmp/$1/chunk.txt > ../tmp/$1/vsplit.txt
check $1 "vsplit.txt" "splitCompoundVerbs.pl"
./splitCompoundNouns.pl ../tmp/$1/vsplit.txt > ../tmp/$1/nsplit.txt
check $1 "nsplit.txt" "splitCompoundNouns.pl"
./makePPngram.pl ../tmp/$1/nsplit.txt > ../tmp/$1/tried.txt
check $1 "tried.txt" "makePPngram.pl"
./fixInOrderTo.pl ../tmp/$1/tried.txt > ../tmp/$1/inorder.txt
check $1 "inorder.txt" "fixInOrderTo.pl"
./fixSbar.pl ../tmp/$1/inorder.txt > ../tmp/$1/sbar.txt
check $1 "sbar.txt" "fixSbar.pl"
./fixNPHeadNouns.pl ../tmp/$1/sbar.txt 1> ../tmp/$1/hnoun.txt 2> ../tmp/$1/hnoun.log
check $1 "hnoun.txt" "fixNPHeadNouns.pl"
./fixNPHeadNouns2.pl ../tmp/$1/hnoun.txt 1> ../tmp/$1/hnoun2.txt 2> ../tmp/$1/hnoun2.log
check $1 "hnoun2.txt" "fixNPHeadNouns2.pl"
./fixDressed.pl ../tmp/$1/hnoun2.txt 1> ../tmp/$1/dress.txt 2> ../tmp/$1/dress.log
check $1 "dress.txt" "fixDressed.pl"
./fixCooks.pl ../tmp/$1/dress.txt > ../tmp/$1/cooks.txt
check $1 "cooks.txt" "fixCooks.pl"
./fixShop.pl ../tmp/$1/cooks.txt > ../tmp/$1/shop.txt
check $1 "shop.txt" "fixShop.pl"
./fixVPaux.pl ../tmp/$1/shop.txt > ../tmp/$1/vpaux.txt
check $1 "vpaux.txt" "fixVPaux.pl"
./fixTO.pl ../tmp/$1/vpaux.txt > ../tmp/$1/to.txt
check $1 "to.txt" "fixTO.pl"
./normDobj.pl ../tmp/$1/to.txt > ../tmp/$1/dobj.txt
check $1 "dobj.txt" "normDobj.pl"
./fixWearingChunk.pl ../tmp/$1/dobj.txt 1> ../tmp/$1/wearchunk.txt 2> ../tmp/$1/wearchunk.log
check $1 "wearchunk.txt" "fixWearingChunk.pl"
./fixDetHead.pl ../tmp/$1/wearchunk.txt > ../tmp/$1/dthead.txt
check $1 "dthead.txt" "fixDetHead.pl"
./fixToPerform.pl ../tmp/$1/dthead.txt > ../tmp/$1/perform.txt
check $1 "perform.txt" "fixToPerform.pl"
./fixLay.pl ../tmp/$1/perform.txt > ../tmp/$1/lay.txt
check $1 "lay.txt" "fixLay.pl"
./breakCC-NPs.pl ../tmp/$1/lay.txt > ../tmp/$1/break.txt
check $1 "break.txt" "breakCC-NPs.pl"
./fixRefVerbs.pl ../tmp/$1/break.txt > ../tmp/$1/ref1.txt
check $1 "ref1.txt" "fixRefVerbs.pl"
./fixRefVerbs.pl ../tmp/$1/ref1.txt > ../tmp/$1/ref2.txt
check $1 "ref2.txt" "fixRefVerbs.pl"
./fixVerbs.pl ../tmp/$1/ref2.txt > ../tmp/$1/verbs1.txt
check $1 "verbs1.txt" "fixVerbs.pl"
./fixPlay.pl ../tmp/$1/verbs1.txt > ../tmp/$1/play.txt
check $1 "play.txt" "fixPlay.pl"
./fixVerbs.pl ../tmp/$1/play.txt > ../tmp/$1/verbs2.txt
check $1 "verbs2.txt" "fixVerbs.pl"
./fixWhile.pl ../tmp/$1/verbs2.txt > ../tmp/$1/while.txt
check $1 "while.txt" "fixWhile.pl"
./fixQuotes.pl ../tmp/$1/while.txt > ../tmp/$1/quote.txt
check $1 "quote.txt" "fixQuotes.pl"
./fixVP-RB.pl ../tmp/$1/quote.txt > ../tmp/$1/vp-rb.txt
check $1 "vp-rb.txt" "fixVP-RB.pl"
./fixPRP-VP.pl ../tmp/$1/vp-rb.txt > ../tmp/$1/vp-prp.txt
check $1 "vp-prp.txt" "fixPRP-VP.pl"
./fixPrt.pl ../tmp/$1/vp-prp.txt > ../tmp/$1/prt.txt
check $1 "prt.txt" "fixPrt.pl"
./fixPP-Prt.pl ../tmp/$1/prt.txt > ../tmp/$1/pp-prt.txt
check $1 "pp-prt.txt" "fixPP-Prt.pl"
./fixDetHead.pl ../tmp/$1/pp-prt.txt > ../tmp/$1/dthead2.txt
check $1 "dthead2.txt" "fixDetHead.pl"
./fixSomeX.pl ../tmp/$1/dthead2.txt > ../tmp/$1/some.txt
check $1 "some.txt" "fixSomeX.pl"
./breakVPs.pl ../tmp/$1/some.txt > ../tmp/$1/breakVP.txt
check $1 "breakVP.txt" "breakVPs.pl"
./fixTO-end.pl ../tmp/$1/breakVP.txt > ../tmp/$1/to-end.txt
check $1 "to-end.txt" "fixTO-end.pl"
./fixVPVP-TO.pl ../tmp/$1/to-end.txt > ../tmp/$1/vpvp-to.txt
check $1 "vpvp-to.txt" "fixVPVP-TO.pl"
./fixFunction.pl ../tmp/$1/vpvp-to.txt > ../tmp/$1/function.txt
check $1 "function.txt" "fixFunction.pl"
./fixPP-CC.pl ../tmp/$1/function.txt > ../tmp/$1/pp-cc.txt
check $1 "pp-cc.txt" "fixPP-CC.pl"
./checkPunctTag.pl ../tmp/$1/pp-cc.txt > ../tmp/$1/punct.check
../../misc/splice.pl ../tmp/$1/url.txt ../tmp/$1/pp-cc.txt > ../../corpora/$1/$1.pos
#./makeChunk.pl ../../tmp/$1.pos > ../../tmp/$1.chunk
popd > /dev/null
|
Python | UTF-8 | 661 | 2.5625 | 3 | [] | no_license | # -*- coding: UTF-8 -*-
def generator(weibo_list,username,city,time):
totalNumber = 0
relatedNumber = 0
valid_list = ['新型病毒','疫情','确诊','肺炎','隔离']
for weibo in weibo_list:
totalNumber = totalNumber + 1
content = weibo['content']
for word in valid_list:
if word in content:
relatedNumber = relatedNumber + 1
break
result = []
result.append(username)
result.append(city)
result.append(time)
result.append(str(totalNumber))
result.append(str(relatedNumber))
result.append(str(relatedNumber/totalNumber * 100))
return result |
Java | UTF-8 | 423 | 1.609375 | 2 | [] | no_license | package com.sce.persistence.exemplar.analise.especie.repository;
import org.springframework.data.repository.CrudRepository;
import com.sce.persistence.exemplar.analise.especie.entity.ExemplarAnaliseEspecie;
import com.sce.persistence.exemplar.analise.especie.entity.ExemplarAnaliseEspecieId;
public interface ExemplarAnaliseEspecieRepository extends CrudRepository<ExemplarAnaliseEspecie, ExemplarAnaliseEspecieId> {
}
|
Java | UTF-8 | 778 | 2.09375 | 2 | [] | no_license | package com.rainbow.gray.framework.example.service.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@FeignClient(value = "discovery-springcloud-example-a")
// Context-patch一旦被设置,在Feign也要带上context-path,外部Postman调用网关或者服务路径也要带context-path
// @FeignClient(value = "discovery-springcloud-example-a", path = "/nepxion")
// @FeignClient(value = "discovery-springcloud-example-a/nepxion")
public interface AFeign {
@RequestMapping(path = "/invoke", method = RequestMethod.POST)
String invoke(@RequestBody String value);
} |
Markdown | UTF-8 | 585 | 2.703125 | 3 | [] | no_license | # ROCK-PAPER-SCISSOR-PROJECT
# rock-paper-scissors
An AI to play the Rock Paper Scissors game
## Requirements
- Python 3
- Keras
- Tensorflow
- OpenCV
Install the dependencies
```sh
$ pip install -r versions.txt
```
Gather Images for each gesture (rock, paper and scissors and None):
In this example, we gather 200 images for the "rock" gesture
```sh
$ python3 gather_images.py rock 200
```
Train the model
```sh
$ python3 train.py
```
Test the model on some images
```sh
$ python3 test.py <path_to_test_image>
```
Play the game with your computer!
```sh
$ python3 play.py
```
|
Python | UTF-8 | 214 | 3.015625 | 3 | [] | no_license | import numpy as np
from matplotlib import pyplot as plt
a = np.array([20,76,25,32,33,12,23,67,4,8,78,9,34,74,2,0])
plt.hist(a, bins = [0,20,40,60,80]) # hist = Histogram
plt.title("Histogram") # Title
plt.show() |
C++ | UTF-8 | 2,560 | 3.625 | 4 | [] | no_license | #pragma once
// This is our 2D point class. This will be used to store the UV coordinates.
class CVector2
{
public:
float x, y;
CVector2();
};
// This is our 3D point class. This will be used to store the vertices of our model.
class CVector3
{
public:
float x, y, z;
CVector3();
CVector3(float _x, float _y, float _z)
{
x = _x;
y = _y;
z = _z;
}
CVector3(const CVector3& vector)
{
x = vector.x;
y = vector.y;
z = vector.z;
}
CVector3(CVector3& vector1, CVector3& vector2)
{
x = vector1.x - vector2.x; // Subtract point1 and point2 x's
y = vector1.y - vector2.y; // Subtract point1 and point2 y's
z = vector1.z - vector2.z; // Subtract point1 and point2 z's
}
CVector3& Normalize()
{
double Magnitude = sqrt(x * x + y * y + z * z); // Get the magnitude
x /= (float)Magnitude; // Divide the vector's X by the magnitude
y /= (float)Magnitude; // Divide the vector's Y by the magnitude
z /= (float)Magnitude; // Divide the vector's Z by the magnitude
return *this; // Return the normal
}
friend CVector3 operator +(const CVector3& vector1, const CVector3& vector2);
friend CVector3 operator *(CVector3& vector1, float value);
friend CVector3 operator /(CVector3& vector1, float value);
};
inline CVector3 Cross(CVector3& vVector1, CVector3& vVector2)
{
CVector3 vCross; // The vector to hold the cross product
// Get the X value
vCross.x = ((vVector1.y * vVector2.z) - (vVector1.z * vVector2.y));
// Get the Y value
vCross.y = ((vVector1.z * vVector2.x) - (vVector1.x * vVector2.z));
// Get the Z value
vCross.z = ((vVector1.x * vVector2.y) - (vVector1.y * vVector2.x));
return vCross; // Return the cross product
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// This adds 2 vectors together and returns the result
inline CVector3 operator+(CVector3& vVector1, CVector3& vVector2)
{
// Return the resultant vector
return CVector3(vVector2.x + vVector1.x, vVector2.y + vVector1.y, vVector2.z + vVector1.z);
}
inline CVector3 operator/(CVector3& vVector1, float value)
{
// Return the resultant vector
return CVector3(vVector1.x / value, vVector1.y / value, vVector1.z / value);
}
inline CVector3 operator*(CVector3& vVector1, float value)
{
// Return the resultant vector
return CVector3(vVector1.x * value, vVector1.y * value, vVector1.z * value);
}
|
JavaScript | UTF-8 | 279 | 3.15625 | 3 | [] | no_license | const comp = (array1, array2) =>
array1 === null || array2 === null
? false
: array2.sort((a, b) => a - b).length ===
array1
.map((el) => el ** 2)
.sort((a, b) => a - b)
.filter((el, i) => el === array2[i]).length;
module.exports = comp;
|
C++ | UTF-8 | 776 | 3.328125 | 3 | [
"MIT"
] | permissive | /*Complete the code here.
Node is as follows:
struct Node
{
int data;
Node* left;
Node* right;
};
*/
int find(int in[], int key, int start, int end){
for(int i = start; i <= end; i++){
if(in[i] == key){
return i;
}
}
return -1;
}
Node* make(int in[], int pre[], int inS, int inE, int& i){
if(inS > inE){
return NULL;
}
int index = find(in, pre[i], inS, inE);
Node* root = new Node();
root->data = pre[i];
i++;
root->left = make(in, pre, inS, index-1, i);
root->right = make(in, pre, index+1, inE, i);
return root;
}
Node* buildTree(int in[],int pre[], int inStrt, int inEnd)
{
//add code here.;
int index = 0;
return make(in, pre, inStrt, inEnd, index);
}
|
Java | UTF-8 | 1,510 | 2.546875 | 3 | [] | no_license | package com.cdk.assignment.billcalculation;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.cdk.assignment.billcalculation.service.DiscountService;
import com.cdk.assignment.exceptions.InvalidAmountException;
@SpringBootApplication
public class BillCalculationApplication implements CommandLineRunner {
public static void main(String[] args) {
//SpringApplication.run(BillCalculationApplication.class, args);
SpringApplication app = new SpringApplication(BillCalculationApplication.class);
//app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
@Override
public void run(String... args) throws InvalidAmountException {
try{
if (args.length > 0 ) {
if(Double.parseDouble(args[0])>0) {
System.out.println("Final Bill amount : "+ new DiscountService().calculateBillAmt(Double.parseDouble(args[0])));
}
else{
throw new InvalidAmountException(args[0]);
}
}
}
catch(NumberFormatException exp){
System.out.println("Catch Block") ;
throw new NumberFormatException("Invalid Purchase Amount : "+args[0]+" Entered");
}
catch(InvalidAmountException exp){
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.