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 |
|---|---|---|---|---|---|---|---|
Swift | UTF-8 | 1,300 | 2.671875 | 3 | [] | no_license | //
// JPPresentationController.swift
// JPWB
//
// Created by KC on 16/10/11.
// Copyright © 2016年 KC. All rights reserved.
//
import UIKit
class JPPresentationController: UIPresentationController {
//MARK: - 懒加载
lazy var coverView: UIView = UIView()
var presentViewFrame = CGRect.zero
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
//1.设置弹出来的View的frame
presentedView?.frame = presentViewFrame
print(presentedViewController.view, presentedView)
//2.添加蒙版
setupCoverView()
}
}
extension JPPresentationController {
fileprivate func setupCoverView() {
coverView.frame = containerView!.bounds
coverView.backgroundColor = UIColor(white: 0.8, alpha: 0.1)
//监听蒙版点击
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissModalView))
coverView.addGestureRecognizer(tap)
containerView?.insertSubview(coverView, belowSubview: presentedView!)
}
}
extension JPPresentationController {
@objc fileprivate func dismissModalView() {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
|
Python | UTF-8 | 1,956 | 3.046875 | 3 | [] | no_license | import math
def func(x):
return math.pow(math.e, x)*math.sin(3*x)
a = 1.0
b = 3.0
tmax = 5.0
c = 0.8
Nt , Nx = 30 , 30
delta_X = (b-a)/Nx;
delta_T = tmax/Nt;
Uapp_1 , Uapp_2 , Uapp_3 , Uapp_4 = [[0] * Nx for i in range(Nx)] , [[0] * Nx for i in range(Nx)] , [[0] * Nx for i in range(Nx)] , [[0] * Nx for i in range(Nx)]
sum1 , sum2 , sum3 , sum4 = 0 , 0 , 0 , 0
Uex = [[0] * 100 for i in range(100)]
x = [0]*100
t = [0]*100
for i in range(0,Nx):
x[i] = a +(i*delta_X)
for j in range(0,Nx):
t[j] = (j*delta_T)
for i in range(0,Nx):
for j in range(0,Nx):
Uex[i][j] = func(x[i] - c*t[j])
for i in range(0,Nx):
Uapp_1[i][0] = func(x[i])
for i in range(0,Nx):
Uapp_2[i][0] = func(x[i])
for i in range(0,Nx):
Uapp_3[i][0] = func(x[i])
for i in range(0,Nx):
Uapp_4[i][0] = func(x[i])
#Formulas
for i in range(0,Nx-1):
for j in range(0,Nt-1):
Uapp_1[i][j+1] = Uapp_1[i][j] - (c*(Uapp_1[i+1][j] - Uapp_1[i][j])*(delta_T/delta_X))
for i in range(0,Nx-1):
for j in range(0,Nt-1):
Uapp_2[i][j+1] = Uapp_2[i][j] - (c*(Uapp_2[i][j] - Uapp_2[i-1][j])*(delta_T/delta_X))
for i in range(0,Nx-1):
for j in range(0,Nt-1):
Uapp_3[i][j+1] = Uapp_3[i][j] - (c*delta_T/(2.0*delta_X)*(Uapp_3[i+1][j] - Uapp_3[i-1][j]))
for i in range(0,Nx-1):
for j in range(0,Nt-1):
Uapp_4[i][j+1] = ((Uapp_4[i+1][j] + Uapp_4[i-1][j])/2) -(c*delta_T/(2.0*delta_X)*(Uapp_4[i+1][j] - Uapp_4[i-1][j]))
#MA
for i in range(0,Nx-1):
delta1 = abs(Uex[i][1] - Uapp_1[i][1])
sum1 += delta1
Ma1 = sum1/Nx
for i in range(0,Nx-1):
delta2 = abs(Uex[i][1] - Uapp_2[i][1])
sum2 += delta2
Ma2 = sum2/Nx
for i in range(0,Nx-1):
delta3 = abs(Uex[i][1] - Uapp_3[i][1])
sum3 += delta3
Ma3 = sum3/Nx
for i in range(0,Nx-1):
delta4 = abs(Uex[i][1] - Uapp_4[i][1])
sum4 += delta4
Ma4 = sum4/Nx
print("Math expect for 1st method:" , Ma1)
print("Math expect for 2nd method:" , Ma2)
print("Math expect for 3rd method:" , Ma3)
print("Math expect for 4th method:" , Ma4)
|
Ruby | UTF-8 | 679 | 3.328125 | 3 | [] | no_license | # encoding: UTF-8
class MinimizeHeterogeneity
def self.calculate_value(board, player)
# The putahi doesn't matter here, since it's not next
# any other piece.
(1..8).inject(0) do |total, spot|
# If the piece belongs to the current player
if board.get_string_value(board.get_piece(spot)) == player
prev = board.get_string_value(board.get_previous(spot))
nex = board.get_string_value(board.get_next(spot))
# Decrement total for each piece the
# enne my ahs close to the current player's
# one.
total += prev == player ? 1 : 0
total += nex == player ? 1 : 0
end
total
end
end
end
|
Python | UTF-8 | 1,105 | 2.953125 | 3 | [] | no_license | from collections import defaultdict, deque
def findConnected(n, d):
result = []
unvisited = set(range(1, n+1))
while unvisited:
n = unvisited.pop()
group = {n}
queue = deque()
queue.append(n)
while queue:
curr = queue.popleft()
neighbors = d[curr]
unvisited -= neighbors
group = group.union(neighbors)
queue.extend(neighbors - group)
result.append(group)
return result
def solve():
n, l, k = map(int, input().split())
d = defaultdict(set)
for _ in range(l):
a, b = map(int, input().split())
d[a].add(b)
d[b].add(a)
components = findConnected(n, d)
components.sort(key=len)
connections = 0
for comp in components:
connections += len(comp) - 1
for _ in range(min(len(components) - 1, k)):
connections += len(components[0]) * len(components[1])
temp = components.pop(0)
components[0] = components[0].union(temp)
print(connections)
c = int(input())
while (c):
solve()
c -= 1
|
Rust | UTF-8 | 203 | 2.90625 | 3 | [] | no_license | use std::ffi::OsStr;
pub fn getString(strr: Option<&OsStr>) -> String {
let res = match strr.unwrap().to_str() {
Some(n) => { String::from(n) }
_ => String::from("")
};
res
} |
C++ | UTF-8 | 1,464 | 3.1875 | 3 | [] | no_license | /**
* \file Ouvrage.cpp
* \brief Implémentation de la classe Ouvrage dérivée de Reference
* \author Vincent Breault
* \date
*/
#include "Ouvrage.h"
using namespace std;
using namespace biblio;
/**
* \brief Constructeur avec paramètre, Construction d'un objet Ouvrage à partir des valeurs passées en paramètre
* @param auteurs
* @param titre
* @param identifiant
* @param annee
* @param editeur
* @param ville
*/
Ouvrage::Ouvrage(const string auteurs, const std::string titre,
const std::string identifiant, const int annee, const std::string ville,
const std::string editeur) : biblio::Reference(auteurs, titre, identifiant, annee)
{
PRECONDITION(util::validerFormatNom(ville));
PRECONDITION(util::validerFormatNom(editeur));
if (util::validerFormatNom(editeur) && util::validerFormatNom(ville))
{
m_editeur = editeur;
m_ville = ville;
} else cout << "Erreur du constructeur de Ouvrage mon excellent ami" << endl;
POSTCONDITION(m_ville == ville);
POSTCONDITION(m_editeur == editeur);
INVARIANTS();
}
/**
* \brief Génère un objet string formaté
* @return Ouvrage formaté
*/
std::string Ouvrage::reqReferenceFormate() const{
ostringstream os;
os << m_auteurs << ". " << m_titre << ". "<<
m_ville << " : " << m_editeur <<", " <<
m_annee << ". " << m_identifiant << ".";
return os.str();
}
void Ouvrage::verifieInvariant() const
{
INVARIANT(util::validerFormatNom(m_ville));
INVARIANT(util::validerFormatNom(m_editeur));
}
|
Java | UTF-8 | 2,387 | 2.15625 | 2 | [] | no_license | package com.metatechcraft.liquid;
import java.util.IdentityHashMap;
import com.forgetutorials.lib.registry.DescriptorFluid;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.FluidContainerRegistry;
import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData;
import net.minecraftforge.fluids.FluidStack;
public class MetaLiquids {
public static Material metaLiquidMaterial = new MaterialMetaLiquid();
public static MetaLiquidContainer metaLiquidContainer;
public static final String[] metaFluidNames = new String[] { "MetaWhite", "MetaBlack", "MetaGreen", "MetaBlue", "MetaRed" };
public static DescriptorFluid[] metaFluids = new DescriptorFluid[32];
public static IdentityHashMap<Block, DescriptorFluid> blockToFluid = new IdentityHashMap<Block, DescriptorFluid>();
public static void initize() {
MetaLiquids.metaLiquidContainer = new MetaLiquidContainer(26648);
// empty
//ItemStack emptyLiquidContainerStack = new ItemStack(MetaLiquids.metaLiquidContainer, 1, 0);
// LanguageRegistry.addName(emptyLiquidContainerStack,
// MetaLiquidContainer.getDisplayName(emptyLiquidContainerStack));
// liquids
for (int i = 0; i < MetaLiquids.metaFluidNames.length; i++) {
DescriptorFluid descriptorFluid = DescriptorFluid.newFluid(MetaLiquids.metaFluidNames[i], 12, 3000, 6000);
Block liquidBlock = new MetaLiquid(descriptorFluid, MetaLiquids.metaFluidNames[i]);
ItemStack metaLiquidStack = new ItemStack(liquidBlock);
String unlocalizedName = MetaLiquids.metaFluidNames[i].replaceAll("[^a-zA-Z]", "");
descriptorFluid.registerFluid("metatech.fluid." + unlocalizedName, metaLiquidStack);
FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(descriptorFluid.getFluid(), 125), new ItemStack(
MetaLiquids.metaLiquidContainer, 1, i + 1), new ItemStack(MetaLiquids.metaLiquidContainer, 1, 0)));
//ItemStack metaLiquidContainerStack = new ItemStack(MetaLiquids.metaLiquidContainer, 1, i + 1);
// LanguageRegistry.addName(metaLiquidContainerStack,
// MetaLiquidContainer.getDisplayName(metaLiquidContainerStack));
descriptorFluid.setCustom("MetaLiquidUID", i + 1);
MetaLiquids.blockToFluid.put(liquidBlock, descriptorFluid);
MetaLiquids.metaFluids[i] = descriptorFluid;
}
}
}
|
Markdown | UTF-8 | 3,233 | 2.578125 | 3 | [] | no_license | # Introduction to radare2
### `12 April 2020`
## Why radare2 ?
If you look at the `Reverse Engineering` or `Malware Analysis` world, they have their favourite tools of
choice. Either its the ubiquitous `IDAPro` or the new kid on the block `Ghidra` which is gaining traction.
There are off course other contenders like `Binary Ninja` and others. So why choose `radare2` ?
What is so special about radare2 ?
Well for beginners both `IDAPro` and `Ghidra` are GUI programs, that is you needs access to a X window
or GUI session to be able to use any of these effectively. If you are working on Linux and are comfortable
with the command line `radare2` provides the interface that can be used at command line. No GUI needed.
Off course there are initiatives within radare2 to support GUI via `Cutter` and people are free to use them.
Maturity ?
Yes its true that tools like `IDAPro` and pretty old and battle tested, same goes for `Ghidra` which was
used for reverse engineering within NSA and was recently opensourced. So the functionality provided by
these must be extremely mature and robust. Not to mention their advanced decompilers which is a critical
component when it comes to getting pseudo-code from assembly. Well I can't argue with that. However
I feel `radare2` gives you a good starting point to get your feet wet, so lets use it !
So what all functionality is required ?
I've installed and used radare2 on and off and loaded a couple of binaries and tried a few command here and
there. But I am nowhere proficient in using radare2. Also I often forget the commands due to time lapse.
So I need a set of MUST-HAVE use cases and their equivalent how-to's in radare2 to get started.
How do we get that ? We don't even know what we are looking for ? Well let's leverage expertise of the users
of `IDApro` and `Ghidra`. What i mean by that is, if we could closely learn how to do the same tasks that
they do in those tools via radare2, we should be set to go.
So Following are the tasks that we need to perform using radare2 !
I will keep updating this post as I learn more about radare2
## radare2 installation
## radare2 basic building blocks
## Loading binary in radare2
## Various view available in radare2
## Moving between various views
## radare2 configuration
## Find out various functions within the binary
`afl` - List all functions
`afll` - Additional details about the functions
## Find out the `Imports` functions
## Find out the `Exports` functions
## List various `Strings` present in the binary
## Find out various sections in the binary, eg ELF sections
## Starting project, saving project How to
## Renaming variables, location, function names
## How to add our comments
## Navigating/Seeking to various locations in the binary
## Find Cross-References or XREFS for code and data, listing
## Graph views How to ?
## Decompilation and pseudo code with different decompiler plugins
## Finding information on Linux API's, libc functions, system calls etc
## Scripting capability of radare2
## Understanding various plugins, how to install and their uses
## Patching binaries How to
## How to use Debugger functionality
## View CPU registers, memory, stack information at runtime
|
Markdown | UTF-8 | 1,122 | 3.15625 | 3 | [] | no_license | # WeatherForcast
Ever wonder what the weather was like all the way in Taipei? Or in Rome? Or even outside your very own window?
I have created a weather application that gives you the information you need to step out the door and go on an adventure!
# What it does
Here's how it works. You type in whatever city it is you want to look up the weather for. The application will give you the current temperature, humidity, wind speed, and the UV index with a color code. It'll even give you an icon for what the majority of the day should be like!
It will also give you the weather for the next five days so that you can plan out a few days in advance if that's your thing. The UI is constantly being improved so if there are a few stylistic things that you are not a fan of, I'm working on it.
# The works
The application is mostly powered through javaScript. There are some HTML elements and some CSS so that it looks usable. Your city search should look like below.
Enjoy!
https://joychen5069.github.io/WeatherForcast/
<img src="/assets/images/Weather-Api.png" alt="Weather App Image" width="100%" height="auto">
|
Java | UTF-8 | 188 | 1.773438 | 2 | [] | no_license | package com.stackroute.gupshup.userservice.exception;
public class UserNotDeletedException extends Exception {
public UserNotDeletedException(String message) {
super(message);
}
}
|
C++ | UTF-8 | 1,769 | 2.90625 | 3 | [] | no_license | //
// Created by Administrator on 2020/12/5.
//
#ifndef MYDATABASE_IX_INTERNAL_H
#define MYDATABASE_IX_INTERNAL_H
#include <string>
#include "ix.h"
#define IX_NULL_POINTER -1
#define IX_NO_PAGE -1
// Bp树的结点的类型:根节点,非叶结点,叶结点,同时为根节点和叶结点
enum IX_NodeType {
ROOT,
NODE,
LEAF,
ROOT_LEAF
};
// 结点中保存的若干索引项值的类型,如果是叶结点对应的类型就是EMPTY或RID_FILLED表示索引val里面存放着rid的值,并且nextPage指针指向溢出块的页号
// 如果非叶结点则为EMPTY或PAGE_ONLY表示索引项val不存放rid,而且nextPage保存子节点的页号
enum IX_ValueType {
EMPTY,
PAGE_ONLY,
RID_FILLED
};
// 索引val: 能够表示子节点的页号,或索引到rid的值并存储溢出块的位置
struct IX_NodeValue {
IX_ValueType state;
RID rid;
PageNum nextPage; // 如果是叶节点,则表示溢出页的页号, 链表结构,如果是非叶结点则是子节点的页号
IX_NodeValue() : state(EMPTY), rid(-1, -1), nextPage(IX_NO_PAGE) {}
};
// 索引文件中索引节点的页头结构
struct IX_NodeHeader {
int numberKeys;
int keyCapacity;
PageNum prePage; // 前一个结点也就是左边的结点
IX_NodeType type;
PageNum parent;
};
// 索引文件中溢出块的页头结构
struct IX_OverflowPageHeader {
int numberRecords; // 记录桶中记录的数量
int recordCapacity; // 记录最多能容纳的记录数量
PageNum parentPage; // 记录父节点的页号
};
// 溢出块中能容纳的rid记录数量
const int RID_COUNT_OF_OVERFLOW_PAGE = (PF_PAGE_SIZE - sizeof(IX_OverflowPageHeader)) / sizeof(RID);
#endif //MYDATABASE_IX_INTERNAL_H
|
Java | UTF-8 | 3,377 | 2.703125 | 3 | [] | no_license | package com.company.io;
import com.company.entity.Rank;
import com.company.entity.Result;
import com.company.util.DbConnectionUtil;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class FullInfoDbReader {
private List<Result> resultList = new ArrayList<>();
private static final String SELECT_ALL = "SELECT f.flight_number, f.data, f.time, a.tail_number, a.brand, a.model,"
+ " a.passenger_capacity, p.last_name, p.name, p.pilot_code, p.p_rank FROM flights f JOIN aircraft a ON f.aircrat=a.id JOIN pilots p ON f.pilot = p.id";
public void readAll() {
Connection connection = DbConnectionUtil.detConnection();
try (PreparedStatement statement = connection.prepareStatement(SELECT_ALL)) {
ResultSet result = statement.executeQuery();
while (result.next()) {
String flight_number = result.getString("f.flight_number");
String data = result.getString("f.data");
String time = result.getString("f.time");
int tail_number = result.getInt("a.tail_number");
String brand = result.getString("a.brand");
String model = result.getString("a.model");
int passenger_capacity = result.getInt("a.passenger_capacity");
String last_name = result.getString("p.last_name");
String name = result.getString("p.name");
String pilot_code = result.getString("p.pilot_code");
Rank rank = Rank.valueOf(result.getString("p.p_rank"));
Result res = new Result(flight_number, data, time, tail_number, brand, model, passenger_capacity, last_name, name, pilot_code, rank);
resultList.add(res);
System.out.println(flight_number + ", " + data + ", " + time + ", " + tail_number + ", " + brand + " "
+ model + ", " + passenger_capacity + ", " + last_name + " " + name + ", " + pilot_code + " (" + rank + ")");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void writeResult() {
try (FileWriter writer = new FileWriter("result\\result.csv")) {
for (Result result : resultList) {
writer.append(result.getFlight_number()).append(", ");
writer.append(result.getData()).append(", ");
writer.append(result.getTime()).append(", ");
writer.append(String.valueOf(result.getTail_number())).append(", ");
writer.append(result.getBrand()).append(", ");
writer.append(result.getModel()).append(", ");
writer.append(String.valueOf(result.getPassenger_capacity())).append(", ");
writer.append(result.getLast_name()).append(", ");
writer.append(result.getName()).append(", ");
writer.append(result.getPilot_code()).append(", ");
writer.append(result.getRank().toString());
writer.append("\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
C# | UTF-8 | 10,663 | 2.546875 | 3 | [] | no_license | using System;
using AutoMapper;
using ProductShop.Data;
using ProductShop.Dtos.Import;
using ProductShop.Models;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Linq;
using ProductShop.Dtos.Export;
using System.Text;
using System.Xml;
using AutoMapper.QueryableExtensions;
namespace ProductShop
{
public class StartUp
{
public static void Main(string[] args)
{
Mapper.Initialize(x =>
{
x.AddProfile<ProductShopProfile>();
});
var context = new ProductShopContext();
//context.Database.EnsureDeleted();
//context.Database.EnsureCreated();
//// 01. Import Users
//var usersXml = File.ReadAllText("../../../Datasets/users.xml");
//var usersResult = ImportUsers(context, usersXml);
//Console.WriteLine(usersResult);
//// 02. Import Products
//var productsXml = File.ReadAllText("../../../Datasets/products.xml");
//var productsResult = ImportProducts(context, productsXml);
//Console.WriteLine(productsResult);
//// 03. Import Categories
//var categoriesXml = File.ReadAllText("../../../Datasets/categories.xml");
//var categoriesResult = ImportCategories(context, categoriesXml);
//Console.WriteLine(categoriesResult);
//// 04.Import Categories and Products
//var categoriesProductsXml = File.ReadAllText("../../../Datasets/categories-products.xml");
//var categoriesProductsResult = ImportCategoryProducts(context, categoriesProductsXml);
//Console.WriteLine(categoriesProductsResult);
//// 05. Export Products In Range
//Console.WriteLine(GetProductsInRange(context));
//// 06. Export Sold Products
//Console.WriteLine(GetSoldProducts(context));
//// 07. Export Categories By Products Count
//Console.WriteLine(GetCategoriesByProductsCount(context));
//// 08.Export Users and Products
Console.WriteLine(GetUsersWithProducts(context));
}
// 01. Import Users
public static string ImportUsers(ProductShopContext context, string inputXml)
{
var xmlSerializer = new XmlSerializer(typeof(ImportUserDto[]), new XmlRootAttribute("Users"));
var usersDto = (ImportUserDto[])xmlSerializer.Deserialize(new StringReader(inputXml));
List<User> users = new List<User>();
foreach (var userDto in usersDto)
{
var user = Mapper.Map<User>(userDto);
users.Add(user);
}
context.Users.AddRange(users);
int count = context.SaveChanges();
return $"Successfully imported {count}";
}
// 02. Import Products
public static string ImportProducts(ProductShopContext context, string inputXml)
{
var xmlSerializer = new XmlSerializer(typeof(ImportProductDto[]), new XmlRootAttribute("Products"));
var productsDto = (ImportProductDto[])xmlSerializer.Deserialize(new StringReader(inputXml));
var products = new List<Product>();
foreach (var productDto in productsDto)
{
var product = Mapper.Map<Product>(productDto);
products.Add(product);
}
context.Products.AddRange(products);
int count = context.SaveChanges();
return $"Successfully imported {count}";
}
// 03. Import Categories
public static string ImportCategories(ProductShopContext context, string inputXml)
{
var xmlSerializer = new XmlSerializer(typeof(ImportCategoryDto[]), new XmlRootAttribute("Categories"));
var categoriesDto = (ImportCategoryDto[])xmlSerializer.Deserialize(new StringReader(inputXml));
var categories = new List<Category>();
foreach (var categoryDto in categoriesDto)
{
var category = Mapper.Map<Category>(categoryDto);
categories.Add(category);
}
context.Categories.AddRange(categories);
int count = context.SaveChanges();
return $"Successfully imported {count}";
}
// 04. Import Categories and Products
public static string ImportCategoryProducts(ProductShopContext context, string inputXml)
{
var xmlSerializer = new XmlSerializer(typeof(ImportCategoryProductsDto[]),
new XmlRootAttribute("CategoryProducts"));
var categoryProductsDto =
((ImportCategoryProductsDto[])xmlSerializer.Deserialize(new StringReader(inputXml)))
.ToList();
var categoryProducts = new List<CategoryProduct>();
foreach (var categoryProductDto in categoryProductsDto)
{
var targetProduct = context.Products.Find(categoryProductDto.ProductId);
var targetCategory = context.Categories.Find(categoryProductDto.CategoryId);
//if (targetProduct != null && targetCategory != null)
//{
var category = Mapper.Map<CategoryProduct>(categoryProductDto);
categoryProducts.Add(category);
//}
}
context.CategoryProducts.AddRange(categoryProducts);
int count = context.SaveChanges();
return $"Successfully imported {count}";
}
// 05. Export Products In Range
public static string GetProductsInRange(ProductShopContext context)
{
var productsInRange = context.Products
.Where(p => p.Price >= 500 && p.Price <= 1000)
.Select(p => new ExportProductsInRangeDto
{
Name = p.Name,
Price = p.Price,
Buyer = $"{p.Buyer.FirstName} {p.Buyer.LastName}"
})
.OrderBy(p => p.Price)
.Take(10)
.ToArray();
var xmlSerializer =
new XmlSerializer(typeof(ExportProductsInRangeDto[]), new XmlRootAttribute("Products"));
StringBuilder sb = new StringBuilder();
var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
xmlSerializer.Serialize(new StringWriter(sb), productsInRange, namespaces);
return sb.ToString().TrimEnd();
}
// 06. Export Sold Products
public static string GetSoldProducts(ProductShopContext context)
{
var soldProducts = context.Users
.Where(u => u.ProductsSold.Any(p => p.Buyer != null))
.Select(u => new ExportProductsSoldDto
{
FirstName = u.FirstName,
LastName = u.LastName,
Products = u.ProductsSold.Select(p => new ExportSoldProductDto
{
Name = p.Name,
Price = p.Price
})
.ToArray()
})
.OrderBy(u => u.LastName)
.ThenBy(u => u.FirstName)
.Take(5)
.ToArray();
var xmlSerializer = new XmlSerializer(typeof(ExportProductsSoldDto[]), new XmlRootAttribute("Users"));
var sb = new StringBuilder();
var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
xmlSerializer.Serialize(new StringWriter(sb), soldProducts, namespaces);
return sb.ToString().TrimEnd();
}
//Query 7. Categories By Products Count
public static string GetCategoriesByProductsCount(ProductShopContext context)
{
var categories = context
.Categories
.Select(x => new ExportCategoriesByCountDto
{
Name = x.Name,
ProductsCount = x.CategoryProducts.Count,
AveragePrice = x.CategoryProducts.Select(a => a.Product.Price).Average(),
TotalRevenue = x.CategoryProducts.Select(а => а.Product.Price).Sum()
})
.OrderByDescending(x => x.ProductsCount)
.ThenBy(x => x.TotalRevenue)
.ToArray();
var sb = new StringBuilder();
var serializer = new XmlSerializer(typeof(ExportCategoriesByCountDto[]), new XmlRootAttribute("Categories"));
var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
serializer.Serialize(new StringWriter(sb), categories, namespaces);
return sb.ToString().TrimEnd();
}
//Query 8. Users and Products
public static string GetUsersWithProducts(ProductShopContext context)
{
var users = context
.Users
.Where(x => x.ProductsSold.Any())
.Select(x => new ExportUserAndProductDto
{
FirstName = x.FirstName,
LastName = x.LastName,
Age = x.Age,
SoldProductDto = new SoldProductDto
{
Count = x.ProductsSold.Count,
ProductDtos = x.ProductsSold.Select(p => new ProductDto()
{
Name = p.Name,
Price = p.Price
})
.OrderByDescending(p => p.Price)
.ToArray()
}
})
.OrderByDescending(x => x.SoldProductDto.Count)
.Take(10)
.ToArray();
var customExport = new ExportCustomUserProductDto
{
Count = context.Users.Count(x => x.ProductsSold.Any()),
ExportUserAndProductDto = users
};
XmlSerializer xmlSerializer = new XmlSerializer(typeof(ExportCustomUserProductDto), new XmlRootAttribute("Users"));
var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var sb = new StringBuilder();
xmlSerializer.Serialize(new StringWriter(sb), customExport, namespaces);
return sb.ToString().TrimEnd();
}
}
} |
PHP | UTF-8 | 302 | 2.953125 | 3 | [] | no_license | <?php
require __DIR__ . "/../vendor/autoload.php";
use MTNewton\NumberPyramid\NumberPyramid;
$pyramid = NumberPyramid::fromSeed(null, 1000);
echo 'File generated at: ' . $pyramid->generate() . PHP_EOL;
echo 'Min: ' . $pyramid->solveMin() . PHP_EOL;
echo 'Max: ' . $pyramid->solveMax() . PHP_EOL;
|
Java | UTF-8 | 2,231 | 2.65625 | 3 | [] | no_license | package com.company.ui.client;
import com.company.book.Book;
import com.company.ui.gui_factory.GuiFactory;
import com.company.ui.librarian.LibrarianBookClickPage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;
/**
* Created by me on 01/02/2017.
*/
public class ClientViewBooksPage extends ClientPage {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTable table;
private List<Book> books;
public ClientViewBooksPage(List<Book> books) {
super();
this.books = books;
setUpUi();
}
public void setUpUi(){
addMenuItems();
initUI();
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
//should be filled from DB
String data[][]=createData();
// setBounds(100, 100, 450, 25*(data.length+1));
String column[]={"Name","Author","Publisher"};
table = getFactory().makeTable(data,column);
JScrollPane sp=new JScrollPane(table);
contentPane.add(sp, BorderLayout.CENTER);
setActions();
}
private String[][] createData() {
String data[][] = new String[books.size()][3];
Iterator bookIterator = books.iterator();
int i=0;
while(bookIterator.hasNext()){
Book book = (Book)bookIterator.next();
data[i][0] = book.getName();
data[i][1] = book.getAuthor();
data[i][2] = book.getPublisher();
i++;
}
return data;
}
@Override
public void resetFactory(GuiFactory factory) {
// TODO Auto-generated method stub
}
public void setActions(){
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
new ClientBookClickPage(books.get(table.getSelectedRow()));
closePage();
}
});
}
}
|
Java | UTF-8 | 927 | 1.84375 | 2 | [] | no_license | package com.zyy.scanner.service;
import java.util.List;
import com.zyy.scanner.model.ControllerMethodParamVO;
import com.zyy.scanner.model.ControllerMethodVO;
import com.zyy.scanner.model.ControllerVO;
import com.zyy.scanner.model.PageInitVO;
/**
* @Author zhangyy
* @DateTime 2019-07-16 11:57
* @Description
*/
public interface IScannerControllerService {
/**
* controller扫描
* @param search
* @return
* @throws Exception
*/
PageInitVO getController(String search) throws Exception;
/**
* 获取方法
* @param classPath
* @return
* @throws Exception
*/
List<ControllerMethodVO> getControllerMethod(String classPath) throws Exception;
/**
* 根据方法URL获取方法的出入参JSON
* @param methodUrl
* @return
* @throws Exception
*/
ControllerMethodParamVO getMethodParam(String methodUrl) throws Exception;
}
|
Java | UTF-8 | 777 | 2.203125 | 2 | [] | no_license | package ch.unibe.scg.cells;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.inject.Scope;
/**
* The scope of the lifetime of a mapper in a pipeline. That is, a pipeline of three
* mappers will have three different scopes, one for each mapper stage.
* Further, {@link Mapper}s are guaranteed to run inside the scope. This is true
* even for the {@link Mapper#close} method, which is still in scope.
*/
@Target({ FIELD, PARAMETER, METHOD })
@Retention(RUNTIME)
@Scope
@interface PipelineStageScoped { }
|
Java | UTF-8 | 5,997 | 3.1875 | 3 | [] | no_license | package team156.Utility;
import team156.Channels;
import team156.RobotPlayer;
import battlecode.common.*;
public class LastAttackedLocationsReport {
/**
* Attack events are stored in radio map, in a circular array.
*
* From BASE_CHANNEL, the first channel stores x location (raw MapLocation
* coordinate), and second y. They alternate all the way through, up to
* NUMBER_OF_STORED_EVENTS*2 channels.
*
* nextEventToOverwriteRelativeIndex is the next event to overwrite
*
* The HQinit() method must be called by HQ
*
* The everyRobotInit() method must be called by every unit reporting.
*
* The report() method should be called every round by every unit reporting.
*/
final static int BASE_CHANNEL = Channels.LAST_ATTACKED_COORDINATES+1;
final static int NUMBER_OF_STORED_EVENTS = 10;
final static int NUMBER_OF_CHANNELS_USED = NUMBER_OF_STORED_EVENTS*2; //one for x, y
final static int NUMBER_OF_EVENTS_THAT_HAVE_OCCURRED_CHANNEL = Channels.LAST_ATTACKED_COORDINATES;
public static int numberOfEventsThatHaveOccurred = 0; // Updates every time you add/read, number of events globally
static double hpLastRound;
static RobotController rc;
/**
* Run this once per game at the start to set up memory array.
*
* (So HQ should run it once in its init)
*
* @throws GameActionException
*/
public static void HQinit() throws GameActionException {
RobotPlayer.rc.broadcast(BASE_CHANNEL+NUMBER_OF_CHANNELS_USED-1, Integer.MAX_VALUE);
RobotPlayer.rc.broadcast(BASE_CHANNEL+NUMBER_OF_CHANNELS_USED-2, Integer.MAX_VALUE);
RobotPlayer.rc.broadcast(NUMBER_OF_EVENTS_THAT_HAVE_OCCURRED_CHANNEL, 0);
}
/**
* Run this once per unit, in the init.
* @return
*
*/
public static void everyRobotInit() throws GameActionException {
hpLastRound = RobotPlayer.myType.maxHealth;
rc = RobotPlayer.rc;
}
/**
* Run this once per round, after myLocation is updated.
*
* If any attack occurs, this function will detect and autoreport it.
*
* @throws GameActionException
*/
public static void report() throws GameActionException {
double hpNow = rc.getHealth();
if (hpNow < hpLastRound) {
hpLastRound = hpNow;
add(RobotPlayer.myLocation.x, RobotPlayer.myLocation.y);
}
}
/**
* Add an event to the data structure
*
* @param x
* @param y
* @throws GameActionException
*/
public static void add(int x, int y) throws GameActionException {
numberOfEventsThatHaveOccurred = RobotPlayer.rc.readBroadcast(NUMBER_OF_EVENTS_THAT_HAVE_OCCURRED_CHANNEL);
int baseChannelIdx = BASE_CHANNEL
+ (numberOfEventsThatHaveOccurred % NUMBER_OF_STORED_EVENTS)
* 2;
RobotPlayer.rc.broadcast(baseChannelIdx, x);
RobotPlayer.rc.broadcast(baseChannelIdx + 1, y);
RobotPlayer.rc.broadcast(NUMBER_OF_EVENTS_THAT_HAVE_OCCURRED_CHANNEL, numberOfEventsThatHaveOccurred+1);
// System.out.println("Attack reported at " + x + ", " + y);
// System.out.println("Last 3 attacks (including this) as follows:");
//
// for (int i =0; i< 5; i++) {
// System.out.println(getLastAttackXCoordinate(i) + "," +getLastAttackYCoordinate(i));
//
// }
}
//TODO: Combine both methods to optimize bytecode usage
/**
* Query data structure
*
* 0 indexed.
*
* If number >= NUMBER_OF_STORED_EVENTS, the events returned will repeat
* cyclically.
*
* @param number
* 0 for the last attacked location, will return
* Integer.MAX_VALUE on 1 + maximum number. <br>
* <br>
* You should stop iteration then.
* @return
* @throws GameActionException
*/
public static int getLastAttackXCoordinate(int number) throws GameActionException {
numberOfEventsThatHaveOccurred = RobotPlayer.rc
.readBroadcast(NUMBER_OF_EVENTS_THAT_HAVE_OCCURRED_CHANNEL);
int relChannel = ((numberOfEventsThatHaveOccurred - number-1) * 2)
% NUMBER_OF_CHANNELS_USED;
if (relChannel < 0)
return RobotPlayer.rc.readBroadcast(BASE_CHANNEL+relChannel+NUMBER_OF_CHANNELS_USED);
else
return RobotPlayer.rc.readBroadcast(BASE_CHANNEL+relChannel);
}
/**
* Query data structure
*
* 0 indexed.
*
* If number >= NUMBER_OF_STORED_EVENTS, the events returned will repeat
* cyclically.
*
* @param number
* 0 for the last attacked location, will return
* Integer.MAX_VALUE on 1 + maximum number. <br>
* <br>
* You should stop iteration then.
* @return
* @throws GameActionException
*/
public static int getLastAttackYCoordinate(int number) throws GameActionException {
numberOfEventsThatHaveOccurred = RobotPlayer.rc
.readBroadcast(NUMBER_OF_EVENTS_THAT_HAVE_OCCURRED_CHANNEL);
int relChannel = 1
+ ((numberOfEventsThatHaveOccurred - number-1) * 2)
% NUMBER_OF_CHANNELS_USED;
if (relChannel < 0)
return RobotPlayer.rc.readBroadcast(relChannel+BASE_CHANNEL+NUMBER_OF_CHANNELS_USED);
else
return RobotPlayer.rc.readBroadcast(relChannel+BASE_CHANNEL);
}
/**
* Gets the latest number of events that have occurred.
* @return
* @throws GameActionException
*/
public static int getNumberOfEventsThatHaveOccurred() throws GameActionException {
numberOfEventsThatHaveOccurred = RobotPlayer.rc
.readBroadcast(NUMBER_OF_EVENTS_THAT_HAVE_OCCURRED_CHANNEL);
return numberOfEventsThatHaveOccurred;
}
}
|
Java | UTF-8 | 1,570 | 2.453125 | 2 | [] | no_license | package com.lingda.gamble.model;
public class SMPSingleRatio {
private double da;
private double xiao;
private double dan;
private double shuang;
private double lon;
private double hu;
public SMPSingleRatio() {
}
public SMPSingleRatio(double da, double xiao, double dan, double shuang, double lon, double hu) {
this.da = da;
this.xiao = xiao;
this.dan = dan;
this.shuang = shuang;
this.lon = lon;
this.hu = hu;
}
public double getDa() {
return da;
}
public void setDa(double da) {
this.da = da;
}
public double getXiao() {
return xiao;
}
public void setXiao(double xiao) {
this.xiao = xiao;
}
public double getDan() {
return dan;
}
public void setDan(double dan) {
this.dan = dan;
}
public double getShuang() {
return shuang;
}
public void setShuang(double shuang) {
this.shuang = shuang;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public double getHu() {
return hu;
}
public void setHu(double hu) {
this.hu = hu;
}
@Override
public String toString() {
return "SMPSingleRatio{" +
"da=" + da +
", xiao=" + xiao +
", dan=" + dan +
", shuang=" + shuang +
", lon=" + lon +
", hu=" + hu +
'}';
}
}
|
Markdown | UTF-8 | 790 | 2.53125 | 3 | [
"MIT"
] | permissive | # TasksApp
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 12.0.3.
This project will perform some CRUD operations with a task model:
```js
task: {
id: '',
name: ''
}
```
## Before run project
Install dependencies:
```bash
yarn install
```
or
```bash
npm install
```
Clone Koa project [here](https://github.com/thovo/koa-api), follow the instruction to start a node server at port 3000. This project need this server to run properly.
## Development server
Run `yarn start` for a dev server. Navigate to `http://localhost:4200/`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests with Jest.
## License
MIT
|
C++ | UHC | 1,829 | 3.71875 | 4 | [] | no_license | #include<iostream>
using namespace std;
//̿ Ű, Կ üũϴ α(18.04.17)
int main()
{
int age;
double tall; double weight;
double bmi; double ki;
cout << " ̿ Ű, Ը Էֽʽÿ.";
cin >> age; cin >> tall; cin >> weight;
ki = tall / 100;
bmi = weight / (ki*ki);
if (age < 20)
cout << " ϴ.";
else if (19 < age < 29)
{
if (bmi < 18)
cout << " üԴϴ" << endl;
else if (18 < bmi < 23)
cout << " ǥ üԴϴ" << endl;
else if (23 < bmi < 30)
cout << " üԴϴ." << endl;
else
cout << " Դϴ." << endl;
}
else if (29 < age < 40)
{
if (bmi < 18.5)
cout << " üԴϴ" << endl;
else if (18.5 < bmi < 24)
cout << " ǥ üԴϴ" << endl;
else if (24 < bmi < 30)
cout << " üԴϴ." << endl;
else
cout << " Դϴ." << endl;
}
cout << endl;
//1~n
{int sum = 0;
int n;
cout << " ԷϽÿ:";
cin >> n;
if (0 < n)
{
for (int i = 1; i <= n; i++)
sum += i;
cout << "1 10 =" << sum << endl;
}
else
cout << "Ҽϴ" << endl;
}
cout << endl;
//ﰢ
int x = 0, y = 0;
int j;
cout << "ﰢ Ȧ Էֽÿ:";
cin >> j;
if (j <= 0 || 0 == j % 2)
{
cout << " ϴ. ڸ ٽ Էּ.";
}
else
{
for (y = 0; y < (j / 2) + 1; y++)
{
for (x = (j / 2) + 1; x > y - 1; x--)
cout << " ";
for (x = 0; x < (2 * y) + 1; x++)
cout << "*";
cout << endl;
}
}
cout << endl;
return 0;
} |
PHP | UTF-8 | 12,752 | 2.828125 | 3 | [] | no_license | <?php
// **** START AWESOMEMINER PRE-RUN CHECK ****
echo "AwesomeMiner - searching\n";
//$AwesomeMiner_check = 1;
// kill tasks matching
$kill_pattern = '~(AwesomeMiner|Awesome|Miner)\.exe~i';
// get tasklist
$task_list = array();
exec("tasklist 2>NUL", $task_list);
foreach ($task_list AS $task_line){
if (preg_match($kill_pattern, $task_line, $out)){
echo "Detected: ".$out[1]."\n Sending term signal!\n";
exec("taskkill /F /IM ".$out[1].".exe 2>NUL");
//$AwesomeMiner_check = 0;
}
}
// Wait for 2 seconds to make sure AwesomeMiner closes down
sleep(2);
echo "AwesomeMiner - not running\n\n";
echo "This program has attempted to close AwesomeMiner. Please double check that it is closed before proceeding.\n";
echo "It is critically important that it is in fact closed.\n";
echo "";
if (PHP_OS == 'WINNT') {
echo '<Y/n>: ';
$line = stream_get_line(STDIN, 1024, PHP_EOL);
} else {
$line = readline('<Y/n>: ');
}
if ($line == "" || $line == "y" || $line == "Y") {
// Do nothing and bypass blocking code
} else {
// Run to the hills!
echo "No selected, terminating program.\n";
die();
}
// **** END AWESOMEMINER PRE-RUN CHECK ****
//Set time zone for later
date_default_timezone_set('America/Los_Angeles');
// **** START GOOGLE AUTH ****
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Sheets::SPREADSHEETS_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* @param string $path the path to expand.
* @return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'your-spreadsheet-id';
$range = 'Data!A:M';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (count($values) == 0) {
print "No data found.\n";
} else {
// Define an array to store outputs of Google Sheets, for comparison with AwesomeMiner XML file
$get_google_array_01 = [];
// We need a 2D array, so we need a variable to count the first index
$google_indexCounter = 0;
// For testing:
//print_r($values);
//die();
// Todo: translate this to a for loop, will make porting easier in the future
foreach ($values as $row) {
// Seperate in to variables for readability
$serial = is_set($row, 0);
$first_hosted = is_set($row, 1);
$client = is_set($row, 2);
$type = is_set($row, 3);
$vlan = is_set($row, 4);
$ip = is_set($row, 5);
$location = is_set($row, 6);
// For testing:
//echo $simple_ip . " - " . $serial . " - " . $client . " - " . $type . "\n";
// Move variables in to 2D array
$get_google_array_01[$google_indexCounter][0] = $serial;
$get_google_array_01[$google_indexCounter][1] = $first_hosted;
$get_google_array_01[$google_indexCounter][2] = $client;
$get_google_array_01[$google_indexCounter][3] = $type;
$get_google_array_01[$google_indexCounter][4] = $vlan;
$get_google_array_01[$google_indexCounter][5] = $ip;
$get_google_array_01[$google_indexCounter][6] = $location;
$get_google_array_01[$google_indexCounter][7] = "10.0." . $get_google_array_01[$google_indexCounter][4] . "." . $get_google_array_01[$google_indexCounter][5];
$get_google_array_01[$google_indexCounter][8] = "10.0." . $get_google_array_01[$google_indexCounter][4] . "." . $get_google_array_01[$google_indexCounter][5] . " - " . $get_google_array_01[$google_indexCounter][0] . " - " . $get_google_array_01[$google_indexCounter][3] . " - " . $get_google_array_01[$google_indexCounter][6];
// itterate up to next index count
$google_indexCounter++;
}
}
// **** END GOOGLE AUTH ****
$awesomeAppData = "C:\Users\joelc\AppData\Roaming\AwesomeMiner\ConfigData.xml";
function echo_array($arr) {
for($q = 0; $q < count($arr); $q++) {
echo $arr[$q] . "\n";
}
}
function echo_array_multiD($arr) {
$count = 0;
for($q = 0; $q < count($arr); $q++) {
//var_dump($q);
// Depending on the array a little visual help for seperation:
echo "Count: " . $count . "\n";
for($r = 0; $r < count($arr[$q]); $r++) {
echo $arr[$q][$r] . "\n";
}
$count += 1;
// Depending on the array a little visual help for seperation:
echo "---\n";
}
}
function check_array_awesomeMultiD($arr1, $arr2) {
// $arr1 = AwesomeMiner array, $arr2 = Google Sheets array
//
for($q = 0; $q < count($arr1); $q++) {
for($r = 0; $r < count($arr1[$q]); $r++) {
echo $arr1[$q][$r] . "\n";
}
$count += 1;
}
}
function get_difference($var1, $var2) {
// Used to return a length value for PHP function array_slice
return $var2 - $var1;
}
function is_set($arr, $offset) {
// Without checking if array offset is set PHP will return an error on empty array members
if(isset($arr[$offset])) {
return $arr[$offset];
} else {
return '';
}
}
function scrape_between($data, $start, $end){
$data = stristr($data, $start); // Stripping all data from before $start
$data = substr($data, strlen($start)); // Stripping $start
$stop = stripos($data, $end); // Getting the position of the $end of the data to scrape
$data = substr($data, 0, $stop); // Stripping all data from after and including the $end of the data to scrape
return $data; // Returning the scraped data from the function
}
function explode_ip_description($data) {
// This function explodes the Awesome Miner description dependent on characters of "-"
// If Awesome Miner description does not contain 3 characters of "-" it does nothing
// Adjust this in the future if description delimiter and or delimiter number changes
// Some of machines in Google Sheets have odd naming conventions
if (substr_count($data, " - ") === 3) {
$data = explode(" - ", $data);
return $data[3];
} elseif (substr_count($data, " - ") === 4) {
$data = explode(" - ", $data);
return $data[4];
} else {
return $data;
}
}
function explode_ip_hostname($data) {
$data = explode(":", $data);
return $data[0];
}
// There is an issue with importing a file that has EOL / new line from Windows.
// To solve we will ignore this problem and just add a new line/return when echoing out
$get_awesomeminer_array = file(glob($awesomeAppData)[0], FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// Need to define points to chop up awesome miner in to seperate arrays, for easier sorting:
$key_external_start = array_search(' <ExternalMinerList>', $get_awesomeminer_array);
$key_external_end = array_search(' </ExternalMinerList>', $get_awesomeminer_array);
// Seperate parts of array for drastically easier sorting/manipulation later
$awesomeminer_array_00 = array_slice($get_awesomeminer_array, 0, get_difference(0, $key_external_start + 1));
$awesomeminer_array_01 = array_slice($get_awesomeminer_array, $key_external_start + 1, get_difference($key_external_start, $key_external_end - 1));
$awesomeminer_array_02 = array_slice($get_awesomeminer_array, $key_external_end, get_difference($key_external_end, 1 + array_search(end($get_awesomeminer_array), $get_awesomeminer_array)));
// Break up in to <ExternalMinerExport> ... </ExternalMinerExport> blocks
// Todo: put this in to its own function
$get_awesomeminer_array_01 = [];
$indexCount = 0;
$indexCountSub = 0;
for($q = 0; $q < count($awesomeminer_array_01); $q++) {
$get_awesomeminer_array_01[$indexCount][$indexCountSub] = $awesomeminer_array_01[$q];
$indexCountSub++;
// If end of external miner, itterate to next array key
if($awesomeminer_array_01[$q] == ' </ExternalMiner>') {
$indexCount++;
$indexCountSub = 0;
}
}
$total_awesome = count($get_awesomeminer_array_01);
$total_google = count($get_google_array_01);
$total_diff = $total_google - $total_awesome;
$match_count = 0;
// For testing:
//print_r($get_awesomeminer_array_01);
//print_r($get_google_array_01);
//die();
// Check AwesomeMiner for description fields, get ip of empty description fields
for($q = 0; $q < count($get_awesomeminer_array_01); $q++) {
for($r = 0; $r < count($get_awesomeminer_array_01[$q]); $r++) {
// Instead of first searching for Description tags we search for the <hostname> tag
// This is necessary because the idiots who made AwesomeMiner are not consistant
// Sometimes the Hostname tag is the 15th, other times it is the 16th array key
// The Description tag location does not move, thank god
if (strpos($get_awesomeminer_array_01[$q][$r], " <Hostname>") !== false) {
echo $get_awesomeminer_array_01[$q][$r] . "\n";
// Get rid of hostname tages
$awesome_miner_description = scrape_between($get_awesomeminer_array_01[$q][$r], ">", "<");
// Get rid of colon and port number
$awesome_miner_descript_ip = explode_ip_hostname($awesome_miner_description);
for($s = 0; $s < count($get_google_array_01); $s++) {
if ($awesome_miner_descript_ip == $get_google_array_01[$s][7]) {
$get_awesomeminer_array_01[$q][3] = " <Description>" . $get_google_array_01[$s][2] . " - " . $get_google_array_01[$s][8] . "</Description>";
echo " <Description>" . $get_google_array_01[$s][2] . " - " . $get_google_array_01[$s][8] . "</Description>\n";
}
}
}
}
// Reset variable to prevent non matching results being mis-labeled from previous succesful find
$awesome_miner_descript_ip = '';
}
// For testing:
//print_r($get_awesomeminer_array_01);
//print_r($get_google_array_01);
//die();
// Flatten 2D array, so that we can combine it with other arrays
$array_flatten = [];
for($d = 0; $d < count($get_awesomeminer_array_01); $d++) {
for($e = 0; $e < count($get_awesomeminer_array_01[$d]); $e++) {
array_push($array_flatten, $get_awesomeminer_array_01[$d][$e]);
}
}
// Numeric month day year hour minute seconds am/pm time stamp for backup file naming
$timestamp = date('mdohisA');
$sourcefile = $awesomeAppData;
$backupfile = $sourcefile . $timestamp;
// Make backup of ConfigData.xml
copy($sourcefile, $backupfile);
// Combine arrays for output
$array_merge = array_merge($awesomeminer_array_00, $array_flatten, $awesomeminer_array_02);
// Remove source file, probably no longer necessary
//unlink($sourcefile);
// Overwrite contents of ConfigData.xml with new data
file_put_contents($sourcefile, implode(PHP_EOL, $array_merge));
// Output to terminal
// ...
// ENTRY POINTS:
// ...
|
Markdown | UTF-8 | 2,096 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | #NYC CitiBike Data Analysis
##Advanced Big Data Analytics
Bahul Jain - bkj2111
Gaurang Sadekar - gss2147
### Introduction
We will be working with [CitiBike Data](https://www.citibikenyc.com/system-data)
and perform different types of analysis to understand Citi bike usage and trips across different areas of New York City. We will also use this data to build prediction models which give insight into the usage of Citi bikes in relation to external factors.
### Goals
1. Create a visualization showing the favorite neighborhoods based on trip information of CitiBike users.
- Estimating the requirement of bike stations in neighborhoods.
- Most common rides each month (by station and by neighborhoods)
- Estimating deficiency or surplus of bikes in neighborhoods based on usage statistics (available bikes and used bikes).
2. Creating a Regression Model to correlate weather (daily average temperature, precipitation, snow depth) impact on CitiBike activity and forecast future usage.
### Data
The data we will be working with is publicly available for use at [CitiBike Data](https://www.citibikenyc.com/system-d ata).
CitiBike Trip data includes the following fields:
- Trip Duration (seconds)
- Start Time and Date
- Stop Time and Date
- Start Station Name
- End Station Name
- Station ID
- Station Lat/Long
- Bike ID
- User Type (Customer = 24-hour pass or 7-day pass user; Subscriber = Annual Member)
- Gender (Zero=unknown; 1=male; 2=female)
- Year of Birth
This is data is clean and anonymized for user privacy, and does not include any sensitive information about the riders themselves.
The system data also includes CitiBike membership data, which has rich per day information about memberships, ride numbers and ride durations.
#### Sources
1. [CitiBike Data](https://www.citibikenyc.com/system-data)
2. [National Climatic Data Center](https://www.ncdc.noaa.gov/cdo-web/datasets/GHCND/stations/GHCND:USW00094728/detail)
### Tools & Languages
1. Spark
2. MLlib
3. Language Choice: Python/Scala
4. Statsmodels / Scikit-Learn
5. Google Maps API
6. Google Geocoding API
|
Java | UTF-8 | 221 | 1.5 | 2 | [] | no_license | package com.sean.ws.io.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.sean.ws.io.entity.HelloEntity;
public interface HelloRepository extends JpaRepository<HelloEntity, Long> {
}
|
Markdown | UTF-8 | 786 | 3.296875 | 3 | [] | no_license | ### 1.bcrypt
---
1. 安装 `npm install bcrypt`
2. 使用
```js
// 导入模块
const bcrypt = require('bcrypt');
// 加密的幂次
const saltRounds = 10; // 默认 10
// 明文密码
const myPlaintextPassword = 'password';
// [方式一] 将明文密码字符串加密
bcrypt.genSalt(saltRounds, function(err, salt) {
bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
// Store hash in your password DB.
});
});
// [方式二]
bcrypt.hash(myPlaintextPassword, saltRounds, function(err, hash) {
// Store hash in your password DB.
});
// 校验用户密码
bcrypt.compare(myPlaintextPassword, hash, function(err, res) {
// res == true
});
```
|
Java | GB18030 | 1,753 | 2.4375 | 2 | [] | no_license | package com.ltmcp.mobile.action;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import com.ltmcp.action.BaseAction;
import com.ltmcp.util.UrlAndPathComm;
public class AppLogAction extends BaseAction{
/**
* ϴlog־ļ
*/
private File txt; // ϴļ
private String txtFileName; // ļ
private String txtContentType; // ļ
/**
* ϴapp Log־
*/
public void addLogInfo() {
try {
String filePath = "";
try {
filePath = readPhoto("appLogs");
} catch (Exception e) {
super.getPringWriter().print(-4); // ͼƬ쳣
return;
}
if (filePath.equals("")) {
super.getPringWriter().print(-5); // ͼƬ쳣
return;
}
} catch (Exception e) {
e.printStackTrace();
super.getPringWriter().print(-3);
}
}
// ϴ־
public String readPhoto(String directoryName) throws IOException {
String realpath = UrlAndPathComm.comm+ directoryName;
if (txt != null) {
File savefile = new File(new File(realpath), txtFileName);
if (!savefile.getParentFile().exists())
savefile.getParentFile().mkdirs();
FileUtils.copyFile(txt, savefile);
return "/" + directoryName + "/" + savefile.getName();
}
return "";
}
public File getTxt() {
return txt;
}
public void setTxt(File txt) {
this.txt = txt;
}
public String getTxtFileName() {
return txtFileName;
}
public void setTxtFileName(String txtFileName) {
this.txtFileName = txtFileName;
}
public String getTxtContentType() {
return txtContentType;
}
public void setTxtContentType(String txtContentType) {
this.txtContentType = txtContentType;
}
}
|
Markdown | UTF-8 | 4,693 | 2.703125 | 3 | [] | no_license | ---
title: 理論から学ぶデータベース実践入門 ch8 SELECTを攻略する (2/2)
tags:
- RDB
- SQL
- 勉強メモ
date: 2019-07-04T21:56:18+09:00
URL: https://wand-ta.hatenablog.com/entry/2019/07/04/215618
EditURL: https://blog.hatena.ne.jp/wand_ta/wand-ta.hatenablog.com/atom/entry/17680117127213419177
bibliography: https://gihyo.jp/book/2015/978-4-7741-7197-5
-------------------------------------
# リレーショナルではない操作
## リレーショナルな操作のおさらい
- SELECTによるリレーショナルな操作
| リレーションの演算 | SELECTによる表現 |
|--------------------|-----------------------------|
| 制限 | 基本形: WHERE句 |
| 射影 | 基本形: select list |
| 直積 | 基本形: FROM句, JOIN句 |
| 結合 | 基本形: FROM句, JOIN句 |
| 積 | 基本形: FROM句, JOIN句 |
| 和 | UNION |
| 差 | NOT EXISTSサブクエリ, MINUS |
| 属性名変更 | 基本形: select list |
| 拡張 | 基本形: select list |
- IN, ANY, EXISTSサブクエリはJOINとDISTINCTを用いて書けることが知られている
- 他のはリレーショナルな演算でない
- FROM句のサブクエリで集約を行っている場合など
## ソート
- ORDER BY句による結果セットの並べ替えはリレーショナルモデル上の演算ではない
- 何しろ集合の要素に順序はない
- ORDER BYはカーソルの操作である (SQL標準より)
- SELECT自身のではない
- アプリケーション開発上有用だが、リレーショナルモデルから逸脱する危険な要素であるため要注意
## 明示的に定義されていないカラム
- ROWID、ROWNUMなど
- やはり順序絡みなのでリレーショナルモデルを逸脱する。要注意
## ストアドファンクション(ユーザ定義関数)
- ストアドファンクションのロジックは手続き型で記述される
- ストアドファンクションがSELECTに含まれると、手続き型の処理になる
- オプティマイザ困惑
- SQLは宣言型プログラミング言語である
- 手続き型ロジックを持ち込むと破綻する
### コラム: 集約とGROUP BY
- GROUP BYは数学的には**「要約」**(Summarizatoin)だよ、という話
- リレーションからリレーションを求める
- 閉包である
- cf. 「集約」(Aggregate)はリレーションからスカラを求める
- 閉包でない
- 要約は拡張の一種
- リレーションの演算以外の何らかの方法で集計を行い、新たに属性を追加している
- 学生の人数を学科ごとに集計する例
```sql
SELECT department
, COUNT(*)
FROM students
GROUP BY department;
```
- 同等の結果を得るサブクエリ
```sql
SELECT department
, (SELECT COUNT(*)
FROM students
WHERE department = t1.department
) AS COUNT
FROM (SELECT DISTINCT
department
FROM students
) AS t1;
```
- 見出し列
```sql
SELECT DISTINCT
department
FROM students
```
- これに集計結果の列を追加している(拡張)
```sql
SELECT COUNT(*)
FROM students
WHERE department = t1.department
```
## リレーショナルではない操作の扱い方
- アプリケーション開発ではリレーショナルではない操作も必要
- 例: ソート
- 大事なのは、リレーショナルな操作とそうでない操作とを明確に区別すること
- 指針
- リレーショナルモデルの範疇でできることをリレーショナルではない操作で実装しない
- オプティマイザによる最適化はリレーショナルモデルの範疇で最大の威力を発揮するため
- リレーショナルモデルの範疇でうまく記述できないと思ったら、DB設計を見直す
- 見直しができない場合、泥沼に足を踏み入れることになる
- リレーショナルではない操作がどうしても必要な場合は、リレーショナルな操作に関するロジックを必ず先に行う
- 【補】リレーショナルな操作の入力はリレーション
- 先にリレーショナルではない操作を行ってしまうと、後にリレーショナルな操作を続けられない
# インデントでSQLを読みやすくする
- MySQL Workbenchとかでやると良いよ
|
JavaScript | UTF-8 | 1,435 | 2.84375 | 3 | [
"MIT"
] | permissive | const login = (event) => {
event.preventDefault();
const fileError = document.getElementById('file-error');
const email = document.querySelector('#email').value.trim();
const password = document.querySelector('#password').value.trim();
const url = 'http://localhost:5700/api/v1/auth/login?';
const options = {
method: 'POST',
headers: {
Accept: 'application/json, text/plain, */*',
'Content-type': 'application/json',
},
body: JSON.stringify({
email, password,
}),
};
fetch(url, options)
.then(response => response.json())
.then((data) => {
const err = 'Sorry, the credentials you provided is incorrect. try again';
if (data.error === err) {
fileError.innerHTML = err;
document.getElementById('email').oninput = () => {
fileError.innerHTML = '';
};
}
if (data.status === 200) {
const { token, user } = data.data[0];
localStorage.setItem('token', token);
if (user.isadmin === true) {
setTimeout(() => {
window.location.href = ('admin_dashboard.html');
}, 5000);
} else {
setTimeout(() => {
window.location.href = ('profile.html');
}, 5000);
}
}
})
.catch((error) => {
console.log('System error', error);
});
};
document.querySelector('#login-form').addEventListener('submit', login);
|
Markdown | UTF-8 | 1,855 | 2.765625 | 3 | [] | no_license | # 反射
1. 什么是反射
- 要了解反射的原理,首先要了解什么是类型信息。Java在运行时识别对象和类的信息,主要有两种方式。
- 传统的RTTI,它假定我们在编译时已经知道了所有的类型信息
- 反射机制,允许在运行时发现和使用类的信息
- Java反射机制都是在运行状态中,对于任意一个类,都能知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取信息以及动态调用对象的方法的功能称为Java语言的反射机制。
2. 反射主要用途
- 框架编写
- ...
3. 反射的基本运用
- 获取Class对象
- 对象.getClass()
- 任何数据类型.class
- Class.forName(String className)——常用
- 创建实例
- 获取field
- getFiled: 访问公有的成员变量
- getDeclaredField:所有已声明的成员变量。但不能得到其父类的成员变量
- getFileds和getDeclaredFields用法同上(参照Method)
- 获取method
- 反射main方法
- 调用method
- 获取constractor
- 利用反射创建数组
- 反射方法的其他使用之——通过反射运行配置文件
- 读取文件时的路径问题
- 反射其他用法之---通过反射越过类型检查
- 泛型用在编译器期,编译过后泛型擦出(消失掉)。所以可以通过反射越过泛型检查。
4. 反射的一些注意事项
> reference1: https://www.cnblogs.com/luoxn28/p/5686794.html
reference2: https://www.sczyh30.com/posts/Java/java-reflection-1/#%E4%B8%80%E3%80%81%E5%9B%9E%E9%A1%BE%EF%BC%9A%E4%BB%80%E4%B9%88%E6%98%AF%E5%8F%8D%E5%B0%84%EF%BC%9F
reference3: https://blog.csdn.net/sinat_38259539/article/details/71799078
reference4: https://www.cnblogs.com/bojuetech/p/5896551.html |
Markdown | UTF-8 | 7,668 | 2.953125 | 3 | [] | no_license | ### 1. "좋은" 소프트웨어에 필수적인 속성들
Maintainability
dependability and security
efficiency and acceptability
### 2. 다른 속성들 제안?
Reusability (can it be reused in other applications) : 재사용성
Portability (can it operate on multiple platforms) : 사용성 (모바일, 랩탑 등 다양한 환경에서 동작 가능해야 함)
Inter-operability (can it work with a wide range of other software systems) : 상호 운용성
### 3. Software engineering is an engineering discipline whose focus is the ( cost-effective ) development of ( high-quality ) software systems.
소프트웨어 공학은 비용 효율적으로 고품질의 소프트웨어를 만들기 위함
---
## 프로젝트 관리자로서 어떤 일을 해야할까?
프로젝트를 제안하고, 프로젝트가 채택 되었을 때 여러가지 **계획**을 한다.
일정, 예산, 사건 사고 등등을 계획, 시작 되면 잘 진행되고 있는지 체크한다.
⇒ 정해진 예산, 마감 기한에 맞추기 위해서는 프로젝트를 효율적으로 진행하기 위한 `계획`을 세워야 한다.
## 프로젝트 계획
- 일을 여러 부분으로 나누고, 나눈 일들을 팀 구성원에게 할당
- 프로젝트를 진행하는 동안 발생할 수 있는 여러 가지 문제를 예측해 솔루션을 준비
→ 어떻게? 구성원이 빠지거나 장비 확보가 늦어 지거나 하는 등
- 일이 어떻게 진행될 것인지 구성원에게 알려줄 수 있음
- 진행 상황을 어떻게 평가할 것인지에 사용 (계획대로 되고 있는지)
## 프로젝트 계획 단계(Planning stages)
- 제안 단계(proposal)
고객의 요구사항에 따라 계획을 세워 가격 책정
목적: 고객한테 산출물에 대한 가격 정보를 주기 위함
→ 가격: 개발 투입 인력, 하드&소프트웨어 장비, 사용 비용, 출장비, 교육비 등등 (개발 비용을 고려해서 산정하나 청구 비용과 다름)
- 시작 단계: 계획을 수행
- 진행 단계: 진행 상황을 모니터링, 평가, 주기적으로 계획을 수정
→ 유난히 일이 오래 걸린다면 다시 계획을 수정
## 개발 비용에 영향을 미치는 요인들
- 시장 기회(Market opportunity)
새로운 시장에 진입하고자 하거나, 시장 경험을 얻고자 하는 경우 가격을 일단 저렴하게 책정, 추후 차차 높임
- 계약 조건(Contractual terms)
코드가 전달 되지 않았다면 추후 유지 보수 등으로 비용을 청구 할 수 있기 때문에 보다 저렴하게 책정 가능, 코드 소유권까지 넘긴다면 보다 많이 책정
- 요구 사항 변경(Requirements volatility)
저렴한 가격으로 계약 이후, 요구사항이 변경되면 추가적으로 요구 가능
- 재정 상태에 따라 (Financial health)
일이 없어서 문 닫기 직전이면 가격을 낮춰 일을 하고자 할 수 있음
## 계획 기반 개발(Plan-driven development)
: 개발 프로세스를 모두 세부적으로 계획하는 software approach
대규모 프로젝트 개발을 관리하는 전통적인 방법.
수행할 작업을 설정하고 인력 배분, 일정 관리, 최종 산출물 계획
- 장점: 진행 과정 동안 발생할 수 있는 문제들을 미리 대비 가능
- 단점: 초기에 세워둔 계획을 많이 수정해야 할 수 있음
- 계획 단계에 들어가야 할 내용들
Introduction: 프로젝트 소개, 목적이나 제약 사항
Project organization: 프로젝트 조직
Risk analysis: 위험 분석(발생할 수 있는 문제와 대처방안)
Hardware and software resource requirements: 자원 요구 사항(장비와 인도 날짜 등)
Work breakdown: 작업 배분
Project schedule: 스케쥴
Monitoring and reporting mechanisms: 모니터링과 보고 방안
→ 프로젝트 관리자는 이렇게 작성한 계획을 기반으로 프로젝트 진행상황을 체크, 의사결정을 지원하기 위해서도 사용
## 다른 계획들(Project plan supplements)
: 프로젝트의 특성이나 개발 조직에 따라 다른 계획들이 필요할 수 있다.
Quality plan (품질 계획): 품질 보증 절차와 표준
Validation plan (검증 계획): 중간 산출물 검증 방안
Configuration management plan (형상 관리 계획): 개발물 버전 관리
Maintenance plan (유지보수 계획): 예상되는 유지보수 내역과 노력
Staff development plan (인력 관리 계획): 팀 구성원들의 능력 향상
## 계획 과정(The planning process)
프로젝트 진행 시 ***계획 변경이 불가피*** 하기 때문에 계획은 반복 되는 프로세스
비지니스 목표가 변경될 경우 프로젝트 계획을 완전히 다시 해야 할 수도 있다.
<img width="660" alt="스크린샷 2020-09-10 오전 10 15 33" src="https://user-images.githubusercontent.com/45806836/92670250-915cd400-f34e-11ea-8785-389a007f91f5.png">
## 프로젝트 스케쥴링(Project scheduling activities)
: 프로젝트의 일을 작업으로 분할하고, 나눠진 일들을 완료하기 위해 필요한 시간과 자원을 추정.
- 남는 인력이 없어야 함: 가능한 동시에 작업하도록 구성
- 동시 작업을 위해선: 종속성이 있는 작업들 최소화
종속성: 어떤 일을 끝내야만 할 수 있는 일들
프로젝트 관리자의 직관과 경험에 달려있음
## 스케쥴링 할 때의 문제
- 개발 비용을 산정하기 어려움 (생산성은 개발 인력에 비례하지 않으며 각 개발자의 역량을 측정하기 어려움)
- 진행 지연 시 개발 인력을 투입하면 communication overhead 발생 가능
- 예기치 못 한 문제는 항상 발생. 항상 우발적인 일들이 발생할 것을 염두
## Milestones & deliverables
- Milestone: 소프트웨어는 실체가 없기 때문에 진행 상황을 파악하기 어려워 진행 상황을 평가할 수 있는 이정표
→ 각 task 들이 완료되면 얻어지는, 중간 관리를 위한 중간 산출물
- deliverable: 고객한테 최종적으로 전달되는 산출물
→ 최종 산출물 뿐 아니라 각종 문서들 포함
<img width="660" alt="스크린샷 2020-09-10 오전 10 15 33" src="https://user-images.githubusercontent.com/45806836/92670250-915cd400-f34e-11ea-8785-389a007f91f5.png">
## 스케쥴링 표기 방법
: 1~2주 정도 걸리는 task들로 나눠 스케쥴링을 표기. graphical notation 사용
- 바(간트) 차트: 달력에 일정을 표기하는 방식
- 액티비티 차트: 각 작업 별로 종속성을 보여줄 수 있는 방식
기간, 산출물(Milestone), critical path 모두 표기해야함
→ critical path: 프로젝트를 완료하는데 걸리는 최소 시간. 산정 가능
→ 액티비티 차트에서 가장 시간이 오래 걸리는 방법을 찾는다.
## Tasks, durations, and dependencies
<img width="708" alt="스크린샷 2020-09-10 오전 10 17 46" src="https://user-images.githubusercontent.com/45806836/92670382-e13b9b00-f34e-11ea-8e4a-a0b82f4ac0c5.png">
## Bar chart
<img width="694" alt="스크린샷 2020-09-10 오전 10 18 37" src="https://user-images.githubusercontent.com/45806836/92670449-00d2c380-f34f-11ea-9ff8-e74e63926a3c.png">
## Activity chart
<img width="693" alt="스크린샷 2020-09-10 오전 10 19 09" src="https://user-images.githubusercontent.com/45806836/92670479-134cfd00-f34f-11ea-917d-f4dd54c34a7e.png">
|
C# | UTF-8 | 1,430 | 2.84375 | 3 | [
"MIT"
] | permissive | using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace YNA.Graphics2D
{
public class SpritePlayer : Sprite
{
private float currentFrame;
private int maxFrame;
private bool isMoving;
public bool IsMoving
{
get { return isMoving; }
set { isMoving = value; }
}
// TODO créer une structure avec tout ce bordel ;-D ca sera moins merdique à passer en paramètre
public SpritePlayer (SpriteConfiguration spriteConfiguration, int maxFrame)
: base (ref spriteConfiguration)
{
this.currentFrame = 0;
this.maxFrame = maxFrame;
this.isMoving = false;
}
public override void Update (GameTime gameTime)
{
if (maxFrame != 0)
{
currentFrame += gameTime.ElapsedGameTime.Milliseconds * 0.01f;
if (currentFrame > maxFrame)
currentFrame = 0;
sourceRectangle = new Rectangle (
(int)currentFrame * sourceRectangle.Value.Width,
sourceRectangle.Value.Y,
sourceRectangle.Value.Width,
sourceRectangle.Value.Height);
}
}
}
}
|
Java | UTF-8 | 789 | 2.421875 | 2 | [] | no_license | package org.molgenis.omx.converters;
import static org.testng.Assert.assertEquals;
import org.molgenis.omx.observ.value.BoolValue;
import org.molgenis.util.tuple.KeyValueTuple;
import org.testng.annotations.Test;
public class TupleToBoolValueConverterTest
{
@Test
public void extractValue() throws ValueConverterException
{
BoolValue value = new BoolValue();
value.setValue(Boolean.TRUE);
assertEquals(new TupleToBoolValueConverter().extractValue(value), Boolean.TRUE);
}
@Test
public void fromTuple() throws ValueConverterException
{
String colName = "col";
KeyValueTuple tuple = new KeyValueTuple();
tuple.set(colName, true);
BoolValue value = new TupleToBoolValueConverter().fromTuple(tuple, colName, null);
assertEquals(value.getValue(), Boolean.TRUE);
}
}
|
C++ | UTF-8 | 2,162 | 2.984375 | 3 | [] | no_license | #include<iostream>
#include<fstream>
#include<cctype>
#include<iomanip>
#include<string>
#include <sstream>
#include"player.h"
#include"game.h"
using namespace std;
void PlayerMenu();
void intro()
{
char input;
bool nt = true;
do {
system("cls");
cout << "\n\n\tNew Tournament?";
cout << "\n\n\ty\tn";
cout << "\n\t> ";
cin >> input;
if (input == 'y' || input == 'Y')
{
nt = true;
// Alle bestanden resetten!
}
else if (input == 'n' || input == 'N')
{
nt = false;
}
else
{
cout << "\n\n\tInput not recognised!\n\n\tUse y for yes or n for no!\n\n\t";
nt = true;
system("pause");
}
} while (nt);
}
void MainMenu()
{
char ch;
do {
system("cls");
cout << "\n\n\tTournament Planner (v1)";
cout << "\n\n\tMain Menu";
cout << "\n\t---------";
cout << "\n\n\t1. List Players";
cout << "\n\n\t2. Modify Players";
cout << "\n\n\t3. Generate Games";
cout << "\n\n\t4. Adjust Game";
cout << "\n\n\t5. Set Results";
cout << "\n\n\t6. Exit Tournament Planner";
cout << "\n\n\t> ";
cin >> ch;
switch (ch)
{
case '1':
ListPlayers();
system("pause");
break;
case '2':
PlayerMenu();
break;
case '3':
break;
case '4':
break;
case '5':
break;
case '6':
break;
default:cout << "\a";
}
} while (ch != '6');
}
void PlayerMenu()
{
char ch;
do {
system("cls");
cout << "\n\n\tTournament Planner (v1)";
cout << "\n\n\tPlayer Menu";
cout << "\n\t---------";
cout << "\n\n\t1. List Players";
cout << "\n\n\t2. Add Player";
cout << "\n\n\t3. Add Player From File";
cout << "\n\n\t4. Modify Player";
cout << "\n\n\t5. Delete Player";
cout << "\n\n\t6. Delete All Players";
cout << "\n\n\t7. Return To Main Menu";
cout << "\n\n\t> ";
cin >> ch;
switch (ch)
{
case '1':
ListPlayers();
system("pause");
break;
case '2':
ManualNewPlayer();
break;
case '3':
break;
case '4':
ModifyPlayer();
break;
case '5':
DeletePlayer();
break;
case '6':
break;
case '7':
break;
default:cout << "\a";
}
} while (ch != '7');
return;
}
int main()
{
//intro();
MainMenu();
system("Pause");
} |
Rust | UTF-8 | 4,355 | 2.53125 | 3 | [] | no_license | use std::{fmt, io};
use pas_common::span::Span;
use pas_common::{Backtrace, DiagnosticLabel, DiagnosticMessage, DiagnosticOutput, TracedError};
use pas_interpreter::result::ExecError;
use pas_pp::PreprocessorError;
use pas_syn::parse::ParseError;
use pas_syn::TokenizeError;
use pas_typecheck::TypecheckError;
#[derive(Debug)]
pub enum CompileError {
TokenizeError(TracedError<TokenizeError>),
ParseError(TracedError<ParseError>),
TypecheckError(TypecheckError),
PreprocessorError(PreprocessorError),
InvalidUnitFilename(Span),
OutputFailed(Span, io::Error),
ExecError(ExecError),
}
impl From<TracedError<TokenizeError>> for CompileError {
fn from(err: TracedError<TokenizeError>) -> Self {
CompileError::TokenizeError(err)
}
}
impl From<TracedError<ParseError>> for CompileError {
fn from(err: TracedError<ParseError>) -> Self {
CompileError::ParseError(err)
}
}
impl From<TypecheckError> for CompileError {
fn from(err: TypecheckError) -> Self {
CompileError::TypecheckError(err)
}
}
impl From<PreprocessorError> for CompileError {
fn from(err: PreprocessorError) -> Self {
CompileError::PreprocessorError(err)
}
}
impl From<ExecError> for CompileError {
fn from(err: ExecError) -> Self {
CompileError::ExecError(err)
}
}
impl DiagnosticOutput for CompileError {
fn main(&self) -> DiagnosticMessage {
match self {
CompileError::TokenizeError(err) => err.err.main(),
CompileError::ParseError(err) => err.err.main(),
CompileError::TypecheckError(err) => err.main(),
CompileError::PreprocessorError(err) => err.main(),
CompileError::OutputFailed(span, err) => DiagnosticMessage {
title: format!(
"Writing output file `{}` failed: {}",
span.file.display(),
err
),
label: None,
},
CompileError::InvalidUnitFilename(at) => DiagnosticMessage {
title: "Invalid unit filename".to_string(),
label: Some(DiagnosticLabel {
text: None,
span: at.clone(),
}),
},
CompileError::ExecError(ExecError::Raised { msg, .. }) => DiagnosticMessage {
title: msg.clone(),
label: None,
},
CompileError::ExecError(err) => err.main(),
}
}
fn see_also(&self) -> Vec<DiagnosticMessage> {
match self {
CompileError::TokenizeError(err) => err.see_also(),
CompileError::ParseError(err) => err.see_also(),
CompileError::TypecheckError(err) => err.see_also(),
CompileError::PreprocessorError(err) => err.see_also(),
CompileError::OutputFailed(..) => Vec::new(),
CompileError::InvalidUnitFilename(..) => Vec::new(),
CompileError::ExecError(..) => Vec::new(),
}
}
fn backtrace(&self) -> Option<&Backtrace> {
match self {
CompileError::TokenizeError(err) => Some(&err.bt),
CompileError::ParseError(err) => Some(&err.bt),
CompileError::TypecheckError(_) => None,
CompileError::PreprocessorError(_) => None,
CompileError::InvalidUnitFilename(_) => None,
CompileError::OutputFailed(..) => None,
CompileError::ExecError(..) => None,
}
}
}
impl fmt::Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
CompileError::TokenizeError(err) => write!(f, "{}", err.err),
CompileError::ParseError(err) => write!(f, "{}", err.err),
CompileError::TypecheckError(err) => write!(f, "{}", err),
CompileError::PreprocessorError(err) => write!(f, "{}", err),
CompileError::InvalidUnitFilename(span) => write!(
f,
"invalid unit identifier in filename: {}",
span.file.display()
),
CompileError::OutputFailed(span, err) => {
write!(f, "writing to file {} failed: {}", span.file.display(), err,)
}
CompileError::ExecError(err) => write!(f, "{}", err),
}
}
}
|
C# | UTF-8 | 2,634 | 2.53125 | 3 | [] | no_license | using System;
using System.Windows;
using System.Windows.Controls;
using MovieRentalSystemDataBase;
using MovieRentalSystemDataBase.QueryTypes;
namespace MovieRentalSystemWPF
{
/// <summary>
/// Logika interakcji dla klasy ViewsPage.xaml
/// </summary>
public partial class ViewsPage : Page
{
public DBConnector Connector { get; set; }
public string Query { get; set; }
public ViewsPage()
{
InitializeComponent();
}
public ViewsPage(DBConnector connector) : this()
{
Connector = connector;
Query = "SELECT * FROM users;";
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
switch (ComboBox.SelectedIndex)
{
case 0:
Query = "SELECT * FROM users;";
break;
case 1:
Query = "SELECT * FROM addresses;";
break;
case 2:
Query = "SELECT * FROM directors;";
break;
case 3:
Query = "SELECT * FROM movie_genres;";
break;
case 4:
Query = "SELECT * FROM movies;";
break;
case 5:
Query = "SELECT * FROM rentals;";
break;
case 6:
Query = "SELECT * FROM workers;";
break;
case 7:
Query = "SELECT * FROM a_detailed_list_of_rental;";
break;
case 8:
Query = "SELECT * FROM genres_count_by_movies;";
break;
case 9:
Query = "SELECT * FROM informations_about_films;";
break;
case 10:
Query = "SELECT * FROM user_account_summary;";
break;
case 11:
Query = "SELECT * FROM users_age;";
break;
case 12:
Query = "SELECT * FROM users_and_adresses;";
break;
}
var view = new Select(Connector, Query);
try
{
var viewDataTable = view.ExecuteQuery();
DataGrid.DataContext = viewDataTable.DefaultView;
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
}
}
}
|
JavaScript | UTF-8 | 2,518 | 3.109375 | 3 | [] | no_license | // html elemanlarını değişkenlere atıyoruz
const form = document.getElementById("form1");
const userName = document.getElementById("userName");
const password = document.getElementById("password");
const email = document.getElementById("email");
const checkbox = document.getElementById("checkbox");
let span = document.getElementById("error");
// form'a "submit" eventi ekliyoruz
form.addEventListener("submit", e => {
e.preventDefault();
checkInputs();
})
// değerlerin başında ve sonunda olabilecek boşluklardan arındırıp yeni bir değişkene atıyoruz
function checkInputs() {
const userNameValue = userName.value.trim();
const passwordValue = password.value.trim();
const emailValue = email.value.trim();
// validation sorguları
if (userNameValue === "") {
errorMessage(userName,"Lütfen bu alanı doldurunuz")
userName.setAttribute("style","border:1px solid red;")
}
if (passwordValue === "") {
errorMessage(password,"Lütfen bu alanı doldurunuz")
password.setAttribute("style","border:1px solid red;")
}
else if (passwordValue.length < 8) {
errorMessage(password,"Şifreniz minimum 8 karakter olmalı")
password.setAttribute("style","border:1px solid red;")
}
if (emailValue === "") {
errorMessage(email,"Lütfen bu alanı doldurunuz")
email.setAttribute("style","border:1px solid red;")
}
else if (!isEmail(emailValue)){
errorMessage(email,"Lütfen geçerli bir email giriniz")
email.setAttribute("style","border:1px solid red;")
}
if (checkbox.checked == false) {
errorMessage(checkbox,"Lütfen bu alanı doldurunuz")
}
}
// hata mesajlarını vermemizi sağlayan fonksiyon
function errorMessage(input,message) {
const formBody = input.parentElement;
const span = formBody.querySelector("span");
span.innerText = message;
}
// email kontrolünü sağlayan fonksiyon
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
// validationların sağlandığı zaman hata mesajlarını ortadan kaldıran fonksiyon
function inputChange(input) {
let newInput = input.parentElement;
let newSpan = newInput.querySelector("span")
newSpan.innerText = "";
input.setAttribute("style","border:1px solid green;")
}
|
Markdown | UTF-8 | 1,247 | 3.15625 | 3 | [] | no_license | # 我的餐廳清單
一個使用 Node.js + Express 打造的餐廳美食網站,可以查看自己的餐廳清單並依照特定方式進行排序、依照餐廳名稱與類別進行搜尋,在查詢不到關鍵字餐廳時,頁面會有提示沒有符合的餐廳、同時在每個餐廳列表中,可以進行修改及刪除表上餐廳,也可以任意新增自己喜歡的餐廳名單。
## 產品功能
1. 使用者可以點擊任一餐廳,查看更多餐廳資訊,如地址、電話與簡介
2. 使用者可以依照中文名稱、餐廳類別進行搜尋
3. 使用者可以新增新的餐廳
4. 使用者可以編輯目前已有餐廳內容
5. 使用者可以刪除餐廳
## 環境建置與需求
- Express: "^1.4.1"
- Bootstrap-icon: "^4.17.1"
- express-handlebars: "^5.3.0"
## 安裝與執行步驟
打開終端機將專案下載至本地執行
```
git clone https://github.com/tinahung126/restaurantList.git
```
進入專案資料夾
```
cd restaurant_list_crud
```
安裝專案需求套件
```
npm i nodemon
```
新增種子資料
```
npm run seed
```
啟動伺服器,執行專案
```
npm run dev
```
終端機顯示 Start listening on http://localhost:3000 即成功啟動,可至 http://localhost:3000 開始使用! |
C++ | UTF-8 | 903 | 2.59375 | 3 | [] | no_license | //: C09:Database.h
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// A prototypical resource class.
#ifndef DATABASE_H
#define DATABASE_H
#include <iostream>
#include <stdexcept>
#include <string>
struct DatabaseError : std::runtime_error {
DatabaseError(const std::string& msg)
: std::runtime_error(msg) {}
};
class Database {
std::string dbid;
public:
Database(const std::string& dbStr) : dbid(dbStr) {}
virtual ~Database() {}
void open() throw(DatabaseError) {
std::cout << "Connected to " << dbid << std::endl;
}
void close() {
std::cout << dbid << " closed" << std::endl;
}
// Other database functions...
};
#endif // DATABASE_H ///:~
|
Python | UTF-8 | 190 | 4.03125 | 4 | [
"MIT"
] | permissive |
shopping = ["bread", "cheese", "apple", "tomato", "biscuits"]
count = 0
for item in shopping:
print(item)
count = count + 1
print('You have', count, 'items in your shopping list') |
JavaScript | UTF-8 | 1,361 | 2.703125 | 3 | [] | no_license | let mongoose = require('mongoose')
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true)
mongoose.connect('mongodb://localhost/blog_demo')
// POST - title, content
let PostSchema = new mongoose.Schema({
title : String,
content : String
})
let Post = mongoose.model('Post', PostSchema)
// USER - email, name
let UserSchema = new mongoose.Schema({
email : String,
name : String,
posts : [PostSchema]
})
let User = mongoose.model('User', UserSchema)
let newUser = new User({
email : 'hermione@hogwarts.edu',
name : 'Herminoe Granger'
})
newUser.posts.push({
title : 'how to bre poly juice portion',
content : 'Just Kidding. Go to portions class to learn it!'
})
newUser.save((err, user) => {
if(err){
console.log(err)
} else {
console.log(user)
}
})
let newPost = new Post({
title : 'Charlie`s post',
content : 'The post of Charlie'
})
newPost.save((err, post) => {
if(err) {
console.log(err)
} else {
console.log(post)
}
})
User.findOne({name: 'Herminoe Granger'}, (err, user) => {
if (err) {
console.log(err)
} else {
// console.log(user)
user.posts.push({
title: "The project",
content : "IDKWAWT"
})
user.save((err, user) => {
if(err) {
console.log(err)
} else {
console.log(user)
}
})
}
})
|
Java | UTF-8 | 878 | 2.546875 | 3 | [] | no_license | package com.newtours.stepdefinitions;
import com.newtours.seleniumdriver.PageActions;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class StepDefGoogle {
PageActions pageActions = new PageActions();
@Given("que lanzo el navegador")
public void que_lanzo_el_navegador() {
pageActions.launcheBrowser("chrome");
}
@When("abro la pagina de inicio en Google")
public void abro_la_pagina_de_inicio_en_Google() {
pageActions.openBrowserUrl("https://www.google.com/");
}
/*@Then("busco {string} y {int} en Google")
public void busco_y_en_Google(String string, Integer int1) {
// Write code here that turns the phrase above into concrete actions
pageActions.typeInTextBox(By.name("q"), string + " "+ int1);
pageActions.clickOnButton(By.name("btnK"));
pageActions.closeBrowser();
}
*/
}
|
PHP | UTF-8 | 1,581 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Laravel\VaporCli\Commands;
use Laravel\VaporCli\Helpers;
use Symfony\Component\Console\Input\InputArgument;
class CertListCommand extends Command
{
/**
* Configure the command options.
*
* @return void
*/
protected function configure()
{
$this
->setName('cert:list')
->addArgument('domain', InputArgument::OPTIONAL, 'The domain name to list certificates for')
->setDescription('List the certificates linked to your account');
}
/**
* Execute the command.
*
* @return void
*/
public function handle()
{
Helpers::ensure_api_token_is_available();
$certificates = $this->vapor->certificates(
$this->argument('domain')
);
if (empty($certificates)) {
Helpers::abort('You do not have any certificates.');
}
$this->table([
'ID', 'Provider', 'Domain', 'Alternative Domains', 'Status', 'Active', 'Created',
], collect($certificates)->map(function ($certificate) {
return [
$certificate['id'],
$certificate['cloud_provider']['name'],
$certificate['domain'],
implode(', ', $certificate['alternative_names']) ?: '-',
ucwords(str_replace('_', ' ', $certificate['status'])),
($certificate['used_by_active_deployment'] ?? false) ? '<info>✔</info>' : '',
Helpers::time_ago($certificate['created_at']),
];
})->all());
}
}
|
C | UTF-8 | 300 | 3.125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,k;
scanf("%d %d\n",&n,&k);
int a[n];
for(i=1;i<=n;i++)
{
scanf("%d\n",&a[i]);
}
int ctr=0;
for(i=1;i<=n;i++)
{
if(a[i]%k==0)
{
ctr=ctr+1;
}
}
printf("%d",ctr);
return 0;
}
|
Java | UTF-8 | 6,448 | 2.125 | 2 | [] | no_license | package com.example.bookstore.ui;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.bookstore.MainActivity;
import com.example.bookstore.R;
import com.example.bookstore.db.BookStoreDataBase;
import com.example.bookstore.entity.Book;
import com.example.bookstore.entity.Category;
import com.example.bookstore.util.FileHelper;
import com.example.bookstore.util.include.TopBarCustomer;
import com.skydoves.powerspinner.OnSpinnerItemSelectedListener;
import com.skydoves.powerspinner.PowerSpinnerView;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import es.dmoral.toasty.Toasty;
public class BooksAddActivity extends AppCompatActivity {
private final List<Integer> categoriesIdList = new ArrayList<>();
private final List<String> categoriesNameList = new ArrayList<>();
private final HashMap<String, Integer> categoriesMap = new HashMap<>();
private final FileHelper fileHelper = new FileHelper();
private final TopBarCustomer topBarCustomer = new TopBarCustomer(this, "添加新图书");
Integer category_id;
private ImageView image_button;
private BookStoreDataBase appDb;
private Bitmap selectedImage = null;
@Override
protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
appDb = BookStoreDataBase.getInstance(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
Intent i = getIntent();
boolean if_edit = i.getBooleanExtra("if_edit", false);
topBarCustomer.init(getWindow().getDecorView());
categoriesParse();
PowerSpinnerView powerSpinnerView = findViewById(R.id.spinner_book_category);
powerSpinnerView.setItems(categoriesNameList);
powerSpinnerView.setOnSpinnerItemSelectedListener((OnSpinnerItemSelectedListener<String>) (oldIndex, oldItem, newIndex, newItem) -> {
category_id = categoriesMap.get(newItem);
});
image_button = findViewById(R.id.add_image_button);
Button submit_button = findViewById(R.id.add_new_book_button);
EditText book_name = findViewById(R.id.new_book_name);
EditText book_author = findViewById(R.id.new_book_author);
EditText book_description = findViewById(R.id.new_book_description);
image_button.setOnClickListener(v -> {
Intent pickPhoto = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
});
// 如果是修改图书,装入之前的数据
if (if_edit) {
selectedImage = fileHelper.loadImageBitmap(this, "book", i.getStringExtra("book_id"));
image_button.setImageBitmap(selectedImage);
TextView image_text = findViewById(R.id.add_image_text);
image_text.setText("修改图书图片");
submit_button.setText("修改");
book_name.setText(i.getStringExtra("book_name"));
book_author.setText(i.getStringExtra("book_author"));
book_description.setText(i.getStringExtra("book_description"));
// 设置下拉列表默认位置
powerSpinnerView.selectItemByIndex(
categoriesIdList.indexOf(
Integer.parseInt(
i.getStringExtra("book_category_id"))));
}
submit_button.setOnClickListener(v -> {
try {
String message, book_id;
Book book = new Book(
book_name.getText().toString(),
book_description.getText().toString(),
book_author.getText().toString(),
category_id
);
if (if_edit) {
message = "修改新图书成功。";
book_id = i.getStringExtra("book_id");
book.setId(Integer.parseInt(book_id));
appDb.bookDao().updateBook(book);
} else {
message = "添加新图书成功。";
book_id = appDb.bookDao().insertBook(book).get(0) + "";
}
fileHelper.saveImage(BooksAddActivity.this, selectedImage, "book", book_id);
Toasty.success(getApplicationContext(),
message,
Toast.LENGTH_SHORT,
true).show();
Intent intent = new Intent(BooksAddActivity.this, MainActivity.class);
startActivity(intent);
finish();
} catch (Exception e) {
e.printStackTrace();
}
});
}
// 图书种类id与图书种类名双向绑定
private void categoriesParse() {
List<Category> categoryList = appDb.categoryDao().getAllCategories();
for (Category c : categoryList) {
categoriesIdList.add(c.getId());
categoriesNameList.add(c.getName());
categoriesMap.put(c.getName(), c.getId());
}
}
// 读取相册图片
@Override
protected void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if (resultCode == RESULT_OK) {
final Uri imageUri = data.getData();
final InputStream imageStream;
try {
imageStream = getContentResolver().openInputStream(imageUri);
selectedImage = BitmapFactory.decodeStream(imageStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
// 在相册界面切回app时更新图片
@Override
public void onResume() {
super.onResume();
if (selectedImage != null) {
image_button.setImageBitmap(selectedImage);
image_button.setPadding(0, 0, 0, 0);
}
}
}
|
Java | UTF-8 | 892 | 1.875 | 2 | [] | no_license | package com.liangzi.mapper;
import com.liangzi.pojo.TCustomerId;
import com.liangzi.pojo.TCustomerIdExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TCustomerIdMapper {
long countByExample(TCustomerIdExample example);
int deleteByExample(TCustomerIdExample example);
int deleteByPrimaryKey(Long id);
int insert(TCustomerId record);
int insertSelective(TCustomerId record);
List<TCustomerId> selectByExample(TCustomerIdExample example);
TCustomerId selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") TCustomerId record, @Param("example") TCustomerIdExample example);
int updateByExample(@Param("record") TCustomerId record, @Param("example") TCustomerIdExample example);
int updateByPrimaryKeySelective(TCustomerId record);
int updateByPrimaryKey(TCustomerId record);
} |
C++ | UTF-8 | 2,176 | 3.171875 | 3 | [] | no_license | //
// @authors:
// Martin Runelöv
// Philip Sköld
//
#include "dijkstras.h"
vector<int> dist; // min pathlengths from single source for each node.
struct Cmp
{
bool operator() (int n1, int n2) const
{
if (dist[n1] != dist[n2])
return dist[n1] < dist[n2];
return n1 > n2;
}
};
int reachableAt(edge e, int t)
{
if (e.P == 0) { // special case. can only use edge once at time e.t
if(t > e.t)
return -1;
if (t == e.t)
return 0;
}
if (t < e.t) return e.t-t; // we haven't reached the starting time yet.
// The last modulo e.P is only used when we get (t-e.t)%e.P == e.P,
// to return 0 instead of e.P - 0 = e.P.
return (e.P - ((t-e.t)%e.P))%e.P; // wait depending on time left until a multiple of e.P after e.t
}
vector<int> dijkstras_ss(graph& G, int start)
{
dist.clear();
dist.resize(G.N, INT_MAX);
vector<int> parent(G.N, -1); // parent vector that can be traversed to construct paths
parent[start] = -1;
dist[start] = 0;
set<int, Cmp> q;
q.insert(start);
while (!q.empty())
{
int u = *q.begin(); // top/front
q.erase(q.begin()); // pop
vector<edge> adjacent = G.getAdj(u);
rep(i, 0, adjacent.size())
{
int d = dist[u] + adjacent[i].w;
int v = adjacent[i].to;
if (d < dist[v])
{
if (q.count(v))
q.erase(v);
dist[v] = d;
parent[v] = u;
q.insert(v);
}
}
}
return dist;
// return parent; // paths;
}
vector<int> dijkstras_ss_tt(graph& G, int start)
{
dist.clear();
dist.resize(G.N, INT_MAX);
vector<int> parent(G.N, -1); // parent vector that can be traversed to construct paths
parent[start] = -1;
dist[start] = 0;
set<int, Cmp> q;
q.insert(start);
while (!q.empty())
{
int u = *q.begin(); // top/front
q.erase(q.begin()); // pop
vector<edge> adjacent = G.getAdj(u);
rep(i, 0, adjacent.size())
{
int wait = reachableAt(adjacent[i], dist[u]);
if (wait == -1) // can't visit anymore
continue;
int d = dist[u] + adjacent[i].w + wait;
int v = adjacent[i].to;
if (d < dist[v])
{
if (q.count(v))
q.erase(v);
dist[v] = d;
parent[v] = u;
q.insert(v);
}
}
}
return dist; //
// return parent; // see documentation in header;
}
|
Markdown | UTF-8 | 13,566 | 2.953125 | 3 | [] | no_license | ---
layout: story
title: Living Together in Santa Cruz
subtitle: A peek into co-op life
date: 2011-04-14 00:10:20
categories: articles featured
tags: CHP
author: Michael Mott
publication: <a href="https://www.cityonahillpress.com/2011/04/14/living-together-in-santa-cruz/">City on a Hill Press</a>
---
<hr width="90%" align="middle" />

_Illustration by Bela Massex, photos by Prescott Watson._
<img src="{{ base.url }}/assets/img/post/coop1.png" alt="Coop right" style="float:right;padding: 5px" width="400">
The wall is plastered with bears. One is eating a human foot, while another holds a fish up like a trophy.
Live murals, good food and Edward Sharpe and the Magnetic Zeros fill up the common room, as friends and strangers meet for the Chavez Art Show. This is the Cesar Chavez Co-op, where UC Santa Cruz and Cabrillo College students have been living for nearly 20 years.
Chavez is a housing cooperative in which residents share rent, eat meals together, and are responsible for upkeep of the house. One of the biggest in Santa Cruz, Chavez holds close to 30 members.
Events like Chavez’s Art Show used to be a lot more common, says UCSC third-year Chavez resident, Nick Golden.
Neighbor relations, zoning problems, debt and a fire in 2005 all affected planned events and membership at Chavez. But Golden says that Chavez is making a comeback.
“We’re definitely on the up right now, which is really exciting to see,” he said. “We’re still working out some kinks with getting the house back on track in terms of work shifts and making sure people do them, and getting it into a fully functioning co-op, but it’s so much better than it’s been in the past.”
Housing co-ops are nothing new. The first housing cooperatives in the United States popped up in New York City in the late 1800s, initially serving the upper class. Eventually they became widely populated by union workers who didn’t want to live in the slums.
<div class="images" style="float:right">
<img src="{{ base.url }}/assets/img/post/coop4.jpg" alt="Chavez residents" width="300">
<div class="caption">
Chavez inhabitants
</div>
</div>
Since then, cooperatives have become a popular option for college students. Housing cooperatives have grown to over a million units across the country, according to the National Cooperative Business Association (NCBA). NCBA is a resource for cooperatives of all types, such as food, credit unions, agricultural, business and housing.
Currently, UC Berkeley has one of the largest network of student co-ops, with 17 houses and 1,300 students in the Berkeley Student Cooperative. Their network is solely focused on students, while most in Santa Cruz are open to anyone, including non-students.
Morgan Harris of the Food Not Lawns co-op off of Mission Street, said there are a lot of benefits for students living in cooperatives.
“As we move off to college we tend to go through this extremely individualistic and often isolationist kind of phase, so the value of co-ops is that it gives you sort of this family to connect back with,” Harris said. “It may not be as deep as your blood family, of course, but in terms of a place for you to grow and love, you really can get that community and get grounded.”
Chavez and Zami! on Laurel Street are two of the largest co-ops in Santa Cruz. They’re sister houses, meaning they make up an organization called the Santa Cruz Student Housing Cooperative (SCSHC), colliqually known as “Chazam.” They work together on projects, from building chicken coops to writing co-op cookbooks, and they also share a lease with a the North American Students of Cooperation (NASCO).
NASCO, founded in 1968, is an organization that helps educate co-ops across the country. It holds an annual conference, the NASCO Institute, where it tackles common issues with co-ops. Part of the company, NASCO Properties, also holds leases, and is working with Chazam to get its debt paid off and come back to its master lease. This is instead of the individual leases it has now, which provide a little more security for NASCO.
<div class="images" style="float:right">
<img src="{{ base.url }}/assets/img/post/coop6.jpg" alt="Zami residents"/>
<div class="caption">Zami house</div>
</div>
While individual leases give NASCO more financial security, NASCO is committed to helping Chazam get back on their feet, and gain more local control with a master lease,
Daniel Miller, NASCO’s director of development and property services, said that NASCO is there to help.
“The whole idea behind NASCO Properties is to help the local co-op get the tools they need to run their co-op,” he said in an email. “We try to help them understand the process of starting a new non-profit, doing outreach to find new members in their community and running their co-op legally and responsibly.”
<div class="images" style="float:right">
<img src="{{ base.url }}/assets/img/post/coop3.jpg" alt="Food Not Lawns residents"/ width="300">
<div class="caption">Food Not Lawns</div>
</div>
Other cooperatives in Santa Cruz either own their house, or have worked out a situation with their landlord to allow a cooperative to exist. Food Not Lawns is one such co-op.
Ducks quack and chickens cluck behind recent UCSC alumnus Harris, who sits on a wooden bench in the garden behind Food Not Lawns. Holding a cup of tea, Harris said a love of sustainability and farming unites them.
“We are here to learn how to garden and to learn how to live sustainably,” he said. “We’re fortunate, we’re blessed enough to have this space where we can do that, [in which] we can work in and play.”
The front lawn of the house, which sprouts off between Mission and Laurel, was completely dug up a few years ago and replaced with vegetables. In the back garden, greenhouses were installed and rows of lettuce, flowers and other plants grow. Food Not Lawns was founded by a group of UCSC students who had met at Pica, a green sustainability program based out of UCSC’s The Village.
Harris, who has been a member for a year and a half, will be teaching a Free Skool course this year, along with two of his housemates.
<img src="{{ base.url }}/assets/img/post/coop2.jpg" alt="Food Not Lawns residents" width="300" style="float:right;padding: 5px">
Free Skool, a community-driven education system loosely organized by residents of Santa Cruz, is all about free learning for anyone who wants it, by whoever wants to teach it.
“[As a co-op] we are teaching a lot of classes this quarter,” Harris said. “One’s about agroecology, horticulture and backyard composting, and then there are other fun ones that we do.”
Food Not Lawns has between eight and 10 members, and only half are students. Harris said personal history and education are not necessarily relevant to living in a co-op.
“We just want passionate people who want to learn more about this kind of lifestyle,” he said. “They just have to have a willingness to learn and be an open communicator, someone who wants to be part of a community.”
A death in the house, combined with zoning issues and member turnover, has brought down membership at Zami!.
Caity Fares sits on an old couch on the Zami! Patio. As music floats out of the house and holiday lights rest above, Fares remembers how they recovered.
“After all of the debt was brought to our attention as a serious problem, it was then that we started to come together and form a stronger collective, and you know, hold up the foundation,” she said.
In February, Chavezians and Zami!tes met to discuss the future of Chazam and the current state of their co-ops and their master lease. Flying in from Chicago, Miller from NASCO attended the joint-house meeting, and said NASCO is there to help in a supporting role.
He said that their goal is that within a few months, Chazam will have a plan of action as to what they want to do, and how they want to handle city regulations that limit the number of members they can have.
“NASCO Properties sees what’s happening now as a temporary step to try and help the co-op members get the tools they need to get back on track,” Miller said. “SCSHC has a mission to provide affordable housing to students to make education more accessible to them … NASCO Properties has a mission of helping local cooperatives fulfill their missions.”
City zoning laws limiting tenants create a number of problems for members of Zami!.
“The main issue is parking,” said Zami! resident November Skye. “We have to have a certain number of parking spots per person, and we’re looking into finding spots on the street that we can use.”
Two houses fill the property, along with a mini-barn and five cats. And the front house is sideways — Zami!’s main house once sat where the Louden Nelson Community Center is now.
In years past, most people entered Zami! through the pink and purple gate on the side — to enter through the front meant walking into someone’s bedroom.
Now though, that space is a common room. Similar transformations occurred throughout the house after the enforcement of city zoning laws forced residents to turn bedrooms into common spaces.
After necessary structural renovations, city officials saw how residents were living in more rooms then zoned for and forced the co-op to reduce its number of tenants.
“We feel like we kind of kicked ourselves, because the reason we ran into trouble was because we were finally getting our shit together and getting the renovations done,” Skye said.
Skye, who changed his name upon coming to Zami!, says living in a co-op allows people to change — they get to decide who they are.
“Here, you stop having to work off cultural scripts, of ‘this is what people are supposed to want, this is what I’m supposed to do,’ and it lets people live their own lives,” he said.
Once, with members sleeping in tents in the backyard and a family of six in the house, residents of Zami! numbered over 30 people.
It was difficult organizing that many people, let alone the normal challenges of co-ops, said Skye.
Occupants at both Chavez and Zami! devote five hours of “love-shifts” per week, making dinner, cleaning bathrooms, managing membership, etc., and are working toward being a really “progressive space,” Skye said.
“We try to focus on dispersing skills, especially across class and gender boundaries. It’s not OK when all the working-class people are doing dishes and all the middle class people are doing management positions,” he said.
A handwritten scrawl on the wall declares that the house was built in 1887. This kind of history is often the only way members can leave a lasting message in many co-ops, as houses change with every new generation of members.
“Every time we get new members, they ask about who we are and we get to decide that every year,” he said.
Co-ops provide a space in which communities can grow. Many co-ops tend to be particularly appealing to students because they are also often affordable.
“It is cheap,” said Breeze Kanikula, a member of the 12 Tribes Jewish Co-op. “And that’s a great thing.”
Low rent costs come at a price, however, said November Skye, third-year resident of the Zami! co-op on Laurel Street.
“Part of why it’s cheap is because you’re doing five hours of maintenance every week,” he said.
Posters of James Dean and classic movies line the living room walls, along with the 12 Tribes’ mission statement, which reads, “[12 Tribes] is a home for anyone interested in living communally while exploring Jewish culture, traditions, and values.”
This means that while most are Jewish, it isn’t a requirement.
“I’m not, and neither are the treasurer and one of the other girls,” Kanikula said. “I do participate in the culture though. I like it, it’s fun. I used to go to Shabbat when I was a kid, with my other Jewish friends.”
Kanikula said that there are certain things that their co-op does differently from others, though, being one of the few religious-based cooperatives in Santa Cruz.
“We do keep the fridge kosher and all of our dinner nights kosher,” she said. “We do have different pots and pans for meat and dairy.”
12 Tribes participates in the larger Santa Cruz Jewish community.
“Every Friday we do Shabbat with Hillel and Chabad house,” Kanikula said. “Hillel is a house for Jewish UCSC students, and Chabad is a national organization, where a rabbi lives in the house with his wife. Shabbat is from Friday at sundown to Saturday at sundown, and we’re not supposed to work or use any electricity, just be one with God.”
The culture of co-ops is continuing to thrive in Santa Cruz and has a promising future, as is evident through the creation of the Art Co-op in winter 2010. Their co-op is one of the smallest, with seven members, and was founded by two previous members of the 12 Tribes. According to founding member Sarah Jaffe, the group has aspirations to grow as a co-op.
“We’re trying to have shows a few times a quarter, and we all help each other out [with each others’ art],” she said.
Caity Fares of the Zami! co-op said a that a lot can be learned from living in a co-op, considering that it is a space that enables the integration of many types of people to form a single community.
“It helps you to understand how every person is dynamic and important, how society tells you to be one way, but it’s important to be yourself and learn from others.” |
Ruby | UTF-8 | 3,658 | 2.5625 | 3 | [
"LicenseRef-scancode-public-domain",
"JSON",
"Apache-2.0"
] | permissive | require "aws-sdk-s3"
require "base64"
require "cfnresponse"
require "digest"
require "httpclient"
require "json"
require "zip"
include Cfnresponse
def prop(event, name)
event["ResourceProperties"]["#{name}"]
end
def random_string
(0...24).map { ('a'..'z').to_a[rand(26)] }.join
end
def generate_zipfile_name(event)
hashes = []
event["ResourceProperties"]["Files"].each do |file|
file =~ /^([^\:]*)[\:](.*)/
path = $1
payload = $2
hashes.push(Digest::MD5.hexdigest(file))
end
[
Digest::MD5.hexdigest(hashes.join),
random_string,
".zip"
]
end
def payload_to_content(payload)
begin
case payload
when /^https?\:\/\//
http = HTTPClient.new
http.get_content(payload)
when /^s3\:\/\//
payload.gsub!("s3://","")
region, bucket, object = payload.split("/", 3)
s3 = Aws::S3::Resource.new(region: region)
s3.client.get_object(
bucket: bucket,
key: object
).body.read
when /^plain\:\/\//
payload.gsub!("plain://","")
else
Base64.decode64(payload)
end
rescue => exception
exception
end
end
def string_to_bool(val)
return val if val.class == FalseClass || val.class == TrueClass
return false unless val.class == String
return true if val == "true"
false
end
def lambda_handler(event:, context:)
puts("Received event: " + json_pretty(event))
# Default zip to `true`.
event["ResourceProperties"]["Zip"] = event["ResourceProperties"]["Zip"].nil? && true || string_to_bool(event["ResourceProperties"]["Zip"])
region = event["ResourceProperties"]["AWSRegion"]
bucket = event["ResourceProperties"]["UploadBucket"]
s3_key = event["ResourceProperties"]["S3Key"]
case event["RequestType"]
when "Delete"
send_response(event, context, "SUCCESS")
when "Create", "Update"
begin
raise "Bucket required" unless bucket
raise "Region required" unless region
# Calculate zipfile name based on MD5 hashes of content
zipfile_elements = generate_zipfile_name(event)
zipfile_name = zipfile_elements.join
hash, _x, _y = zipfile_elements
if event["ResourceProperties"]["Zip"]
buffer = Zip::OutputStream.write_buffer do |out|
event["ResourceProperties"]["Files"].each_with_index do |file, index|
path, payload = file.split(":", 2)
out.put_next_entry(path)
out.write payload_to_content(payload)
end
end.string
File.open("/tmp/#{zipfile_name}", "wb") { |f| f.write(buffer) }
# Upload zipfile to s3
s3 = Aws::S3::Resource.new(region: prop(event, "AWSRegion"))
if s3_key
obj = s3.bucket(prop(event, "UploadBucket")).object(s3_key)
else
obj = s3.bucket(prop(event, "UploadBucket")).object(zipfile_name)
end
obj.upload_file("/tmp/#{zipfile_name}")
zipfile_name = s3_key if s3_key
response = {
"Message": "#{prop(event, "UploadBucket")}/#{zipfile_name}"
}
else
s3 = Aws::S3::Resource.new(region: prop(event, "AWSRegion"))
event["ResourceProperties"]["Files"].each_with_index do |file, index|
path, payload = file.split(":", 2)
obj = s3.bucket(prop(event, "UploadBucket")).object(path)
obj.put(body: payload_to_content(payload))
end
response = {
"Message": prop(event, "UploadBucket")
}
end
send_response(event, context, "SUCCESS", response)
rescue Exception => e
puts e.message
puts e.backtrace
sleep 10
send_response(event, context, "FAILED")
end
end
end
|
Java | UTF-8 | 1,866 | 2.265625 | 2 | [
"MIT"
] | permissive | package no.nav.foreldrepenger.behandlingslager.dokumentbestiller;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.JoinColumnOrFormula;
import org.hibernate.annotations.JoinColumnsOrFormulas;
import org.hibernate.annotations.JoinFormula;
import no.nav.foreldrepenger.behandlingslager.kodeverk.KodeverkTabell;
import no.nav.vedtak.felles.jpa.converters.BooleanToStringConverter;
@Entity(name = "DokumentMalType")
@Table(name = "DOKUMENT_MAL_TYPE")
public class DokumentMalType extends KodeverkTabell {
@Convert(converter = BooleanToStringConverter.class)
@Column(name = "generisk", nullable = false)
private boolean generisk;
@ManyToOne(optional = false)
@JoinColumnsOrFormulas({
@JoinColumnOrFormula(column = @JoinColumn(name = "DOKUMENT_MAL_RESTRIKSJON", referencedColumnName = "kode", nullable = false)),
@JoinColumnOrFormula(formula = @JoinFormula(referencedColumnName = "kodeverk", value = "'"
+ DokumentMalRestriksjon.DISCRIMINATOR + "'"))})
private DokumentMalRestriksjon dokumentMalRestriksjon = DokumentMalRestriksjon.INGEN;
@Column(name = "doksys_kode", nullable = false, updatable = false, insertable = false)
private String doksysKode;
public static final String REVURDERING_DOK = "REVURD";
public static final String INNTEKTSMELDING_FOR_TIDLIG_DOK = "INNTID";
DokumentMalType() {
// Hibernate trenger default konstruktør
}
public String getDoksysKode() {
return doksysKode;
}
public DokumentMalRestriksjon getDokumentMalRestriksjon() {
return dokumentMalRestriksjon;
}
public boolean erGenerisk() {
return generisk;
}
}
|
TypeScript | UTF-8 | 4,773 | 2.515625 | 3 | [] | no_license | import { Tag as t, RootDictionary } from "./types";
let emptyWord = {
is: "",
noun: "",
transitive: "",
intransitive: "",
adjective: "",
adverb: "",
preposition: "",
tags: [],
};
// prettier-ignore
enum r {
enter_subclause, exit_subclause, transitive, intransitive, me, it, you, one,
two, three, four, five, six, seven, eight, nine, zeroth, first, second, third,
fourth, fifth, sixth, seventh, eighth, ninth, time, past, present, future, second_time,
day, year, yes, no, maybe, true, false, good, bad, simple, complex, none, some, all,
few, many, merge, split, group, part, connect, branch, love, hate, life, death, prev,
next, chaos, order, male, female, neuter, rare, common, open, close, big, small, agent,
object, same, distinct, opposite, begin, end, near, far, smooth, rough, and, or, xor, create,
repair, break, destroy, take, put, count, iterate, to, from, through, around, between,
more, less, pleasure, pain, this, that, overt, covert, real, model, unreal, static,
dynamic, corner, round, hard, soft, thing, direction, obligation, work, change, shape,
use, mark, light, which_does, which_receives, participle, noun_swap
}
let grammar: RootDictionary = {
[r.enter_subclause]: {},
[r.exit_subclause]: {},
[r.transitive]: {},
[r.intransitive]: {},
// suffixes?
[r.which_does]: {},
[r.which_receives]: {},
[r.participle]: {},
[r.noun_swap]: {},
};
let pronouns: RootDictionary = {
[r.me]: {},
[r.it]: {},
[r.you]: {},
};
let numbers: RootDictionary = {
// TODO: figure out how to handle zero/none
[r.one]: { is: "", tags: [t.Number, t.Root] },
[r.two]: { is: "", tags: [t.Number, t.Root] },
[r.three]: { is: "", tags: [t.Number, t.Root] },
[r.four]: { is: "", tags: [t.Number, t.Root] },
[r.five]: { is: "", tags: [t.Number, t.Root] },
[r.six]: { is: "", tags: [t.Number, t.Root] },
[r.seven]: { is: "", tags: [t.Number, t.Root] },
[r.eight]: { is: "", tags: [t.Number, t.Root] },
[r.nine]: { is: "", tags: [t.Number, t.Root] },
};
let ordinals: RootDictionary = {
[r.zeroth]: { is: "", tags: [t.Number, t.Root] },
[r.first]: { is: "", tags: [t.Number, t.Root] },
[r.second]: { is: "", tags: [t.Number, t.Root] },
[r.third]: { is: "", tags: [t.Number, t.Root] },
[r.fourth]: { is: "", tags: [t.Number, t.Root] },
[r.fifth]: { is: "", tags: [t.Number, t.Root] },
[r.sixth]: { is: "", tags: [t.Number, t.Root] },
[r.seventh]: { is: "", tags: [t.Number, t.Root] },
[r.eighth]: { is: "", tags: [t.Number, t.Root] },
[r.ninth]: { is: "", tags: [t.Number, t.Root] },
};
let timeRoot: RootDictionary = {
[r.time]: { is: "", tags: [t.Time] },
[r.past]: { is: "", tags: [t.Time] },
[r.present]: { is: "", tags: [t.Time] },
[r.future]: { is: "", tags: [t.Time] },
[r.second_time]: { is: "", tags: [t.Time] },
[r.day]: { is: "", tags: [t.Time] },
[r.year]: { is: "", tags: [t.Time] },
};
let roots: RootDictionary = {
...grammar,
...pronouns,
...numbers,
...ordinals,
...timeRoot,
[r.yes]: {},
[r.no]: {},
[r.maybe]: {},
[r.true]: {},
[r.false]: {},
[r.good]: { is: "" },
[r.bad]: { is: "" },
[r.simple]: { is: "" },
[r.complex]: { is: "" },
[r.none]: { is: "" },
[r.some]: { is: "" },
[r.all]: { is: "" },
[r.few]: {},
[r.many]: {},
[r.merge]: { is: "" },
[r.split]: { is: "" },
[r.connect]: { is: "" },
[r.branch]: { is: "" },
[r.group]: { is: "" },
[r.part]: { is: "" },
[r.love]: { is: "" },
[r.hate]: { is: "" },
[r.life]: { is: "" },
[r.death]: { is: "" },
[r.prev]: { is: "" },
[r.next]: { is: "" },
[r.chaos]: {},
[r.order]: {},
[r.male]: {},
[r.female]: {},
[r.neuter]: {},
[r.rare]: {},
[r.common]: {},
[r.open]: {},
[r.close]: {},
[r.big]: {},
[r.small]: {},
[r.agent]: {},
[r.object]: {},
[r.same]: {},
[r.distinct]: {},
[r.opposite]: {},
[r.begin]: {},
[r.end]: {},
[r.near]: {},
[r.far]: {},
[r.smooth]: {},
[r.rough]: {},
[r.and]: {},
[r.or]: {},
[r.xor]: {},
[r.create]: {},
[r.repair]: {},
[r.break]: {},
[r.destroy]: {},
[r.take]: {},
[r.put]: {},
[r.count]: {},
[r.iterate]: {},
[r.to]: {},
[r.from]: {},
[r.through]: {},
[r.around]: {},
[r.between]: {},
[r.more]: {},
[r.less]: {},
[r.pleasure]: {},
[r.pain]: {},
[r.this]: {},
[r.that]: {},
[r.overt]: {},
[r.covert]: {},
[r.real]: {},
[r.model]: {},
[r.unreal]: {},
[r.static]: {},
[r.dynamic]: {},
[r.corner]: {},
[r.round]: {},
[r.hard]: {},
[r.soft]: {},
// TODO: organize
[r.thing]: {},
[r.direction]: {},
[r.obligation]: {},
[r.work]: {},
[r.change]: {},
[r.shape]: {},
[r.use]: {},
[r.mark]: {},
[r.light]: {},
};
export { r, roots };
|
Markdown | UTF-8 | 976 | 2.859375 | 3 | [
"MIT"
] | permissive | ## Project Structure
The scaffolding is mapped after Github's guidelines for public repositories.
1. Github pages live under the root `docs` folder.
2. The `.github` folder is used for issues and pull requests docs.
3. The root folder holds the `src` (sources) folder.
```
node-package-blueprint my-project
cd my-app
```
It will create a directory called my-project inside the current folder.
Inside that directory, it will generate the initial project structure:
```
my-project
├── README.md
├── package.json
├── .gitignore
├── .travis.yml
├── [...]
└── src
└── js
└── [...]
└── scss
└── [...]
└── docs
├── README.md
└── docs
└── [...]
```
No configuration or complicated folder structures, just the files you need to build your app.
Once the installation is done, you can [run some commands](./integrated-tooling.md) inside the project folder.
|
Python | UTF-8 | 2,324 | 3.546875 | 4 | [] | no_license | #歌曲是行
#用户是列
#推荐策略:找和你最相似的用户 推荐他听过但是你没有听过的歌曲
import numpy as np
import math
def Cosine(vec1, vec2):
npvec1, npvec2 = np.array(vec1), np.array(vec2)
return npvec1.dot(npvec2)/(math.sqrt((npvec1**2).sum()) * math.sqrt((npvec2**2).sum()))
music = ['Dreams', 'Rock and Roll', 'Blue'] #其实就不用指定music name li了 id就成
def recommendation(mat,target_uid):
number_of_users=mat.shape[0]
number_of_musics=mat.shape[1]
target_row_index = target_uid - 1 # 真正对应用户的数据行
print(mat[target_row_index, :])
if set(mat[target_row_index, :])==set([0]):#冷启动
return None,None
max_row = (None, 0)
none_null_index_list = []
for i in range(number_of_musics):
if mat[target_row_index, i] != 0:
none_null_index_list.append(i)
print('not null index is')
print(none_null_index_list)
for i in range(number_of_users):
if i != target_row_index: # 不和自己计算相似度
# 计算相似度的时候 只计算两个用户都打过分的列:进一步的策略是:只取target user打过分的列
similarity = Cosine(mat[target_row_index, none_null_index_list], mat[i, none_null_index_list])
if similarity > max_row[1]:
max_row = (i, similarity)
print(max_row)
# 取出target_user没有mark但是和他相似度最高的用户mark为4,5的歌曲set
music_set = []
for i in range(number_of_musics):
if mat[max_row[0], i] >= 4 and mat[target_row_index, i] == 0:
music_set.append(i+1) #note:range是从0开始的
print(music_set)
try:
music_id=music_set.pop() #即使有多个音乐 只随机弹出一个音乐
except:
music_id=None
similar_user_id=max_row[0]+1
return music_id,similar_user_id
#print(Cosine([0,1],[1,2]))
#传进去的是两个list
#number_of_musics=len(music)
#number_of_users=5
#行数 列数
mat = np.zeros((5,3)) #基础打分都是0
#print(mat.shape)
mat[0,0] = 5
mat[0,1]=5
mat[0,2]=5
mat[3,0] = 1
mat[3,1]=1
mat[3,2]=1
mat[4,0]=5
mat[4,2]=4
print(mat)
#决定对哪一个用户推荐
#target_uid=5 #numpy的行下标和列下标是从0开始的
print(recommendation(mat,5))
|
C++ | UTF-8 | 544 | 3.53125 | 4 | [] | no_license | #include <iostream>
class Base {
public:
int m_value;
int getValue() {
return m_value;
}
Base(int b)
: m_value{b} {
}
};
class Derive : public Base {
private:
using Base::m_value;
public:
int getValue() = delete;
std::string getName() {
return "dj";
}
Derive(int v)
: Base{v} {
}
};
int main() {
Base b(5);
Derive d(4);
std::cout << d.getName() << "\n";
auto newb = static_cast<Base>(d);
std::cout << newb.getValue() << "\n";
}
|
Java | UTF-8 | 336 | 1.773438 | 2 | [] | no_license | package Tests;
import Pages.*;
import org.testng.annotations.Test;
public class GetQuotesTest extends TestBase
{
GetQuotesPage GetQuotesObj;
@Test(priority = 7)
public void UserBuyUCAComp() throws InterruptedException {
GetQuotesObj=new GetQuotesPage(driver);
GetQuotesObj.UserSelectWalaaComp();
}
}
|
Java | UTF-8 | 5,876 | 2.265625 | 2 | [
"EPL-1.0",
"Classpath-exception-2.0",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-protobuf",
"CDDL-1.1",
"W3C",
"APSL-1.0",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain"... | permissive | /*
* Copyright (c) 2000, 2023, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
package com.oracle.coherence.guides.partitions.bank;
import com.tangosol.io.AbstractEvolvable;
import com.tangosol.io.ExternalizableLite;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
import com.tangosol.net.BackingMapContext;
import com.tangosol.net.BackingMapManagerContext;
import com.tangosol.util.Binary;
import com.tangosol.util.BinaryEntry;
import com.tangosol.util.Converter;
import com.tangosol.util.ExternalizableHelper;
import com.tangosol.util.InvocableMap;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.math.BigDecimal;
/**
* An {@link com.tangosol.util.InvocableMap.EntryProcessor} to transfer
* an amount between two accounts for the same customer.
* <p>
* This EntryProcessor is invoked against the customer cache and uses
* a partition local transaction to adjust the balance of the two accounts.
* This ensures that the update of the accounts is atomic and idempotent
* so that if there is a failure causing Coherence to re-execute the
* EntryProcessor, the adjustment and result will still be correct.
* <p>
* To keep the code simple there is no error handling, for example we do not
* check the accounts actually exist.
*
* @author Jonathan Knight 2023.01.14
* @since 22.06.4
*/
public class TransferProcessor
extends AbstractEvolvable
implements InvocableMap.EntryProcessor<CustomerId, Customer, Void>,
ExternalizableLite, PortableObject {
/**
* The evolvable portable object implementation version for this class.
*/
public static final int IMPLEMENTATION_VERSION = 1;
/**
* The account to debit.
*/
AccountId sourceAccountId;
/**
* The account to credit.
*/
AccountId destinationAccountId;
/**
* The amount to transfer.
*/
BigDecimal amount;
/**
* A default no-args constructor required for serialization.
*/
public TransferProcessor() {
}
/**
* Create a {@link TransferProcessor}.
*
* @param sourceAccount the identifier of the account to debit
* @param destinationAccount the identifier of the account to credit
* @param amount the amount to transfer
*/
public TransferProcessor(AccountId sourceAccount, AccountId destinationAccount, BigDecimal amount) {
this.sourceAccountId = sourceAccount;
this.destinationAccountId = destinationAccount;
this.amount = amount;
}
@Override
@SuppressWarnings("unchecked")
public Void process(InvocableMap.Entry<CustomerId, Customer> entry) {
// Convert the entry to a BinaryEntry
BinaryEntry<CustomerId, Customer> binaryEntry = entry.asBinaryEntry();
// Obtain the manager context
BackingMapManagerContext context = binaryEntry.getContext();
// Obtain the converter to use to convert the account identifiers
// into Coherence internal serialized binary format
// It is important to use the correct key converter for this conversion
Converter<AccountId, Binary> keyConverter = context.getKeyToInternalConverter();
// Obtain the backing map context for the accounts cache
BackingMapContext accountsContext = context.getBackingMapContext(BankCacheNames.ACCOUNTS);
// Convert the source account id to a binary key and obtain the cache entry for the source account
Binary sourceKey = keyConverter.convert(sourceAccountId);
InvocableMap.Entry<AccountId, Account> sourceEntry = accountsContext.getBackingMapEntry(sourceKey);
// Convert the destination account id to a binary key and obtain the cache entry for the destination account
Binary destinationKey = keyConverter.convert(destinationAccountId);
InvocableMap.Entry<AccountId, Account> destinationEntry = accountsContext.getBackingMapEntry(destinationKey);
// adjust the values for the two accounts
Account sourceAccount = sourceEntry.getValue();
sourceAccount.adjustBalance(amount.negate());
// set the updated source account back into the entry so that the cache is updated
sourceEntry.setValue(sourceAccount);
Account destinationAccount = destinationEntry.getValue();
destinationAccount.adjustBalance(amount);
// set the updated destination account back into the entry so that the cache is updated
destinationEntry.setValue(destinationAccount);
return null;
}
@Override
public void readExternal(DataInput in) throws IOException {
sourceAccountId = ExternalizableHelper.readObject(in);
destinationAccountId = ExternalizableHelper.readObject(in);
amount = ExternalizableHelper.readBigDecimal(in);
}
@Override
public void writeExternal(DataOutput out) throws IOException {
ExternalizableHelper.writeObject(out, sourceAccountId);
ExternalizableHelper.writeObject(out, destinationAccountId);
ExternalizableHelper.writeBigDecimal(out, amount);
}
@Override
public int getImplVersion() {
return IMPLEMENTATION_VERSION;
}
@Override
public void readExternal(PofReader in) throws IOException {
sourceAccountId = in.readObject(0);
destinationAccountId = in.readObject(1);
amount = in.readBigDecimal(0);
}
@Override
public void writeExternal(PofWriter out) throws IOException {
out.writeObject(0, sourceAccountId);
out.writeObject(1, destinationAccountId);
out.writeBigDecimal(2, amount);
}
}
|
Java | UTF-8 | 3,065 | 2.203125 | 2 | [] | no_license | package com.grupo12.viera.pencauy;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import java.util.ArrayList;
import modelos.ItemPencas;
import modelos.RespuestaApiPencas;
import modelos.Usuario;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
//modelos
//retrofit
public class ListadoSolPencas extends AppCompatActivity {
private static final String ETIQUETA ="RESP API Sol pencas";
private Retrofit retro;
private ArrayList<ItemPencas> arrai;
private ListView vistalista;
private AdaptadorSolPencas adaptador;
private Usuario usuarioLoguado;
@Override
protected void onCreate(Bundle savedInstanceState) {
usuarioLoguado= ConfigSingletton.getInstance().getUsuarioLogueado();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listado_pencas);
//creo el conextor retrofit
Log.i(ETIQUETA, "entro al solPencas" );
retro = ConfigSingletton.getInstance().getRetro();
//ejecuto el llamado
obtenerDatos();
//defino la lista
vistalista=(ListView)findViewById(R.id.listPencas);
//creo el arreglo vacio
arrai=new ArrayList<ItemPencas>();
//y defino el adaptador, que se encarga de cargar la lista con los datos del array
adaptador=new AdaptadorSolPencas(getApplicationContext(),arrai,retro,usuarioLoguado.getId());
vistalista.setAdapter(adaptador);
}
private void obtenerDatos(){
//llamo a la interfaz
ServicioApiListadoPencas interfaz =retro.create(ServicioApiListadoPencas.class);
//en la interfaz llamo a la funcion obtener lista pata que me de la respuesta de la api
Call<RespuestaApiPencas> respuestacall=interfaz.obtenerListaPencasSolicitadas(ConfigSingletton.getInstance().getUsuarioLogueado().getId());
respuestacall.enqueue(new Callback<RespuestaApiPencas>() {
@Override
public void onResponse(Call<RespuestaApiPencas> call, Response<RespuestaApiPencas> response) {
if (response.isSuccessful()) {
RespuestaApiPencas respuesta = response.body();
ArrayList<ItemPencas> listaRespuesta = respuesta.getResultado();
for (int i = 0; i < listaRespuesta.size(); i++) {
ItemPencas r = listaRespuesta.get(i);
Log.i(ETIQUETA, "Respuesta:" + i + " " + r.getNombre()+"Es solicitada?: "+r.getFueSolicitada());
arrai.add(r);
adaptador.notifyDataSetChanged();
}
} else {
Log.e(ETIQUETA, "en respuesta:" + response.errorBody());
}
}
@Override
public void onFailure(Call<RespuestaApiPencas> call, Throwable t) {
Log.e(ETIQUETA, "en falla:" + t.getMessage());
}
});
}
}
|
Java | UTF-8 | 2,956 | 3.828125 | 4 | [
"MIT"
] | permissive | package tian.pusen.juc._05_synch._04_call_future;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
// Callable接口类似于Runnable,从名字就可以看出来了,但是Runnable不会返回结果,并且无法抛出返回结果的异常,
// 而Callable功能更强大一些,被线程执行后,可以返回值,这个返回值可以被Future拿到,也就是说,Future可以拿到异步执行任务的返回值
public class CallableAndFuture {
public static void main(String[] args) {
System.out.println("Begin Main ");
System.out.println("sample1");
sample1();
System.out.println("sample2");
sample2();
System.out.println("sample3");
sample3();
System.out.println("Main End");
}
public static void sample1(){
Callable<String> callable = new Callable<String>() {
public String call() throws Exception {
return new Random().nextInt(100) + "";
}
};
FutureTask<String> futureTask = new FutureTask<String >(callable);
Thread thread = new Thread(futureTask);
thread.start();
try {
Thread.sleep(5000);// 可能做一些事情
System.out.println(futureTask.get());
} catch (InterruptedException e) {
} catch (ExecutionException e) {
e.printStackTrace();
}
}
// Threadpool调用
public static void sample2(){
ExecutorService threadPool = Executors.newSingleThreadExecutor();
Future<Integer> futureTask = threadPool.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return new Random().nextInt(100);
}
});
try {
Thread.sleep(5000);// 可能做一些事情
System.out.println(futureTask.get());
} catch (InterruptedException e) {
} catch (ExecutionException e) {
e.printStackTrace();
}
threadPool.shutdown();
}
// 返回多个值
public static void sample3(){
ExecutorService threadPool = Executors.newCachedThreadPool();
CompletionService<Integer> cs = new ExecutorCompletionService<Integer>(threadPool);
for(int i = 1; i < 5; i++) {
final int taskID = i;
cs.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return taskID;
}
});
}
// 可能做一些事情
for(int i = 1; i < 5; i++) {
try {
System.out.println(cs.take().get());
} catch (InterruptedException e) {
} catch (ExecutionException e) {
e.printStackTrace();
}
}
threadPool.shutdown();
}
}
|
Python | UTF-8 | 1,297 | 3.828125 | 4 | [] | no_license | class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
newHead = ListNode(-1)
newHead.next = head
pre = newHead
cur = head
index = 1
prefix = None
while cur:
if index == m:
prefix = pre
if index > m and index <= n:
pre.next = cur.next
cur.next = prefix.next
prefix.next = cur
cur = pre.next
if index == n:
return newHead.next
index += 1
continue
pre = pre.next
cur = cur.next
index += 1
return newHead.next # 如果m是头节点,那么就直接返回cur
def printList(self, head):
while head:
print(head.val, end=" ")
head = head.next
if __name__ == '__main__':
solution = Solution()
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node5 = ListNode(5)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5
solution.printList(solution.reverseBetween(node1, 1, 4)) |
Markdown | UTF-8 | 2,785 | 2.75 | 3 | [
"MIT"
] | permissive | # Phantasma
A remake of Incentive Software's Freescape engine, allowing games created with the 3d Construction Set to run on modern computers.
Freescape was an early cross-platform scripted 3d game engine, first being used in 1987's Driller for the Spectrum, CPC, C64, Amiga, ST and PC. This project was inspired by 1991's 3D Construction Kit, released as the Virtual Reality Studio in some overseas markets, which allowed users to make their own wholly original games through a combination of modelling and scripting. Such games could be freely redistributed with the Freescape runtime, making Freescape technically the world's first licensed 3d game engine.
## Ongoing Work
This is the development branch; I’m cleaning, commenting, refactoring and removing dependencies. It’s work in progress and will return to master when it’s playable.
Substitute "will be" for "is" (or as required for tense) where appropriate below.
## Design and Dependencies
An instance of `Game` can be obtained from the binary image of either a 16- or 8-bit 3d Construction Kit game. That instance can then be instructed in user input and requested to issue drawing commands for the 3d display. By supplying a delegate, it can make let you know when a sound effect is triggered or a HUD item needs to be updated.
So the only requirements for the main body of code are a C++ compiler with some form of OpenGL available.
The OpenGL code is designed for the programmable pipeline rather than the fixed and should work across both vanilla OpenGL and OpenGL ES. It gets no benefit from the programmable pipeline but at the time of writing the fixed is a bit of an anachronism and it seems likely it will cease to be available on certain mobile platforms in the near future.
## Modules
### Command Language
Freescape is scripted via the Freescape Command Language ('FCL'); scripts are called either 'conditions' or 'animators', depending on what they do.
In Phantasma, scripts are detokenised from disk, then parsed into an internal form. That's because FCL exists in at least three forms with distinct on-disk tokenisations, so it's helpful to decouple the logic for reading from disk and the logic for performing scripts.
### Areas
Areas are individual scenes — they collect some objects with some scripts (animators and conditions on the 16-bit platforms, conditions only on the 8-bit platforms), set a scale for the scene and have some defined entrances.
User traversal between (and, sometimes, within) areas is handled by adding a condition on the thing that looks like a door that checks for collisions and warps the user to an entrance elsewhere when appropriate.
Note the scene scale. It's sort of like floating point for the entire scene. You trade scene size for geometry precision. |
Python | UTF-8 | 5,072 | 2.765625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env python3
# -*- coding = utf-8 -*-
import os
import sys
import warnings
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, BatchNormalization, DepthwiseConv2D, MaxPooling2D, UpSampling2D, ZeroPadding2D
from tensorflow.keras.layers import InputLayer, ReLU, Dropout, Add
from tensorflow.keras.regularizers import l2
from keras_applications import correct_pad
# Helper functions.
def validate_image_format(func):
"""Decorator to validate image_data_format."""
def inner(*args, **kwargs):
# Confirm image_data_format.
if K.image_data_format() != 'channels_last':
warnings.warn('You should be using a TensorFlow backend, which uses channel_last.', SyntaxWarning)
return func(*args, **kwargs)
return inner
def make_divisible(value, divisor, min_value = None):
"""Ensures that each layer has a channel number divisible by 8.
Taken from the original tensorflow repository, and can be seen at
https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py"""
if min_value is None:
min_value = divisor
new_value = max(min_value, int(value + divisor / 2) // divisor * divisor)
if new_value < 0.9 * value:
new_value += divisor
return new_value
# Primary architecture functions.
@validate_image_format
def convolution_block(input, filters, kernel_size, strides = (1, 1), padding = 'same',
activation = 'relu', use_bias = False, block_name = None):
"""A convolution block: Convolution, BatchNormalization, and ReLU activation."""
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
with tf.name_scope('convolution_block'):
if block_name:
x = Conv2D(filters, kernel_size = kernel_size, strides = strides, padding = padding, kernel_regularizer = l2(0.01),
kernel_initializer = 'he_normal', use_bias = use_bias, name = f'{block_name}_conv')(input)
x = BatchNormalization(momentum = 0.999, name = f'{block_name}_bn')(x)
x = ReLU(name = f'{block_name}_relu')(x)
else:
x = Conv2D(filters, kernel_size = kernel_size, strides = strides, padding = padding, kernel_regularizer = l2(0.01),
kernel_initializer = 'he_normal', use_bias = use_bias)(input)
x = BatchNormalization(momentum = 0.999)(x)
x = ReLU()(x)
return x
@validate_image_format
def separable_convolution_block(input, filters, rate = 1, kernel_size = (3, 3), strides = (1, 1)):
"""Depthwise separable Convolution Block: DepthwiseConvolution & Convolution."""
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
depth_padding = 'same'
with tf.name_scope('separable_convolution_block'):
x = DepthwiseConv2D(kernel_size = kernel_size, strides = strides, dilation_rate = (rate, rate),
padding = depth_padding, use_bias = False)(input)
x = BatchNormalization(momentum = 0.999)(x)
x = ReLU()(x)
x = convolution_block(x, filters, kernel_size = (1, 1), padding = 'same')
return x
@validate_image_format
def upsample_block(input, filters, kernel_size, strides = (1, 1), padding = 'same', upsample = 2):
"""An upsampling block: Convolution and then Upsampling."""
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
if isinstance(upsample, int):
upsample = (upsample, upsample)
with tf.name_scope('upsampling_block'):
x = Conv2D(filters, kernel_size = kernel_size, strides = strides, padding = padding, activation = 'relu',
kernel_initializer = 'he_normal')(input)
x = BatchNormalization()(x)
x = UpSampling2D(size = upsample, interpolation = 'bilinear')(x)
return x
@validate_image_format
def inverted_resnet_block(input, expansion, strides, filters, block_id):
"""Inverted ResNet block. Modified from tf.keras.applications.mobilenet_v2"""
channels = input.shape[-1]
pointwise_filters = make_divisible(int(filters), 8)
with tf.name_scope('inverted_resnet_block'):
# Expansion.
x = convolution_block(input, expansion * channels, kernel_size = (1, 1), padding = 'same',
activation = 'relu', use_bias = False, block_name = f'block_{block_id}_expand')
# Depthwise.
x = DepthwiseConv2D(kernel_size = (3, 3), strides = strides, padding = 'same',
use_bias = False, name = f'block_{block_id}_depthwise_conv')(x)
x = BatchNormalization(name = f'block_{block_id}_depthwise_bn')(x)
x = ReLU(name = f'block_{block_id}_depthwise_relu')(x)
# Projection.
x = convolution_block(x, pointwise_filters, kernel_size = (1, 1), padding = 'same',
activation = 'relu', use_bias = False, block_name = f'block_{block_id}_project')
if channels == pointwise_filters and strides == 1: # Skip connection.
x = Add()([input, x])
return x
|
C++ | MacCentralEurope | 1,478 | 3.25 | 3 | [
"MIT"
] | permissive | /*
Given a string str, find length of the longest repeating subseequence such that the two subsequence dont have same string character at same position, i.e., any ith character in the two subsequences shouldnt have the same index in the original string.
Input:
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains an integer N denoting the length of string str.
The second line of each test case contains the string str consisting only of lower case english alphabets.
Output:
Print the length of the longest repeating subsequence for each test case in a new line.
Constraints:
1<= T <=100
1<= N <=1000
Example:
Input:
2
3
abc
5
axxxy
Output:
0
2
*/
#include<bits/stdc++.h>
using namespace std;
int LRS(string s1, string s2, int n, int m){
int dp[n+1][m+1];
for(int i=0;i<n+1;i++) dp[i][0]=0;
for(int j=0;j<m+1;j++) dp[0][j]=0;
for(int i=1;i<n+1;i++){
for(int j=1;j<m+1;j++){
if(s1[i-1]==s2[j-1] && i!=j)
dp[i][j]=1 + dp[i-1][j-1];
else dp[i][j]=max(dp[i][j-1], dp[i-1][j]);
}
}
return dp[n][m];
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
while(t--){
int n;
cin>>n;
string s1,s2;
cin>>s1;
s2=s1;
cout<<LRS(s1,s2,n,n)<<endl;
}
return 0;
}
|
Python | UTF-8 | 2,604 | 2.78125 | 3 | [] | no_license | import requests
import logging
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
logging.basicConfig(format='%(levelname)s: %(message)s',
level=logging.WARNING,
filename='output.log',
filemode='w')
def add_note(user_id, order_id, count):
env = "dev"
body = {
}
url = get_url(env) + '/api/{}/{}'.format(user_id, order_id)
resp = requests.post(url, json=body, headers=get_header(env))
if resp.status_code != 200:
logging.error('--{}, failed to add note: {}, {}, status_code: {}, response content: {}'
.format(count, user_id, order_id, resp.status_code, resp.content))
else:
logging.warning('--{}, successfully add note: {}, {}'.format(count, user_id, order_id))
def get_header(env_key):
header_map = {'dev': {
'Content-Type': 'application/json',
'X-Session-User': 'x',
'X-Session-Key': 'x'
}, 'prod': {
'Content-Type': 'application/json',
'X-Session-User': 'x',
'X-Session-Key': 'x'
}}
return header_map[env_key]
def get_url(env_key):
url_map = {'dev': 'https://dev.xx.com',
'prod': 'https://prod.xx.com'
}
return url_map[env_key]
def operate():
count = 0
obj_list = []
with ThreadPoolExecutor(max_workers=3) as executor:
with open("/Users/pc/Pictures/testo.csv", "r") as f:
for line in f:
count = count + 1
line_array = line.split(",")
order_id = line_array[0].replace('"', '')
user_id = line_array[1].replace('"', '')
print(count, order_id, user_id)
# add_note 方法, 参数: user_id, order_id, count
obj = executor.submit(add_note, user_id, order_id, count)
obj_list.append(obj)
# executor.submit 是异步提交, 所以几万次 submit 0.3s 就结束了,
# 利用 as_completed 方法 保证所有的 任务被执行完, future.result() 会阻塞未执行完的线程
# (任务都提交了, 只有 3 个 worker , 未执行的任务是否放在 队列中? 暂未查证.)
for future in as_completed(obj_list):
future.result()
if __name__ == '__main__':
start_ticks = round(time.time() * 1000)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
operate()
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
print(str((round(time.time() * 1000) - start_ticks) / 1000) + "秒")
|
Java | UTF-8 | 127 | 2.28125 | 2 | [] | no_license | package ships;
public class Destroyer extends Ship
{
Destroyer(String pName)
{
super(pName);
super.setLength(3);
}
}
|
C# | UTF-8 | 8,012 | 3.015625 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Grid
{
private Block[] gridPositions;
private int sizeX, sizeY;
private float axisXHeight = 0;
// Initialize a grid area
public Grid(int sizeX, int sizeY)
{
this.sizeX = sizeX;
this.sizeY = sizeY;
gridPositions = new Block[sizeX * sizeY + 1]; // 6 x 11
}
public int getWidth()
{
return sizeX;
}
public int getHeight()
{
return sizeY;
}
// Move the alignment axis upwards
public void moveAxisX(float y)
{
axisXHeight += y;
// If the alignment axis reaches the top push blocks upwards (in the array) and restart from the start
if(axisXHeight >= 1)
{
axisXHeight = 0;
pushUp();
}
}
public int getSize()
{
return sizeX * sizeY;
}
// Add a block to the grid
public void addBlock(int x, int y, Block block)
{
gridPositions[x + y * sizeX] = block;
}
// Get a block at a position in the grid
public Block getBlock(int x, int y)
{
return gridPositions[x + y * sizeX];
}
// Get a list of blocks in a row
public Block[] getRow(int y)
{
Block[] blocks = new Block[sizeX];
for(int x = 0; x < sizeX; x++)
{
blocks[x] = gridPositions[x + y * sizeX];
}
return blocks;
}
// Get a list of blocks in a column
public Block[] getColumn(int x)
{
Block[] blocks = new Block[sizeY];
for (int y = 0; y < sizeY; y++)
{
blocks[y] = gridPositions[x + y * sizeX];
}
return blocks;
}
public Vector3 convertPositionToGrid(Vector3 pos)
{
return new Vector3(Mathf.FloorToInt(pos.x), Mathf.RoundToInt(pos.y - axisXHeight));
}
// Check if a spot in the grid is empty
public bool isEmpty(int x, int y)
{
if (gridPositions[x + y * sizeX])
{
return false;
}
return true;
}
// Push all blocks in the grid to a higher level
public void pushUp()
{
for(int x = 0; x < sizeX; x++)
{
for(int y = sizeY - 2; y >= 0; y--)
{
gridPositions[x + (y + 1) * sizeX] = gridPositions[x + y * sizeX];
}
}
}
// Realign all or all stationary blocks
public void realignBlocksToGrid()
{
for(int x = 0; x < sizeX; x++)
{
for(int y = 0; y < sizeY; y++)
{
Block unalignedBlock = gridPositions[x + y * sizeX];
if(unalignedBlock)
{
if (!unalignedBlock.isFalling() && !unalignedBlock.isSwapping())
{
unalignedBlock.transform.SetPositionAndRotation(new Vector3(x, y + axisXHeight), unalignedBlock.transform.rotation);
}
else if(unalignedBlock.isFalling()) //unalignedBlock.isSwapping())
{
if (isEmpty(Mathf.FloorToInt(unalignedBlock.transform.position.x), Mathf.FloorToInt(unalignedBlock.transform.position.y)))
{
gridPositions[x + y * sizeX] = null;
gridPositions[Mathf.FloorToInt(unalignedBlock.transform.position.x) + Mathf.FloorToInt(unalignedBlock.transform.position.y) * sizeX] = unalignedBlock;
}
}
}
}
}
}
// realign
public void realignBlockToBlock(Block block, Block anotherBlock)
{
if(block && anotherBlock)
{
if (!block.isFalling() && !anotherBlock.isFalling()
|| block.isFalling() && anotherBlock.isFalling())
{
block.transform.SetPositionAndRotation(new Vector3(block.transform.position.x, anotherBlock.transform.position.y), block.transform.rotation);
anotherBlock.transform.SetPositionAndRotation(new Vector3(anotherBlock.transform.position.x, block.transform.position.y), block.transform.rotation);
}
else if (block.isFalling() && !anotherBlock.isFalling())
{
block.transform.SetPositionAndRotation(new Vector3(block.transform.position.x, anotherBlock.transform.position.y), block.transform.rotation);
}
else if (!block.isFalling() && anotherBlock.isFalling())
{
anotherBlock.transform.SetPositionAndRotation(new Vector3(anotherBlock.transform.position.x, block.transform.position.y), block.transform.rotation);
}
}
}
public void swap(int blockLeftX, int blockRightX, int y)
{
realignBlockToBlock(gridPositions[blockLeftX + y * sizeX], gridPositions[blockRightX + y * sizeX]);
if (!isEmpty(blockLeftX, y) && !isEmpty(blockRightX, y))
{
gridPositions[blockLeftX + y * sizeX].setSwapGoal(gridPositions[blockRightX + y * sizeX].transform.position);
gridPositions[blockRightX + y * sizeX].setSwapGoal(gridPositions[blockLeftX + y * sizeX].transform.position);
}
else if(isEmpty(blockLeftX, y))
{
gridPositions[blockRightX + y * sizeX].setSwapGoal(new Vector3(gridPositions[blockRightX + y * sizeX].transform.position.x - 1, y));
}
else if(isEmpty(blockRightX, y))
{
gridPositions[blockLeftX + y * sizeX].setSwapGoal(new Vector3(gridPositions[blockLeftX + y * sizeX].transform.position.x + 1, y));
}
Block tempBlock = gridPositions[blockLeftX + y * sizeX];
gridPositions[blockLeftX + y * sizeX] = gridPositions[blockRightX + y * sizeX];
gridPositions[blockRightX + y * sizeX] = tempBlock;
}
public bool canSwap(int x1, int x2, int y)
{
if (gridPositions[x1 + y * sizeX].isFalling() && !isEmpty(x2, y))
{
return !gridPositions[x1 + y * sizeX].isSpawning() && !gridPositions[x1 + y * sizeX].isSetForRemoval() && !gridPositions[x2 + y * sizeX].isSpawning() && !gridPositions[x2 + y * sizeX].isSetForRemoval();
}
if (!gridPositions[x1 + y * sizeX].isFalling() && !isEmpty(x2, y))
{
return !gridPositions[x1 + y * sizeX].isSpawning() && !gridPositions[x1 + y * sizeX].isSetForRemoval() && !gridPositions[x2 + y * sizeX].isSpawning() && !gridPositions[x2 + y * sizeX].isSetForRemoval();
}
if (gridPositions[x1 + y * sizeX].isFalling() && isEmpty(x2, y))
{
return !gridPositions[x1 + y * sizeX].isSpawning() && !gridPositions[x1 + y * sizeX].isSetForRemoval();
}
if (!gridPositions[x1 + y * sizeX].isFalling() && isEmpty(x2, y))
{
return !gridPositions[x1 + y * sizeX].isSpawning() && !gridPositions[x1 + y * sizeX].isSetForRemoval();
}
return false;
}
public int getHighestColumn()
{
int max = 0;
int columnMax = 0;
for(int x = 0; x < sizeX; x++)
{
if(max < getColumnHeight(x))
{
max = getColumnHeight(x);
columnMax = x;
}
}
return columnMax;
}
public int getColumnHeight(int x)
{
for(int y = 0; y < sizeY; y++)
{
if(isEmpty(x, y))
{
return y;
}
}
return sizeY;
}
public bool blockOnTop()
{
for(int x = 0; x < sizeX; x++)
{
if (!isEmpty(x, sizeY - 1))
{
return true;
}
}
return false;
}
}
|
PHP | UTF-8 | 1,376 | 2.515625 | 3 | [] | no_license | <?php
/**
* Test case for ZendLoaderTest
* @author gabe@fijiwebdesign.com
* @example phpunit --verbose test/ZendLoaderTest.php
* Do not use phpunit from composer as it depends on composer autoloader which also loads the tested classes giving false posiives.
*/
class ZendLoaderTest extends PHPUnit_Framework_TestCase
{
/**
* /../vendor/audoload.php loads Zend\Loader\AutoloaderFactory
*/
public function testZendLoaderAutoloaderFactory()
{
require __DIR__ . '/../vendor/autoload.php';
$this->assertTrue(class_exists('Zend\Loader\AutoloaderFactory'), 'Zend\Loader\AutoloaderFactory exists');
}
/**
* /../vendor/audoload.php loads Zend\Session\Container
*/
public function testZendLoaderSession()
{
require __DIR__ . '/../vendor/autoload.php';
$Actual = new Zend\Session\Container();
$this->assertInstanceOf('Zend\Session\Container', $Actual, 'Instance of Model');
}
/**
* ../lib/Autoload.php loads Zend\Session\Container
*/
public function testZendLoaderUsingFijiAutoloader()
{
require __DIR__ . '/../lib/Autoload.php';
$Actual = new Zend\Session\Container();
$this->assertInstanceOf('Zend\Session\Container', $Actual, 'Instance of Model');
}
} |
PHP | UTF-8 | 1,549 | 2.71875 | 3 | [] | no_license | <?php
session_start();
if (!isset($_POST['ID_repertuar']))
{
header('Location: usun_seans.php');
exit();
}
$wszystko_OK=true;
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
require_once "connect.php";
$polaczenie = @new mysqli($host,$db_user,$db_password,$db_name);
if ($polaczenie->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
}
else
{
//Usuwanie seansu
//Walidacja
$ID_repertuar = $_POST['ID_repertuar'];
//Sprawdzenie czy usuwany seans jest w repertuarze
if(!$rezultat = $polaczenie->query("SELECT ID_repertuar FROM repertuar WHERE ID_repertuar = $ID_repertuar"))
{
$wszystko_OK = false;
$_SESSION['e_dodawanie_seansu']="Podany seans nie istnieje!";
echo "Podany seans nie istnieje!"."<br/>";
$rezultat->free_result();
}
if($wszystko_OK == true)
{
//DELETE
$polaczenie->query("DELETE FROM sala WHERE ID_repertuar = $ID_repertuar;");
$polaczenie->query("DELETE FROM repertuar WHERE ID_repertuar = $ID_repertuar;");
$rezultat->free_result();
$polaczenie->close();
header("Location: usun_seans.php");
exit();
}
else
{
echo "Nie udało się usunąć danych z bazy danych! "."<br/>";
}
$polaczenie->close();
}
}
catch(Exception $e)
{
echo '<span style="color:red;">Błąd serwera! Przepraszamy za niedogodności i prosimy o rejestrację w innym terminie!</span>';
echo '<br/>Informacja developerska: '.$e;
}
?>
|
Markdown | UTF-8 | 3,268 | 2.640625 | 3 | [] | no_license |
---
title: "Python3"
date: 2020-07-10T17:01:50+05:30
tags: ["object-oriented","basic-course","python3","programming","Mike","pypy","micropython","cpython",multi-paradigm"]
categories: ["Python"]
Author: "Mike"
images:
- /images/pyth.jpg
draft: false
---
{{< figure src="/images/pyth.jpg" >}}
Python3
The mission of the Python Software Foundation is to promote, protect, and advance the Python programming language, and to support and facilitate the growth of a diverse and international community of Python programmers
Python (programming language)
From Wikipedia, the free encyclopedia
Jump to navigationJump to search
Python
Python logo and wordmark.svg
Paradigm Multi-paradigm: functional, imperative, object-oriented, structured, reflective
Designed by Guido van Rossum
Developer Python Software Foundation
Stable release Typing discipline Duck, dynamic, gradual
OS Linux, macOS, Windows Vista (and newer) and more
License Python Software Foundation License
Filename extensions .py, .pyi, .pyc, .pyd, .pyo (prior to 3.5),[5] .pyw, .pyz (since 3.5)[6]
Website www.python.org
Major implementations
CPython, PyPy, Stackless Python, MicroPython, CircuitPython, IronPython, Jython, RustPython
Dialects
Cython, RPython, Starlark[7]
Influenced by
ABC,[8] Ada,[9] ALGOL 68,[10] APL,[11] C,[12] C++,[13] CLU,[14] Dylan,[15] Haskell,[16] Icon,[17] Java,[18] Lisp,[19] Modula-3,[13] Perl, Standard ML[11]
Influenced
Apache Groovy, Boo, Cobra, CoffeeScript,[20] D, F#, Genie,[21] Go, JavaScript,[22][23] Julia,[24] Nim, Ring,[25] Ruby,[26] Swift[27]
Python Programming at Wikibooks
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects.[28]
Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented, and functional programming. Python is often described as a "batteries included" language due to its comprehensive standard library.[29]
Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0, released in 2000, introduced features like list comprehensions and a garbage collection system with reference counting.
Python 3.0, released in 2008, was a major revision of the language that is not completely backward-compatible, and much Python 2 code does not run unmodified on Python 3.
The Python 2 language was officially discontinued in 2020 (first planned for 2015), and "Python 2.7.18 is the last Python 2.7 release and therefore the last Python 2 release."[30] No more security patches or other improvements will be released for it.[31][32] With Python 2's end-of-life, only Python 3.5.x[33] and later are supported.
Python interpreters are available for many operating systems. A global community of programmers develops and maintains CPython, a free and open-source[34] reference implementation. A non-profit organization, the Python Software Foundation, manages and directs resources for Python and CPython development.
|
Java | UTF-8 | 787 | 3 | 3 | [] | no_license | import java.util.Scanner;
import java.lang.Math;
public class Beautiful_days_at_the_movies {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
int j = scanner.nextInt();
int k = scanner.nextInt();
int rev = 0; int count = 0;
int num; int number;
for (int l=i; l<=j; l++) {
num = l;
number = num;
while(num != 0) {
int rem = num % 10;
rev = rev*10 + rem;
num=num/10;
}
int difference = Math.abs(rev-number);
if (difference % k ==0) {count++;}
rev = 0;
}
System.out.println(count);
}
}
|
C++ | UTF-8 | 629 | 2.984375 | 3 | [] | no_license | #include "equipo.h"
Equipo::Equipo() {
m_juegos = 0;
m_sets = 0;
}
void Equipo::sumaJuego(Equipo *other) {
m_juegos++;
int juegosOther = other->totalJuegosGanados();
if ((m_juegos >= 6) && (m_juegos > (juegosOther + 2))) {
clearJuegos();
other->clearJuegos();
sumaSet();
} else if ((juegosOther >= 6) && (juegosOther > (m_juegos + 2))) {
clearJuegos();
other->clearJuegos();
other->sumaSet();
}
}
int Equipo::totalJuegosGanados() { return m_juegos; }
int Equipo::totalSetsGanados() { return m_sets; }
void Equipo::sumaSet() { m_sets++; }
void Equipo::clearJuegos() { m_juegos = 0; }
|
C++ | UTF-8 | 1,550 | 2.984375 | 3 | [] | no_license | #include "PcPongBoard.h"
void PcPongBoard::moveBoardTowardsTarget()
{
if (dirToMove != 0)
{
if (dirToMove > getLower().getY() && boardLimit(DOWN))
{
getUpper().erase();
move(0, DOWN);
getLower().draw();
}
else if (dirToMove < getLower().getY() && boardLimit(UP))
{
getLower().erase();
move(0, UP);
getUpper().draw();
}
}
}
int PcPongBoard::findBallHitLocation(PongBoard* leftPlayer, PongBoard* rightPlayer)const
{//this function calculates where the ball is going to hit and return the y of the hit location
Point edge;
int diry=ball->getDirY();
edge = ball->getLeftest();
if (ball->getDirX() == LEFT)
{
while (leftPlayer->getLower().getX() != edge.getX())
{
if (edge.getY()+UP== MIN_Y || edge.getY()+DOWN == MAX_Y)
diry *= -1;
edge.move(LEFT, diry);
}
leftPlayer->setDirToMove(edge.getY()+DOWN);
}
else
{
edge.move(RIGHT * 3, 0);
while (rightPlayer->getLower().getX() != edge.getX())
{
if (edge.getY() + UP == MIN_Y || edge.getY() + DOWN == MAX_Y)
diry *= -1;
edge.move(RIGHT, diry);
}
rightPlayer->setDirToMove(edge.getY()+DOWN);
}
return edge.getY();
}
void PcPongBoard::updateDirToMove(int gameMode,int ballHitLocation)
{
int miss;
switch (gameMode)
{
case NOVICE:
miss = 10;
break;
case GOOD:
miss = 40;
break;
case BEST:
miss = 0;
break;
}
if (miss != 0)
{
srand(time(NULL));//random func helper
miss = rand() % miss;
}
if (miss == 1)//should miss the ball - put wrong hit location
{
dirToMove = ballHitLocation + UP * 5;
}
}
|
Java | UTF-8 | 142 | 1.875 | 2 | [] | no_license | package math;
/**
*
*/
public class AddBinary
{
public String addBinary(String a, String b)
{
}
}
|
Markdown | UTF-8 | 796 | 3.5 | 4 | [] | no_license | ---
title: v-if和v-show的区别
date: 2019-08-12 20:08:27
tags:
categories:
- Vue
---
**v-if** 是“真正”的条件渲染,因为它会确保在切换过程中条件块内的事件监听器和子组件适当地被销毁和重建。
**v-if** 也是惰性的:如果在初始渲染时条件为假,则什么也不做——直到条件第一次变为真时,才会开始渲染条件块。
相比之下,**v-show** 就简单得多——不管初始条件是什么,元素总是会被渲染,并且只是简单地基于 CSS 进行切换。
一般来说,**v-if** 有更高的切换开销,而 **v-show** 有更高的初始渲染开销。因此,如果需要非常频繁地切换,则使用 **v-show** 较好;如果在运行时条件很少改变,则使用 **v-if** 较好。
|
Java | UTF-8 | 466 | 1.78125 | 2 | [
"Apache-2.0"
] | permissive | package xyz.erupt.core.view;
import lombok.Getter;
import lombok.Setter;
import xyz.erupt.annotation.fun.PowerObject;
import java.util.Map;
/**
* @author YuePeng
* date 2018-09-29.
*/
@Getter
@Setter
public class EruptBuildModel {
private EruptModel eruptModel;
private Map<String, EruptBuildModel> tabErupts;
private Map<String, EruptModel> combineErupts;
private Map<String, EruptModel> operationErupts;
private PowerObject power;
}
|
C# | UTF-8 | 2,072 | 3.296875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EventTest
{
class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
a.MyEvent += b.DoB;
a.MyEvent += b.DoBB;
a.MyEvent -= b.DoB;
var list = a.Get(new []
{
1, 2, 3, 4, 5
}
);
var list1 = list;
a.DoA();
//int[] arr ={81,31,21,24,55,99,15};
//for (var j = 0; j < arr.Length; j++)
//{
// for (var i = 0; i < arr.Length - j-1; i++)
// {
// if (arr[i] > arr[i + 1])
// {
// var temp = arr[i];
// arr[i] = arr[i + 1];
// arr[i + 1] = temp;
// }
// }
//}
//arr.ToList().ForEach(a=>Console.WriteLine(a));
Console.ReadLine();
}
}
public class MyEventArgs : EventArgs
{
public string X { get; set; }
public string Y { get; set; }
}
public class A
{
public Action<string> MyEvent;
public void DoA()
{
OnMyEvent("nihao,jack");
}
void OnMyEvent(string str)
{
var temp = Interlocked.CompareExchange(ref MyEvent, null, null);
if (temp != null)
{
temp(str);
}
}
public IEnumerable<int> Get(int[] arr)
{
foreach (var i in arr)
{
yield return i;
}
}
}
public class B
{
public void DoB(string str)
{
Console.WriteLine(str);
}
public void DoBB(string str)
{
Console.WriteLine("zheshidobb"+str);
}
}
}
|
C# | UTF-8 | 954 | 2.53125 | 3 | [
"MIT"
] | permissive | namespace Prizma.Web
{
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// The program class for the front-end.
/// </summary>
public class Program
{
/// <summary>
/// The main application method.
/// </summary>
/// <param name="args">
/// The application arguments.
/// </param>
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
/// <summary>
/// This method creates the host builder.
/// </summary>
/// <param name="args">
/// The method arguments.
/// </param>
/// <returns>
/// The <see cref="IWebHostBuilder"/>.
/// </returns>
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
} |
Java | UTF-8 | 1,483 | 2.25 | 2 | [] | no_license | package br.com.chellenge.crud.exception.handler;
import java.util.Date;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import br.com.chellenge.crud.exception.ClienteException;
import br.com.chellenge.crud.exception.ClienteIdInexistenteExcpetion;
import br.com.chellenge.crud.exception.UsuarioException;
@ControllerAdvice
public class ResourceExceptionHandler {
@ExceptionHandler(ClienteException.class)
public ResponseEntity<ApiError> handlerCliente(ClienteException ex){
ApiError error = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage(), new Date());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
@ExceptionHandler(ClienteIdInexistenteExcpetion.class)
public ResponseEntity<ApiError> handlerClienteIdNulo(ClienteIdInexistenteExcpetion ex){
ApiError error = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage(), new Date());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
@ExceptionHandler(UsuarioException.class)
public ResponseEntity<ApiError> handlerUsuario(UsuarioException ex){
ApiError error = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage(), new Date());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
|
PHP | UTF-8 | 4,489 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php $message=""; ?>
<?php
if(isset($_POST['submit'])){
date_default_timezone_set("Asia/Dhaka");
$date=date("d F,Y h:i:s A");
$title=escape($_POST['title']);
$content=escape($_POST['content']);
$status="draft";
$tags=escape($_POST['tags']);
$author=escape($_POST['author']);
$image=$_FILES['image']['name'];
$image_temp=$_FILES['image']['tmp_name'];
$pdf=$_FILES['pdf']['name'];
$pdf_temp=$_FILES['pdf']['tmp_name'];
$video=$_FILES['video']['name'];
$video_temp=$_FILES['video']['tmp_name'];
if($image_temp!=null){
move_uploaded_file($image_temp,"../upload/images/$image");
}
if($pdf_temp!=null){
move_uploaded_file($pdf_temp,"../upload/pdf/$pdf");
}
if($video_temp!=null){
move_uploaded_file($video_temp,"../upload/video/$video");
}
$query="insert into notices(date,title,content,status,tags,image,pdf,video,author)values('$date','$title','$content','$status','$tags','$image','$pdf','$video','$author')";
$result=mysqli_query($con,$query);
if(!$result){
die("query failed").mysqli_error($con);
}
else{
$query="select * from notices";
$res=mysqli_query($con,$query);
while($row=mysqli_fetch_assoc($res)){
$the_notice_id=escape($row['id']);
}
header("Location:notices.php?source=add_notice&message=Notice Successfully Created¬ice_id=$the_notice_id");
}
}
?>
<?php if(isset($_GET['message'])){
$message=escape($_GET['message']);
?>
<div class="col-xs-6 " style="text-align:center; margin-left:410px; margin-bottom:20px;background:#A0E8A9;color:#fff; border-radius:10px;width:500px;" >
<h2><p style="font-size:15px; margin-top:-10px; "> <?php echo $message; ?>
<?php if(isset($_GET['notice_id'])){
$the_notice_id=escape($_GET['notice_id']);?>
<a style="color:skyblue;" href="../single_notice.php?single_notice=<?php echo $the_notice_id ?>">View Notice</a>
<?php } ?>
</p>
</h2>
</div>
<?php } ?>
<div class="col-xs-6 " style="text-align:center; margin-left:250px;" >
<form method="post" action="" enctype="multipart/form-data" >
<div class="form-group">
<label for="title">Notice Title</label>
<input type="text" class="form-control" name="title" >
</div>
<div class="form-group">
<label for="author">Author</label>
<input type="text" class="form-control" name="author" >
</div>
<!--
<div class="form-group">
<label for="post_author">Post Author</label>
<select name="post_author" id="" class="form-control" >
-->
<?php
/* $query="select * from users where user_role='admin'";
$select_user=mysqli_query($con,$query);
if(!$select_user){echo "query failed".mysqli_error($con);}
while($row=mysqli_fetch_assoc($select_user)){
$user_id=escape($row['user_id']);
$username=escape($row['username']);
echo "<option value='$username'>{$username}</option>";
}
*/
?>
<!--
</select>
</div>
-->
<div class="form-group">
<label for="image">Post Image</label>
<input type="file" style="margin-left:auto;margin-right:auto;padding:20px; background:aliceblue;" name="image">
</div>
<div class="form-group">
<label for="pdf">Post Pdf</label>
<input type="file" style="margin-left:auto;margin-right:auto;padding:20px; background:aliceblue;" name="pdf">
</div>
<div class="form-group">
<label for="video">Post Video</label>
<input type="file" style="margin-left:auto;margin-right:auto;padding:20px; background:aliceblue;" name="video">
</div>
<div class="form-group">
<label for="tags">Notice Tags</label>
<input type="text" class="form-control" name="tags">
</div>
<div class="form-group">
<label for="content">Notice Content</label>
<textarea name="content" id=""></textarea>
</div>
<input type="submit" value="Add Notice" name="submit" class="btn btn-primary">
</form>
</div> |
JavaScript | UTF-8 | 4,465 | 3.140625 | 3 | [] | no_license | var _runStyle = [
'Linear', 'Quad', 'Cubic', 'Quart', 'Quint', 'Sine', 'Expo', 'Circ', 'Bounce'
],
_runType = [
'easeIn', 'easeOut', 'easeInOut'
],
timingFn = function(){};
attrValue = '';
//根据时间来设置动画
//需要获取的值有,1、节点对象;2、需要修改的参数;3、总共花费时间;4、回调函数
/*
* attr是一个对象,要传入的格式为
* {
* width:100,
* height:100,
* transform: {
// start: function () {
// return {
// rotateX: {
// start: 0,
// change: 180
// },
// rotateY: {
// start: 360,
// change: 60
// }
// },
up: function (attr, key, time) {
// attrValue = '';
// for (var attrKey in attr) {
// var _value = getStep(time, attr[attrKey].start, attr[attrKey].change, animationTime.duration);
// attrValue += attrKey + '(' + _value + 'deg)'; //这里应该是开始加上变化的角度
// this.style[key] = attrValue;
// }
// }
// }
* }
* animationTime传入格式:
* {
* duration: 1000, //动画时间
* delay: 1000, //延时时间
* _runStyle: 8, //1为匀速
* _runType: 2,
*
* }
*
* */
function animationRunning(ele, attr, animationTime, callback) {
console.log(animationTime);
if (!_runStyle[animationTime._runStyle]) { //如果运行方式不存在;则设置为默认。
console.log('参数设置错误,默认匀速运动');
animationTime._runStyle = 0;
}
if (_runStyle[animationTime._runStyle] === 'Linear') {
timingFn = Tween.Linear;
} else {
switch (animationTime._runType) {
case 0:
timingFn = Tween[_runStyle[animationTime._runStyle]].easeIn;
case 1:
timingFn = Tween[_runStyle[animationTime._runStyle]].easeOut;
case 2:
timingFn = Tween[_runStyle[animationTime._runStyle]].easeInOut;
default:
timingFn = Tween.Linear; //当设置参数为错误的时候,默认为匀速
}
}
// 获取最开始时间
var startData = new Date().getTime();
//用于存放数据开始及结束的值
var attrVal = {},//每次都要清空,否则之前的参数还是会出现
fnAttr = {}; //存放的都是特殊样式中的样式和值。
// 获取初始值,并保存
for (var key in attr) {
if (typeof attr[key] === "object") {
//遍历要添加的值,存入对象中。
for (var attrKey in attr[key].start()) {
fnAttr[attrKey] = attr[key].start()[attrKey];
}
attrVal[key] = attr[key].up.bind(ele, fnAttr); //把特殊对象的值传入。
} else {
var _start = parseFloat(getStyle(ele)[key]) || 0;
var _change = attr[key] - parseFloat(getStyle(ele)[key]);
attrVal[key] = { //开始值和结束值,如果设置为改变值
start: _start, //如果获取初始值没有则为0
end: attr[key], //结束值
change: _change
}
}
}
fn();
//动画函数
function fn() {
if (animationTime.delay > 0) { //首先要判断是否有延迟,如果设置了延迟为0,-1之类的也会出现错误,所以要大于0
(function nullFn() {
if (new Date().getTime() - startData < animationTime.delay) {
requestAnimationFrame(nullFn);
} else {
startData = new Date().getTime(); //获取的是延时过后开始的时间。
run(); //动画运行方法
}
})();
} else {
run();
}
}
function run() {
//时间比例,已过时间/总时间 = 已过路程/ 总路程
var spendTime = new Date().getTime() - startData;
// 当时间比例大于等于1时,就说明时间已过最大值
if (spendTime >= animationTime.duration) {
spendTime = animationTime.duration;
setStyle(ele, attrVal, spendTime,animationTime.duration);
callback && callback();
} else {
setStyle(ele, attrVal, spendTime,animationTime.duration);
requestAnimationFrame(run);
}
}
}
//设置参数,传入要设置的节点,以及要设置的属性
function setStyle(ele, attrval, spendTime,duration) {
for (var key in attrval) {
if (typeof attrval[key] === "function") {
attrval[key](key, spendTime);
} else {
var em = 'px';
if (key === 'opacity') {
em = '';
}
ele.style[key] = timingFn(spendTime, attrval[key].start, attrval[key].change, duration) + em;
}
}
}
//获取初始样式
function getStyle(ele) {
return ele.currentStyle || getComputedStyle(ele);
} |
Python | UTF-8 | 456 | 3.921875 | 4 | [] | no_license | #!/usr/bin/python
#mapper
# Format of each line is:
# date\ttime\tstore name\titem description\tcost\tmethod of payment
#
# We want elements 2 (category) and 4 (cost)
# We need to write them out to standard output, separated by a tab
import sys
import csv
for line in sys.stdin:
data = line.strip().split("\t")
print len(data)
print "tamanho"
category = data[3]
cost = data[4]
print "{0}\t{1}".format(category, cost)
|
Java | UTF-8 | 487 | 2.890625 | 3 | [] | no_license | package players;
public class Magic extends Hero {
public Magic(int health, int damage) {
super(health, damage, Ability.BOOST);
}
@Override
public void applySuperAbility(Hero[] heroes, Boss boss) {
if (this.getHealth() > 0) {
for (int i = 0; i < heroes.length; i++) {
if (heroes[i].getHealth() > 0) {
heroes[i].setDamage((heroes[i].getDamage() + 5) );
}
}
}
}
}
|
Markdown | UTF-8 | 3,819 | 3.5625 | 4 | [] | no_license | ##### [GO TO LIST](../README.md)
# 아이템37. ordinal 인덱싱 대신 EnumMap을 사용하라
### ordinal() 사용 예
```java
class Plant {
enum LifeCycle { ANNUAL, PERENNIAL, BIENNIAL }
final String name;
final LifeCycle lifeCycle;
Plant(String name, LifeCycle lifeCycle) {
this.name = name;
this.lifeCycle = lifeCycle;
}
@Override public String toString() {
return name;
}
}
```
``` java
Set<Plant>[] plantByLifeCycle =
(Set<Plant>[]) new Set[Plant.LifeCycle.values().length];
for(int i = 0; i < plantsByLifeCycle.length; i++)
plantsByLifeCycle[i] = new HashSet<>();
for(Plant p : garden)
plantsByLifeCycle[p.lifeCycle.ordinal()].add(p);
for(int i = 0; i < plantsByLifeCycle.length; i++) {
System.out.printf("%s: %s\n",
Plant.LifeCycle.values()[i], plantsByLifeCycle[i]);
}
```
- 문제가 많은 코드.
- 배열은 제네릭과 호환되지 않으니 비검사 형변환을 해야함
- 인덱스 의미에 대한걸 표시해야한다.
- enum 정수값을 보증해야한다.
### EnumMap을 사용해서 문제점 해결
```java
Map<Plant.LifeCycle, Set<Plant>> plantsByLifeCycle =
new EnumMap<>(Plant.LifeCycle.class);
for(Plant.LifeCycle lc : Plant.LifeCycle.values())
plantsCyLifeCycle.put(lc, new HashSet<>());
for(Plant p : garden)
plantsByLifeCycle.get(p.lifeCycle).add(p);
```
- 형변환을 사용하지 않아도 된다.
- 인덱스 계산도 필요없다.
- ordinal은 내부 배열을 사용하는 걸 제거하므로서 이점이 생긴다.
### Stream을 활용하면
```java
System.out.println(Arrays.stream(garden))
.collect(groupingBy(p -> p.lifeCycle,
() -> new EnumMap<>(LifeCycle.class), toSet()));
```
### 다른 예제를 보자
```java
public enum Phase {
SOLID, LIQUID, GAS;
public enum Transition {
MELT, FREEZE, BOIL, CONDENSE, SUBLIME, DEPOSIT;
// 행은 from의 ordinal을, 열은 to의 ordinal을 인덱스로 쓴다.
private static final Transition[][] TRANSITIONS = {
{ null, MELT, SUBLIME },
{ FREEZE, null, BOIL },
{ DEPOSIT, CONDENSE, null }
};
// 다른상태로 전이
public static Transition from(Phase from, Phase to) {
return TRANSITIONS[from.ordinal()][to.ordinal()];
}
}
}
```
- ArrayIndex, NullPointer Exception 위험
### EnumMap을 사용하면?
```java
public enum Phase {
SOLD, LIQUID, GAS;
public enum Transition {
MELT(SOLD, LIQUID), FREEZE(LIQUID, SOLID),
BOIL(LIQUID, GAS), CONDENSE(GAS, LIQUID),
SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID);
}
private final Phase from;
private final Phase to;
Transition(Phase from, Phase to) {
this.from = from;
this.to = to;
}
private static final Map<Phase, Map<Phase, Transition>>
m = Stream.of(values()).collect(groupingBy(t -> t.from,
() -> new EnumMap<>(Phase.class),
toMap(t -> t.to, t -> t,
(x, y) -> y, () -> new EnumMap<>(Phase.class))));
public static Transition from(Phase from, Phase to) {
return m.get(from).get(to);
}
}
```
- 유지보수 측면에서도 EnumMap이 더 간편하다.
```java
public enum Phase {
SOLD, LIQUID, GAS, PLASMA;
public enum Transition {
MELT(SOLD, LIQUID), FREEZE(LIQUID, SOLID),
BOIL(LIQUID, GAS), CONDENSE(GAS, LIQUID),
SUBLIME(SOLID, GAS), DEPOSIT(GAS, SOLID),
IONIZE(GAS, PLASMA), DEIONIZE(PLASMA, GAS);
}
... // 코드 이하 동일
}
```
### 정리
- enum에서 배열의 인덱스를 얻기 위해서 ordinal을 쓰는 것이 일반적으로 좋지 않다.
- EnumMap<>, 다차원은 EnumMap<..., EnumMap<...>>으로 표현하라.
|
Java | UTF-8 | 2,367 | 2.34375 | 2 | [
"MIT"
] | permissive | package se.jocke.nb.eslint.task;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
/**
*
* @author jocke
*/
public class ESLintIgnore {
private final FileObject root;
private final List<PathMatcher> pathMatchers;
private ESLintIgnore(FileObject root, List<PathMatcher> pathMatchers) {
this.root = root;
this.pathMatchers = new ArrayList<>(pathMatchers);
this.pathMatchers.add(FileSystems.getDefault().getPathMatcher("glob:node_modules/**/*"));
}
public static ESLintIgnore get(FileObject fileObject) {
if (fileObject.isFolder() && fileObject.getFileObject(".eslintignore") != null) {
try {
FileObject ignore = fileObject.getFileObject(".eslintignore");
List<PathMatcher> pathMatchers = new ArrayList<>();
final List<String> lines = ignore.asLines();
for (String glob : lines) {
glob = glob.endsWith("/") ? glob + "**/*" : glob;
pathMatchers.add(FileSystems.getDefault().getPathMatcher("glob:" + glob));
}
return new ESLintIgnore(fileObject, pathMatchers);
} catch (IOException iOException) {
Logger.getLogger(ESLintIgnore.class.getName()).log(Level.WARNING, "Failed to read ignore file");
return new ESLintIgnore(fileObject, Collections.EMPTY_LIST);
}
} else if (fileObject.isFolder()) {
return new ESLintIgnore(fileObject, Collections.EMPTY_LIST);
} else {
throw new IllegalArgumentException("Not a folder " + fileObject);
}
}
public boolean isIgnored(FileObject fileObject) {
Path filePath = FileUtil.toFile(fileObject).toPath();
Path dirPath = FileUtil.toFile(root).toPath();
final Path relPath = dirPath.relativize(filePath);
for (PathMatcher pathMatcher : pathMatchers) {
if (pathMatcher.matches(relPath)) {
return true;
}
}
return false;
}
}
|
Java | UTF-8 | 253 | 1.539063 | 2 | [] | no_license | package com.bolsadeideas.springboot.di.app.models.dao;
import com.bolsadeideas.springboot.di.app.models.entity.Huesped;
import org.springframework.data.repository.CrudRepository;
public interface IHuespedDao extends CrudRepository<Huesped, Long> {
}
|
Markdown | UTF-8 | 3,000 | 3.6875 | 4 | [] | no_license | #JSX in React
jsx는 리액트 엘리먼트는 만들어 주는 javascript syntax extension 이다. 컴파일 된 후에는 일반적인 자바스크립트 오브젝트로 변환된다. 그래서 jsx에서 자바스크립트 코드를 실행 할 수도 있다.
보통 리액트와 함께 jsx를 사용하는데, jsx가 필수 사항은 아니다. jsx를 사용하지 않고, createElement함수로 리액트 엘리먼트를 만들어서 사용할 수도 있다. (실제로 babel이 컴파일 할때 jsx를 React.createElement로 변경한다. [onlnie bebel compiler](https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-0&targets=&browsers=&builtIns=false&code=function%20hello()%20%7B%0A%20%20return%20%3Cdiv%3EHello%20world!%3C%2Fdiv%3E%3B%0A%7D))
createElement함수가 생성하는 오브젝트를 단순화해서 나타내면 아래와 같다.
```javascript
// Note: this structure is simplified
const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world'
}
};
```
####주의
jsx안에서 for, if 같이 반환 값이 없는 코드는 사용 할 수 없다. 하지만 if나 for 안에 jsx가 들어가는 것은 가능하다.
```javascript
function getGreeting(user) {
if (user) {
return <h1>Hello, {formatName(user)}!</h1>;
}
return <h1>Hello, Stranger.</h1>;
}
```
##react element
리액트 엘리먼트란 리액트 어플리케이션에서 사용하는 최소단위의 블럭을 말한다. 화면에 무엇을 보여줄 것인지를 나타내는 것이다. 브라우저의 dom 엘리먼트와는 달리 리액트 엘리먼트는 아주 단순한(기능이 없는? 밋밋한?) 오브젝트이다. 그래서 생성하고 수정하는게 쉽고 빠르게 된다. 이러한 리액트 엘리먼트가 모여서 컴포넌트를 형성하게 된다.
```javascript
const element = <h1>Hello, world</h1>;
```
##element without jsx
jsx를 사용하지 않고 리액트 엘리먼트를 만드는 방법은 아래와
```javascript
React.createElement(
type,
[props],
[...children]
)
// 활용 예
const e = React.createElement;
ReactDOM.render(
e('div', null, 'Hello World'),
document.getElementById('root')
);
```
##element와 component의 차이
컴포넌트는 ui를 작은 단위로 쪼갠 것으로 각각의 컴포넌트는 독립된 객체로 존재한다. 알기쉬운 예로 비교하자면, 자바스크립트의 함수와 비슷하다고 할 수 있다. input(리액트에서는 prop)을 받아서 리액트 엘리먼트를 반환해 준다.
여기서 리액트 엘리먼트는 위에서 언급한 대로 화면에 무엇을 보여줄 것인지를 나타내는 블럭이다.
컴포넌트의 간단한 예를 들면 다음과 같다. props를 받아서 화면에 h1테그로 출력해주는 리액트 엘리먼트를 반환해 주는걸 확인 할 수 있다.
```javasript
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
```
|
JavaScript | UTF-8 | 461 | 2.765625 | 3 | [] | no_license | import data from '../config/quotes.json'
class DataHandler {
getJson = () => {
return fetch("https://talaikis.com/api/quotes/random/")
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
getOldJson = () => {
console.log(data)
return data;
}
}
export default DataHandler |
TypeScript | UTF-8 | 382 | 2.65625 | 3 | [
"MIT"
] | permissive | import { composeReducers } from './composeReducers';
describe('composeReducers', () => {
it('correctly composes reducers', () => {
const reducer = composeReducers(
(state, action) => state - action.payload,
(state, action) => state * action.payload,
(state, action) => state + action.payload
);
expect(reducer(1, { type: 'action', payload: 3 })).toBe(9);
});
});
|
Python | UTF-8 | 3,335 | 2.671875 | 3 | [
"BSD-3-Clause"
] | permissive | from .._compact import StringIO
from pyexcel_io import save_data, RWManager
from pyexcel_io.utils import AVAILABLE_WRITERS
from ..constants import DEFAULT_SHEET_NAME
class RendererFactory:
renderer_factories = {}
@classmethod
def get_renderer(self, file_type):
renderer_class = self.renderer_factories.get(file_type)
return renderer_class(file_type)
@classmethod
def register_renderers(self, renderers):
for renderer in renderers:
for file_type in renderer.file_types:
self.renderer_factories[file_type] = renderer
class BaseRenderer(object):
file_types = tuple(AVAILABLE_WRITERS) + tuple(RWManager.writer_factories.keys())
def __init__(self, file_type):
self.file_type = file_type
self.stream = None
def get_io(self):
return RWManager.get_io(self.file_type)
def render_sheet_to_file(self, file_name, sheet, **keywords):
sheet_name = DEFAULT_SHEET_NAME
if sheet.name:
sheet_name = sheet.name
data = {sheet_name: sheet.to_array()}
save_data(file_name,
data,
**keywords)
def render_book_to_file(self, file_name, book, **keywords):
save_data(file_name, book.to_dict(), **keywords)
def render_sheet_to_stream(self, file_stream, sheet, **keywords):
sheet_name = DEFAULT_SHEET_NAME
if sheet.name:
sheet_name = sheet.name
data = {sheet_name: sheet.to_array()}
save_data(file_stream,
data,
file_type=self.file_type,
**keywords)
def render_book_to_stream(self, file_stream, book, **keywords):
save_data(file_stream, book.to_dict(),
file_type=self.file_type, **keywords)
RendererFactory.register_renderers((BaseRenderer,))
class Renderer(BaseRenderer):
def get_io(self):
return StringIO()
def render_sheet_to_file(self, file_name, sheet, write_title=True, **keywords):
self.set_write_title(write_title)
with open(file_name, 'w') as outfile:
self.set_output_stream(outfile)
self.render_sheet(sheet)
def render_sheet_to_stream(self, file_stream, sheet, write_title=True, **keywords):
self.set_write_title(write_title)
self.set_output_stream(file_stream)
self.render_sheet(sheet)
def render_book_to_file(self, file_name, book, write_title=True, **keywords):
self.set_write_title(write_title)
with open(file_name, 'w') as outfile:
self.set_output_stream(outfile)
self.render_book(book)
def render_book_to_stream(self, file_stream, book, write_title=True, **keywords):
self.set_write_title(write_title)
self.set_output_stream(file_stream)
self.render_book(book)
def set_output_stream(self, stream):
self.stream = stream
def set_write_title(self, flag):
self.write_title = flag
def render_sheet(self, sheet):
self.stream.write(sheet.name)
def render_book(self, book):
number_of_sheets = book.number_of_sheets() - 1
for index, sheet in enumerate(book):
self.render_sheet(sheet)
if index < number_of_sheets:
self.stream.write('\n')
|
Java | UTF-8 | 1,548 | 2.140625 | 2 | [] | no_license | package br.com.dominio.controller;
import java.io.Serializable;
import javax.enterprise.context.spi.Context;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import org.primefaces.context.RequestContext;
//import org.slf4j.Logger;
import br.com.dominio.util.FacesUtil;
public abstract class AbstractMB implements Serializable {
// @Inject
// protected Logger logger;
@Inject
private RequestContext requestContext;
private static final String KEEP_DIALOG_OPENED = "KEEP_DIALOG_OPENED";
//public AbstractMB() {
//}
protected void displayErrorMessageToUser(String message) {
FacesUtil messageUtil = new FacesUtil();
messageUtil.exibirMensagemErro(message);
}
protected void displayInfoMessageToUser(String message) {
FacesUtil messageUtil = new FacesUtil();
messageUtil.exibirMensagemSucesso(message);
}
protected void displayWarnMessageToUser(String message) {
FacesUtil messageUtil = new FacesUtil();
messageUtil.exibirMensagemAlerta(message);
}
protected void closeDialog(){
this.requestContext.addCallbackParam(KEEP_DIALOG_OPENED, false);
}
protected void keepDialogOpen(){
this.requestContext.addCallbackParam(KEEP_DIALOG_OPENED, true);
}
/**
* Atualiza um componente pelo seu id no contexto atual
*
* @param componentId o id do componente
*/
protected void updateComponent(String componentId) {
this.requestContext.update(componentId);
}
}
|
JavaScript | UTF-8 | 1,233 | 2.84375 | 3 | [] | no_license | const amqp = require('amqplib')
const chalk = require('chalk')
const sleep = require('../sleep')
const Exchange = require('./exchange')
const topic = String(process.argv[2]).toUpperCase()
const priority = Number(process.argv[3])
async function main(topic, priority = 1) {
const connection = await amqp.connect('amqp://localhost')
const ch = await connection.createChannel()
await ch.assertExchange(Exchange.name, Exchange.type, { durable: false })
const Q = await ch.assertQueue(`${topic}.logs`, { durable: true })
ch.bindQueue(Q.queue, Exchange.name, topic)
// dont send me more than one a time
ch.prefetch(1)
ch
.consume(Q.queue, async msg => {
printColoredLog(msg.content.toString())
// pretend to do some work
await sleep(priority * 1000)
// notify that you're done
ch.ack(msg)
}, {
ack: true,
priority
})
}
function printColoredLog(message) {
switch (topic) {
case 'ERROR': return console.log(chalk.red(message))
case 'WARNING': return console.log(chalk.yellow(message))
case 'INFO': return console.log(chalk.green(message))
default: return console.log(chalk.grey(message))
}
}
main(topic, priority).catch(console.error) |
Markdown | UTF-8 | 3,406 | 2.9375 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: Running Jekyll in Windows
date: "2015-01-11 13:28"
categories:
- jekyll
---
<p class="message">I have an updated post <a href="/posts/Running-Jekyll-in-Windows-using-Docker">using Docker to run Jekyll in Windows</a>. The method described below is still valid but you know have more choices.
</p>
Setting up [Jekyll](http://jekyllrb.com/) for Windows is painful. To set it up you need to follow a multiple step setup process and cross your fingers. [Julian Thilo](https://twitter.com/juthilo) has done a great job outlining all the steps and pitfalls on his [Run Jekyll on Windows](http://jekyll-windows.juthilo.com/) site. This is how I initially setup Jekyll but the trouble with this process is it takes several steps and potentially requires a bit of debugging to figure out.
I recently switch development machines, which meant I needed to setup Jekyll again and didn't want to repeat the error prone process. At the same time I happened to learn [how use Vagrant](http://sciencevikinglabs.com/science/vagrant/2014/12/21/vagrant-getting-started.html) at the [user group](http://augusta-polyglot.github.io/) I organize.
Combining the two ideas I created a [Vagrant Configuration for Jekyll](https://github.com/jsturtevant/jekyll-vagrant). Now when I switch machines I have the same automated setup. I can be up and running in a few minutes and it is the [same environment](https://github.com/github/pages-gem) that is used for [GitHub Pages](https://pages.github.com/).
## Setup
1. Make sure [Vagrant](https://www.vagrantup.com/) and your favorite virtual machine are installed. I use [Virtual Box](https://www.virtualbox.org/) and when setting up a new machine I already have these dependencies installed using [Chocolately and BoxStarter][8a792ea8].
2. Clone the [jekyll-vagrant](https://github.com/jsturtevant/jekyll-vagrant) repository
```git clone https://github.com/jsturtevant/jekyll-vagrant.git```
3. Open command prompt to location of the ```vagrantfile``` in the new cloned repository and run ```vagrant up```
4. Jekyll and all it's dependencies are installed!
## Existing Jekyll Projects
1. Copy the projects folder to the folder that contains the ```vagrantfile```.
2. Login to the VM using ```vagrant ssh```
## New Jekyll Projects
1. Open a command prompt to location of the ```vagrantfile``` and run ```vagrant ssh```
2. Once in the VM prompt ```cd /vagrant```
3. Create a new site with ```jekyll new <sitename>```
## Start the Site
1. In the VM prompt ```cd /vagrant/<YourProjectFolder>```
2. Start the Jekyll server ```jekyll serve --force_polling``` ([force polling is required](http://stackoverflow.com/a/23084706/697126) with vagrant because of share)
3. On your host machine you can open any browser and navigate to ```localhost:4000```
4. Work on you project on your host machine and see updates as they happen on ```localhost:4000```!
## Conclusion
[Jekyll](http://jekyllrb.com/) is a fun blogging platform but the support for Windows is limited. There are ways to install Jekyll directly on the host machine but they are tedious and error prone. By leveraging [Vagrant](https://www.vagrantup.com/) we can have a fast, repeatable Jekyll setup that is in sync with [GitHub Pages](https://pages.github.com/) environment.
[8a792ea8]: http://www.aspenrootsdevelopment.com/posts/Chocolatey-And-Boxstarter "Chocolatey and Boxstarter"
|
Java | UTF-8 | 722 | 3.6875 | 4 | [] | no_license | package hw3;
import java.util.Scanner;
public class Zad7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//declare size of array
int n=0;
do {
System.out.println("Input size:");
n = sc.nextInt();
} while(n<1);
//create array and fill with numbers
int[] array = new int[n];
for (int i=0;i<array.length;i++){
System.out.println("Input number on position "+(i+1)+":");
array[i]= sc.nextInt();
}
int[] array2 = new int[n];
array2[0]=array[0];
array2[n-1]=array[n-1];
for (int i = 1; i < array.length-1; i++) {
array2[i]=array[i-1]+array[i+1];
}
for (int i = 0; i < array2.length; i++) {
System.out.println(array2[i]+" ");
}
}
}
|
Java | UTF-8 | 12,121 | 1.5625 | 2 | [] | no_license | /*
* Copyright (C) 2015, Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Please email droidsafe@lists.csail.mit.edu if you need additional
* information or have any questions.
*
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpcore/trunk/module-main/src/main/java/org/apache/http/protocol/HTTP.java $
* $Revision: 555989 $
* $Date: 2007-07-13 06:33:39 -0700 (Fri, 13 Jul 2007) $
*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
/***** THIS FILE HAS BEEN MODIFIED FROM THE ORIGINAL BY THE DROIDSAFE PROJECT. *****/
package org.apache.http.protocol;
// Droidsafe Imports
import droidsafe.runtime.*;
import droidsafe.helpers.*;
import droidsafe.annotations.*;
public final class HTTP {
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.690 -0500", hash_original_method = "134212A674CF385E582642AFF649A905", hash_generated_method = "E308477FC9CABEB85C4755A08378A651")
public static boolean isWhitespace(char ch) {
return ch == SP || ch == HT || ch == CR || ch == LF;
}
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.610 -0500", hash_original_field = "827B2E55812199FEACACB1E9C37846C6", hash_generated_field = "4B48828FAC4FE3DBFFFAEBA8A8C921C4")
public static final int CR = 13;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.613 -0500", hash_original_field = "B49D7BCA303E83D5E6889B0D7C14B13F", hash_generated_field = "DBCCC25381D1593318771528439CD34E")
public static final int LF = 10;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.615 -0500", hash_original_field = "A28828A0B92B7CCEDA71A5B2AE8AE8F1", hash_generated_field = "8C31871A8309CB160AA82B7C23210018")
public static final int SP = 32;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.617 -0500", hash_original_field = "7C616B473E4C8E4367E2D7A3C253DDF4", hash_generated_field = "73DE634A37CDD97EAD750FBA8C4C9FBC")
public static final int HT = 9;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.620 -0500", hash_original_field = "683DFC7E7BA00A43D201F7E238E33F4B", hash_generated_field = "CD72CB4685B408B00CABB27031A6E67E")
/** HTTP header definitions */
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.622 -0500", hash_original_field = "7EB3283A3DA44782F7C0F7D82F970F6F", hash_generated_field = "C873F93E350601E9BA4876A9082000C0")
public static final String CONTENT_LEN = "Content-Length";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.625 -0500", hash_original_field = "46364DAB064DC5AB4E14A25EF7C77722", hash_generated_field = "F0FB0CC8338BC684D174D37138E71AF4")
public static final String CONTENT_TYPE = "Content-Type";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.628 -0500", hash_original_field = "ED3F7B67193A1825AB248A53D9C4D42F", hash_generated_field = "D94FB51F80F2B147EA4680CE432C1F0C")
public static final String CONTENT_ENCODING = "Content-Encoding";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.631 -0500", hash_original_field = "2A490AB509A41B7A8D98470AA5A84912", hash_generated_field = "E8579121D1EEE88EB5D1CF19E8603FAA")
public static final String EXPECT_DIRECTIVE = "Expect";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.633 -0500", hash_original_field = "14410297368C2DE695CF4179DD04C85D", hash_generated_field = "0B8C287D2005A31833DE791D61201060")
public static final String CONN_DIRECTIVE = "Connection";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.636 -0500", hash_original_field = "42E2857A87EE0D51532DFD1FDF4D62F6", hash_generated_field = "B1342B7FA4AD6A351ECF0FFB5F118EF2")
public static final String TARGET_HOST = "Host";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.640 -0500", hash_original_field = "BC4203D8CE9B792041A4F855B1F6A4A3", hash_generated_field = "E2B32A00DC1ECEDFED5285C80EA77905")
public static final String USER_AGENT = "User-Agent";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.643 -0500", hash_original_field = "A60877960BCC71CABE0DB62C4C34A229", hash_generated_field = "DE28CCA6101D868C19F7866E0E4CF84A")
public static final String DATE_HEADER = "Date";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.645 -0500", hash_original_field = "16F67FA43AF79A31A634AF7E701D5AF3", hash_generated_field = "888CA02569744C2DDF961A4D613EEEDE")
public static final String SERVER_HEADER = "Server";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.648 -0500", hash_original_field = "597CF85895F35EB9121700CF37460088", hash_generated_field = "2F1A29638B2D0E29C2FE55A6F7179955")
public static final String EXPECT_CONTINUE = "100-continue";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.650 -0500", hash_original_field = "1345F4EC2710CA29E98CA27CB2EFE96C", hash_generated_field = "6DC990621E1FEBEF4641A3A13BCCD60A")
public static final String CONN_CLOSE = "Close";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.653 -0500", hash_original_field = "ED065862777B89FA1B2796CAAA22B81B", hash_generated_field = "CC47465F6C28D40E3A32A53EEC662014")
public static final String CONN_KEEP_ALIVE = "Keep-Alive";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.656 -0500", hash_original_field = "4C7C4E92CA4CDF03CA684D4DFCA73F0F", hash_generated_field = "7698A1C415B04EFDB79A05219636C1E7")
public static final String CHUNK_CODING = "chunked";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.658 -0500", hash_original_field = "B84614F1B6CA7A351CB142FF62477DE5", hash_generated_field = "72080EB6EE7DF12980F670A096811F52")
public static final String IDENTITY_CODING = "identity";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.660 -0500", hash_original_field = "4C869B13BEF7E7EB87393F929DAAEF08", hash_generated_field = "059F3081BD79133B19DA92D71B903D4B")
public static final String UTF_8 = "UTF-8";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.663 -0500", hash_original_field = "F937D08544423510C929202A06C5E40C", hash_generated_field = "37AEDC72537277B8C7D6E458F0C0A8AC")
public static final String UTF_16 = "UTF-16";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.665 -0500", hash_original_field = "4BA4D73EFE3E4386F492E6E345E19D10", hash_generated_field = "6E4160004BBA062156F08F5FA5E24E91")
public static final String US_ASCII = "US-ASCII";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.668 -0500", hash_original_field = "394EEB836B539DF1CB4EC3F596C7BAFE", hash_generated_field = "E3FF2ABE49D9B0E6D68B9CE78330A0E0")
public static final String ASCII = "ASCII";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.672 -0500", hash_original_field = "9B4241CF8375027A3760457C90F1C043", hash_generated_field = "C54DD200E0A99AF152F5F6AA68726A31")
public static final String ISO_8859_1 = "ISO-8859-1";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.675 -0500", hash_original_field = "80F00EEAB510ACD218BBCD92ADFCF7C8", hash_generated_field = "0B189A530E87CE08F47FE84B87D301D4")
public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.677 -0500", hash_original_field = "E5E4987AC6CB51C1736EE888F6D513E1", hash_generated_field = "4DAD949FEE540AB1667F5B541534AB37")
public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII;
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.680 -0500", hash_original_field = "072BC0913DC612375B064B1872E7FECA", hash_generated_field = "1CB198EE1ACA6C0EBAFB3A73F020BC6B")
public final static String OCTET_STREAM_TYPE = "application/octet-stream";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.682 -0500", hash_original_field = "CF4F3F90E35325C80A7D4177EE02F8D3", hash_generated_field = "A701F6EF1312597F444CFD473F9B1D59")
public final static String PLAIN_TEXT_TYPE = "text/plain";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.685 -0500", hash_original_field = "0D4F333C65C7E7E0D1EA7A2FBA11A129", hash_generated_field = "38C97344F99EEB0BB029FDDD6DDE4624")
public final static String CHARSET_PARAM = "; charset=";
@DSGeneratedField(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.687 -0500", hash_original_field = "6EBAFB707ABA4DCB92E2BD199F559B91", hash_generated_field = "D2FDB251E5ED6DA906DD06661166E627")
public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE;
@DSComment("Private Method")
@DSBan(DSCat.PRIVATE_METHOD)
@DSGenerator(tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:01:46.693 -0500", hash_original_method = "3A6FCD823D5B25065B735A0BBABE71E6", hash_generated_method = "451E5D2DCE9FF602E8836599E91046BA")
private HTTP() {
}
}
|
C++ | UTF-8 | 2,094 | 2.53125 | 3 | [] | no_license | #include "logger.h"
void Logger::init()
{
ros::init(init_argc, init_argv,"Bebop_Logger");
ros::NodeHandle nh;
this->battery_sub = nh.subscribe("/bebop/states/common/CommonState/BatteryStateChanged",1, &Logger::batteryCallback, this);
this->odom_sub = nh.subscribe("/bebop/odom",1,&Logger::odometryCallback, this);
this->position_sub = nh.subscribe("/bebop/states/ardrone3/PilotingState/PositionChanged",1,&Logger::positionCallback,this);
while(ros::ok())
{
ros::spinOnce();
this->status.insert_status(this->status_cnt,this->droneId,this->latitude, this->longitude, this->altitude, this->percent);
this->status_cnt++;
}
}
Logger::Logger(int argc, char** argv, const char* droneName){
this->init_argc = argc;
this->init_argv = argv;
this->droneInfo = DroneInfo("localhost","root","rosemfhs","mydb",3306);
this->status = Status("localhost","root","rosemfhs","mydb",3306);
this->droneName = droneName;
this->droneId = droneInfo.get_DroneID_byname(this->droneName);
this->latitude = this->longitude = this-> altitude = this->percent = 0;
this->status_cnt = 1;
}
void Logger::batteryCallback(const bebop_msgs::CommonCommonStateBatteryStateChanged::ConstPtr& msg)
{
ROS_INFO("Battery : %d", msg->percent); //int
this->percent = msg ->percent;
}
void Logger::odometryCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
this->positionX = msg->pose.pose.position.x;
this->positionY = msg->pose.pose.position.y;
this->positionZ = msg->pose.pose.position.z;
this->orientationX = msg->pose.pose.orientation.x;
this->orientationY = msg->pose.pose.orientation.y;
this->orientationZ = msg->pose.pose.orientation.z;
this->linearX = msg->twist.twist.linear.x;
this->linearY = msg->twist.twist.linear.y;
this->linearZ = msg->twist.twist.linear.z;
}
void Logger::positionCallback(const bebop_msgs::Ardrone3PilotingStatePositionChanged::ConstPtr& msg)
{
this->altitude = msg->altitude;
this->longitude = msg->longitude;
this->latitude = msg->latitude;
} |
Python | UTF-8 | 8,988 | 2.71875 | 3 | [] | no_license | from nose.tools import *
from nose import with_setup
import unittest
import os
import shutil
import tempfile
import uuid
from s3cache import S3Cache
from s3cache.exception import *
def _read_file(filename):
content = ""
with open(filename, 'r') as content_file:
content = content_file.read()
return content
class TestS3Cache(unittest.TestCase):
def setUp(self):
self.cleanup_dirs = []
def tearDown(self):
for d in self.cleanup_dirs:
shutil.rmtree(d)
def cleanup(self, d):
self.cleanup_dirs.append(d)
def bucketFactory(self, create=True):
bucket_name = str(uuid.uuid4())
local_cache = tempfile.mkdtemp()
self.cleanup(local_cache)
self.assertTrue(os.path.exists(local_cache))
endpoint = os.environ['S3_ENDPOINT']
port = int(os.environ['S3_PORT'])
s3 = S3Cache(local_cache, bucket_name, port=port,
is_secure=False, host=endpoint)
if create:
s3.create_bucket()
self.assertTrue(s3.bucket_exists())
s3.set_verbosity(True)
s3.set_caching(True)
return s3
@raises(S3CacheConnectError)
def testS3ConnectionTimeout(self):
bucket_name = str(uuid.uuid4())
local_cache = tempfile.mkdtemp()
self.cleanup(local_cache)
self.assertTrue(os.path.exists(local_cache))
endpoint = uuid.uuid4()
port = 1000
s3 = S3Cache(local_cache, bucket_name, port=port,
is_secure=False, host=endpoint)
s3.connect()
def testBucketExists(self):
create = False
s3 = self.bucketFactory(create)
# does the bucket exist?
self.assertFalse(s3.bucket_exists())
# delete non-existent bucket
self.assertFalse(s3.remove_bucket())
def testBucketCreateAndDelete(self):
create = True
s3 = self.bucketFactory(create)
# does the bucket exist?
self.assertTrue(s3.bucket_exists())
# delete non-existent bucket
self.assertTrue(s3.remove_bucket())
def testBucketDeleteError(self):
create = False
s3 = self.bucketFactory(create)
# does the bucket exist?
self.assertFalse(s3.bucket_exists())
# delete non-existant bucket
s3.remove_bucket()
@raises(S3CacheBucketNotExistError)
def testReadWriteOnNonExistentBucket(self):
create = False
s3 = self.bucketFactory(create)
# does the bucket exist?
self.assertFalse(s3.bucket_exists())
# Try some operations on a non-existent bucket
object_name = "bucket-does-not-exist.txt"
f = s3.open(object_name, "r")
@raises(S3CacheIOError)
def testReadNonExistentFile(self):
s3 = self.bucketFactory()
object_name = "file-does-not-exist.txt"
f = s3.open(object_name, "r")
def testFileCreateAndDelete(self):
for caching in (True, False):
s3 = self.bucketFactory()
s3.set_caching(caching)
object_name = "/foo/bar.txt"
content = "content"
# Create an object
f = s3.open(object_name, "w")
f.write(content)
bytes_written = f.close()
self.assertEqual(bytes_written, len(content))
self.assertTrue(s3.object_exists(object_name))
# then delete it
self.assertTrue(s3.remove_object(object_name))
self.assertFalse(s3.object_exists(object_name))
# Create an object again
f = s3.open(object_name, "w")
f.write(content)
bytes_written = f.close()
self.assertEqual(bytes_written, len(content))
self.assertTrue(s3.object_exists(object_name))
# Revove using file handle
self.assertTrue(f.remove())
self.assertFalse(s3.object_exists(object_name))
def testTwoHandlesToSameFile(self):
for caching in (True, False):
s3 = self.bucketFactory()
object_name = "/foo/bar.txt"
content = "content"
# Create an object
f1 = s3.open(object_name, "w")
f1.write(content)
bytes_written = f1.close()
self.assertEqual(bytes_written, len(content))
self.assertTrue(f1.exists())
self.assertTrue(s3.object_exists(object_name))
f2 = s3.open(object_name, "r")
self.assertTrue(f2.exists())
self.assertTrue(f2.remove())
# now both handles will should that the file doesn't exist
self.assertFalse(s3.object_exists(object_name))
self.assertFalse(f1.exists())
self.assertFalse(f2.exists())
def testLocallyCached(self):
s3 = self.bucketFactory()
# Turn on caching
s3.set_caching(True)
object_name = "/foo/cached.txt"
f = s3.open(object_name, "w")
f.close()
self.assertTrue(f.cached())
self.assertTrue(f.remove_cached())
self.assertFalse(f.cached())
self.assertTrue(f.exists())
self.assertTrue(f.remove())
self.assertFalse(f.exists())
self.assertFalse(f.cached())
# Turn off caching
s3.set_caching(False)
object_name = "/foo/no-cache.txt"
f = s3.open(object_name, "w")
f.close()
self.assertFalse(f.cached())
self.assertTrue(f.remove_cached())
self.assertFalse(f.cached())
self.assertTrue(f.exists())
# Read from S3, and the file has to be cached for reading
f = s3.open(object_name, "r")
self.assertTrue(f.cached())
f.close()
self.assertTrue(f.remove())
self.assertFalse(f.exists())
self.assertFalse(f.cached())
def testCreateAndAppendToFile(self):
for caching in (True, False):
s3 = self.bucketFactory()
# Toggle caching
s3.set_caching(caching)
object_name = "new-file.txt"
content = "content"
# write a file
f = s3.open(object_name, "w")
f.write(content)
bytes_written = f.close()
self.assertEqual(bytes_written, len(content))
self.assertTrue(s3.object_exists(object_name))
# now append to it
f = s3.open(object_name, "a")
f.write(content)
bytes_written = f.close()
self.assertEqual(bytes_written, len(content) * 2)
self.assertTrue(s3.object_exists(object_name))
def testOverWriteExistingFile(self):
for caching in (True, False):
s3 = self.bucketFactory()
# Toggle caching
s3.set_caching(caching)
object_name = "new-file.txt"
content = "content"
# write a file
f = s3.open(object_name, "w")
f.write(content)
bytes_written = f.close()
self.assertEqual(bytes_written, len(content))
self.assertTrue(s3.object_exists(object_name))
f = s3.open(object_name, "r")
line = f.readline()
f.close()
self.assertEqual(line, content)
# now append to it
alternative_content = "Mary had a little lamb"
self.assertNotEqual(content, alternative_content)
f = s3.open(object_name, "w")
f.write(alternative_content)
bytes_written = f.close()
self.assertEqual(bytes_written, len(alternative_content))
self.assertTrue(s3.object_exists(object_name))
f = s3.open(object_name, "r")
line = f.readline()
f.close()
self.assertEqual(line, alternative_content)
def testCreateAndDownloadFile(self):
# Write a file out file
object_name = "myfile1.txt"
content = "content"
s3 = self.bucketFactory()
s3.set_caching(True)
f = s3.open(object_name, "w")
f.write(content)
bytes_written = f.close()
self.assertEqual(bytes_written, len(content))
self.assertTrue(s3.object_exists(object_name))
# Now check it content directly
local_cache = s3.local_cache()
local_filename = os.path.join(local_cache, object_name)
self.assertTrue(os.path.exists(local_filename))
local_content = _read_file(local_filename)
self.assertEqual(local_content, content)
# Now manually remove the file from local cache
os.unlink(local_filename)
self.assertFalse(os.path.exists(local_filename))
# Open the file to read and see that it is downloaded
# from the bucket
f = s3.open(object_name, "r")
line = f.readline()
self.assertEqual(line, content)
# Remove file
self.assertTrue(s3.remove_object(object_name))
self.assertFalse(s3.object_exists(object_name))
|
C++ | UTF-8 | 4,113 | 3.328125 | 3 | [] | no_license | #include <algorithm>
#include <set>
#include <map>
#include "Functions.h"
std::string Functions::DNAStrand(const std::string& dna)
{
auto newString = std::string("");
for(auto&& s : dna){
switch (s){
case 'A':
newString += "T";
break;
case 'T':
newString += "A";
break;
case 'G':
newString += "C";
break;
case 'C':
newString += "G";
break;
default:
std::cout << "This is fukd. How did you end up here? |" << s << "|";
}
}
//your code here
return newString;
}
int Functions::get_sum(int a, int b) {
if(a == b) return a;
int max = a > b ? a : b;
int min = a < b ? a : b;
int sum = 0;
for(int i = min; i <= max; i++){
sum += i;
}
return sum;
}
std::string Functions::accum(const std::string &s) {
auto count = 0;
auto newString = std::string("");
for(auto&& letter : s) {
if(count > 0) {
newString += "-";
}
newString += toupper(letter);
for(int i = 0; i < count; i++) {
newString += tolower(letter);
}
count++;
}
return newString;
}
bool Functions::is_isogram(const std::string &str) {
auto string = std::string(str.length(),' ');
std::transform(begin(str), end(str), begin(string), [](auto&& c){return std::tolower(c);});
for(auto&& s : string) {
if(std::count(begin(string), end(string), s) >= 2) {
return false;
}
}
return true;
}
bool Functions::is_perfect_square(int&& n){
auto&& root = 0;
while(root <= n) {
if(root*root == n) return true;
root++;
}
return false;
}
bool Functions::comp(std::vector<int>&& a, std::vector<int>&& b) {
for(auto&& root : a) {
if(!std::count(begin(b), end(b), root*root)) {
return false;
} else {
b.erase(std::find(begin(b), end(b), root*root));
}
}
return b.size() == 0;
}
bool Functions::comp_better(std::vector<int>&& a, std::vector<int>&& b) {
for(auto&& root : a) {
root = root*root;
}
std::sort(begin(a), end(a));
std::sort(begin(b), end(b));
return a == b;
}
long long Functions::rowSumOddNumbers(unsigned n){
//1 = 1
//3 5 = 8
//7 9 11 = 27
//13 15 17 19 = 64
if(n == 1) return 1;
auto nums = 0;
std::vector<int> sums{1};
for(int i = n; i >= 0; i--) {
nums += i;
}
auto sum = 0;
for(int ii = 1; ii < nums; ii++){
sums.emplace_back(sums.back()+2);
if(ii >= nums-n){
sum += sums.back();
}
}
return sum;
}
long long Functions::rowSumOddNumbers_better(unsigned int n) {
//1^3 = 1, 2^3 = 8, 3^3 = 27 and so on..
return n*n*n;
}
int Functions::convertFromRoman(const std::string &roman) {
std::map<char, int> values = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000},
};
auto sum = 0;
for(auto it = begin(roman); it != end(roman);){
int valThis = values.find(*it)->second;
int valNext = values.find(*(std::next(it)))->second;
if(valThis < valNext) {
sum += valNext - valThis;
it += 2;
} else {
sum += valThis;
it++;
}
}
return sum;
}
std::string Functions::likes(const std::vector<std::string> &names)
{
switch(names.size()){
case 0:
return "no one likes this";
case 1:
return names[0] + " likes this";
case 2:
return names[0] + " and " + names[1] + " like this";
case 3:
return names[0] + ", " + names[1] + " and " + names[2] + " like this";
default:
return names[0] + ", " + names[1] + " and " + std::to_string(names.size()-2) + " others like this";
}
} |
Python | UTF-8 | 287 | 2.578125 | 3 | [] | no_license | class Solution(object):
def kthSmallest(self, matrix, k):
def extract(matrix):
a = []
for val in matrix:
for v in val:
a.append(v)
return sorted(a)
e = extract(matrix)
return e[(k - 1)] |
Java | UTF-8 | 3,704 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package py.org.fundacionparaguaya.pspserver.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name = "family", schema = "ps_families")
public class FamilyEntity extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ps_families.family_family_id_seq")
@SequenceGenerator(name = "ps_families.family_family_id_seq", sequenceName = "ps_families.family_family_id_seq", allocationSize = 1)
@Column(name = "family_id")
private Long familyId;
private String name;
@ManyToOne(targetEntity = CountryEntity.class)
@JoinColumn(name = "country")
private CountryEntity countryEntity;
@ManyToOne(targetEntity = CityEntity.class)
@JoinColumn(name = "city")
private CityEntity cityEntity;
private String locationType;
private String locationPositionGps;
@ManyToOne(targetEntity = PersonEntity.class)
@JoinColumn(name = "person_reference_id")
private PersonEntity personEntity;
@ManyToOne(targetEntity = ApplicationEntity.class)
@JoinColumn(name = "application_id")
private ApplicationEntity applicationEntity;
@ManyToOne(targetEntity = OrganizationEntity.class)
@JoinColumn(name = "organization_id")
private OrganizationEntity organizationEntity;
public Long getFamilyId() {
return familyId;
}
public void setFamilyId(Long familyId) {
this.familyId = familyId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CountryEntity getCountry() {
return countryEntity;
}
public void setCountry(CountryEntity country) {
this.countryEntity = country;
}
public CityEntity getCity() {
return cityEntity;
}
public void setCity(CityEntity city) {
this.cityEntity = city;
}
public String getLocationType() {
return locationType;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
public String getLocationPositionGps() {
return locationPositionGps;
}
public void setLocationPositionGps(String locationPositionGps) {
this.locationPositionGps = locationPositionGps;
}
public PersonEntity getPersonReferenceId() {
return personEntity;
}
public void setPersonReferenceId(PersonEntity personReferenceId) {
this.personEntity = personReferenceId;
}
public ApplicationEntity getApplicationId() {
return applicationEntity;
}
public void setApplicationId(ApplicationEntity applicationId) {
this.applicationEntity = applicationId;
}
public OrganizationEntity getOrganizationId() {
return organizationEntity;
}
public void setOrganizationId(OrganizationEntity organizationId) {
this.organizationEntity = organizationId;
}
@Override
public String toString() {
return "FamilyEntity [familyId=" + familyId + ", name=" + name + ", countryEntity=" + countryEntity
+ ", cityEntity=" + cityEntity + ", locationType=" + locationType + ", locationPositionGps="
+ locationPositionGps + ", personEntity=" + personEntity + ", applicationEntity=" + applicationEntity
+ ", organizationEntity=" + organizationEntity + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (familyId == null || obj == null || getClass() != obj.getClass())
return false;
FamilyEntity toCompare = (FamilyEntity) obj;
return familyId.equals(toCompare.familyId);
}
@Override
public int hashCode() {
return familyId == null ? 0 : familyId.hashCode();
}
}
|
Markdown | UTF-8 | 331 | 2.71875 | 3 | [
"MIT"
] | permissive | ## Locked
#### Overview
Locks all days in calendar.
#### HTML Structure
```html
<div class="calendar"></div>
```
#### Javascript Initialization
```js
var calendar = new HelloWeek({
selector: '.calendar',
locked: true,
onNavigation: () => {
calendar.setLocked(false);
calendar.update();
}
});
```
|
Markdown | UTF-8 | 7,155 | 3.03125 | 3 | [
"MIT"
] | permissive | ---
title: 'The Power of Incorporating a GitHub Copilot'
date: '2022-07-25T18:41:54.613Z'
template: blog
tags: Tools
image: './media/the-power-of-incorporating-a-git-hub-copilot.png'
---
Imagine a tool that can help you code faster by suggesting autocomplete your code! The [software developers](https://www.cobuildlab.com/blog/tips-to-choose-right-custom-software-development-company-for-your-business/) spend most of their time coding, which is time-consuming and sometimes mentally draining. You can now code quicker and achieve more thanks to machine learning and AI.
Businesses also want solutions that help them analyze customer feedback better and tailor their services to them. In this regard, GitHub Copilot can help developers and enterprises utilize [sentiment analysis](https://www.surgehq.ai/blog/building-a-no-code-toxicity-classifier-by-talking-to-copilot) AI through machine learning models.
This article explores the power of incorporating a Github Copilot.
<br>
<title-3>What is GitHub Copilot?</title-3>
GitHub Copilot is an [AI programming assistant](https://github.com/features/copilot) that helps developers code faster while putting in less work. Github describes the product as an AI pair programmer that reads the comments and context of code and gives developers coding suggestions.
Copilot is a product of collaboration between Github and OpenAir. OpenAI's Codex system powers it. Codex has been trained from billions of publicly available code repositories on GitHub to understand source code and natural language. It draws knowledge from its rich base to make code suggestions. And this makes Codex arguably more potent than GPT-3 in code generation.
The large dataset from which Codex is trained gives Copilot an upper hand in knowing how developers code. As such, it can produce better code suggestions.
<br>
<title-3>Github Copilot Availability</title-3>
Github launched Copilot in June 2021 as a technical preview. However, the company has now made Github Copilot available for all developers. But it is not free! The AI pair programmer is available at a monthly \$10 or \$100 annual subscription. Nevertheless, Copilot is freely available for verified students and top contributors of open source code.
GitHub Copilot is offered as SaaS (Software as a service) and is available as a downloadable extension for coding. You can use it on coding tools such as Visual Studio Code, Visual Studio, Neovim, and Jet.
Additionally, Github supports common programming languages such as Python, JavaScript, TypeScript, Ruby, and Go.
<br>
<title-3>How GitHub Copilot Works</title-3>
Github Copilot relies on the context of your code to predict and autocomplete your code lines. When you start typing code on the Github Copilot editor, the extension reads and relays your code line and comments to the Copilot service. It learns the context by accessing the file you\'re editing and the related files within the same project.
It will then analyze the datasets it has been trained from and try to find the most suitable code for your context. Its functionality instantly suggests individual lines and whole functions of codes. As you write your code, the AI will analyze your coding cues and autocomplete your code with possible suggestions.
Better still, Copilot gives multiple suggestions so you can pick the one that matches your code. If none of the suggestions interests you, you can let it generate more recommendations until you get a completion that makes sense.
Creators and developers have found Github Copilot to work better with repetitive text because you let it autocomplete the code. It is a great tool to help you learn new programming languages.
<br>
<title-3>Does GitHub Copilot Write Perfect Code?</title-3>
Although Github is a perfect developer tool, it doesn't write perfect code. It tries to understand the context of your file and project and predict the best. However, sometimes it spits outputs that do not make sense. This confusion may arise from the AI not understanding your inputs or commands, or maybe it hasn't yet learned that particular code.
If you want to get better results from Copilot, it is advisable to break your code into small functions and provide parameters and docstrings that are easy to understand. If you keep your comments simple, the tool will quickly understand the context and generate meaningful code.
Plus, Copilot does not test the code suggestions it makes, so it might not always be functional. The developer must test and verify the authenticity of the generated code just like any other code.
<br>
<title-3>The Benefits of Github Copilot</title-3>
So, is the hype about Github Copilot in the developer\'s world worth it? The answer is simply yes. Though Copilot doesn't generate perfect code, it comes with benefits that make the developers\' life much easier. Here are some of the top benefits of incorporating Github Copilot:
<title-4>Github Copilot reduces Distractions</title-4>
Github is a fantastic tool for developers. It helps you focus on the flow of your project flow. Therefore, developers can speed up their processes and boost their productivity. This is critical for a business that wants to rely on sentiment analysis to analyze customer data and provide better customer service.
<title-4>Copilot Helps in Tackling Repetitive Tasks</title-4>
Another critical benefit of Github Copilot is helping developers complete repetitive coding tasks faster and with less effort. When you incorporate Copilot in your processes, it will learn your coding style as you feed the code and comments. And as you progress, you will find that the tool figures out the context and auto-fills repetitive code with better accuracy.
<title-4>Pushing Developers To Better Document Code</title-4>
Copilot helps developers improve their code documenting techniques. As mentioned earlier, Github works better when the code lines and comments are kept simple. And as you progress using the tool, your overall coding skills improve tremendously. The code document is not only accessible for Copilot to create more accurate completions but also makes the code more accessible for you and others to read and improve.
<br>
<title-3>GitHub Copilot Doesn't Replace Human Developers.</title-3>
Will Github Copilot replace human developers? NO! Copilot is an assistant, just as the name suggests. It cannot write an entire code on its own at the click of a button. The user is still in total control to get better results. After all, you must test and verify the code to ensure it works. Rather than replacing developers, Github Copilot makes them more productive and happier with their work.
<br>
<title-3>Final Thoughts</title-3>
The future of coding is brighter, thanks to AI tools like Github Copilot. This machine learning AI is extensive for developers and businesses alike. It complements developers' skills and improves their creativity in creating business solutions that work. And most importantly, Copilot can help with sentiment analysis that aids businesses in understanding their consumers' behavior and offering them satisfactory services.
|
Java | UTF-8 | 53 | 2.171875 | 2 | [] | no_license | public long longValue() {
return (long) value;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.