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
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 216 | 1.984375 | 2 |
[
"MIT"
] |
permissive
|
package main.java.utils.os;
import main.java.Main;
public class ThisJar {
public static boolean checkJar(){
return !Main.class.getResource("Main.class").toString().split(":")[0].equals("file");
}
}
|
C++
|
UTF-8
| 810 | 2.8125 | 3 |
[] |
no_license
|
/**
* @file timer.h
*
* @brief The Timer header file.
*
* This file is part of SDENV2, a 2D/3D OpenGL framework.
*
*/
#ifndef TIMER_H
#define TIMER_H
#include <iostream>
// include glew
#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>
/**
* @brief The Timer class
*/
class Timer
{
public:
Timer(); ///< @brief Constructor of the Timer
~Timer(); ///< @brief Destructor of the Timer
/// @brief start the Timer
/// @return void
void start();
/// @brief get the amount of seconds
/// @return float
float seconds();
/// @brief stop the Timer
/// @return void
void stop();
/// @brief get if the Timer is running
/// @return bool
bool isRunning();
private:
bool _running; ///< @brief the running bool
float _offset; ///< @brief the offset for the time
};
#endif /* end TIMER_H */
|
C#
|
UTF-8
| 1,144 | 3.4375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Numerics;
namespace NETFinals
{
class NegativeNumberException : Exception
{ }
class FinalsQuestion1
{
public List<int> GetAllPrimeNumbers(int input)
{
List<int> primeNumbersArr = new List<int>();
bool isPrime;
for (int Q1a = 2; Q1a < input; Q1a++)
{
isPrime = true;
for (int Q1a_a = 2; Q1a_a < (Q1a / 2); Q1a_a++)
{
if (Q1a % Q1a_a == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
primeNumbersArr.Add(Q1a);
}
}
return primeNumbersArr;
}
public BigInteger FindFactorial(int input)
{
BigInteger factorialResult = input;
for (int Q1b = input - 1; Q1b > 0; Q1b--)
{
factorialResult *= Q1b;
}
return factorialResult;
}
}
}
|
Java
|
UTF-8
| 8,973 | 1.695313 | 2 |
[] |
no_license
|
package com.pnfsoftware.jeb.rcpclient.parts.units.code;
import com.pnfsoftware.jeb.client.api.IUnitFragment;
import com.pnfsoftware.jeb.core.actions.ActionContext;
import com.pnfsoftware.jeb.core.actions.ActionXrefsData;
import com.pnfsoftware.jeb.core.units.IInteractiveUnit;
import com.pnfsoftware.jeb.core.units.INativeCodeUnit;
import com.pnfsoftware.jeb.core.units.code.asm.items.INativeMethodItem;
import com.pnfsoftware.jeb.rcpclient.RcpClientContext;
import com.pnfsoftware.jeb.rcpclient.actions.ActionUIContext;
import com.pnfsoftware.jeb.rcpclient.actions.GraphicalActionExecutor;
import com.pnfsoftware.jeb.rcpclient.extensions.ViewerRefresher;
import com.pnfsoftware.jeb.rcpclient.extensions.viewers.FilteredTableViewer;
import com.pnfsoftware.jeb.rcpclient.extensions.viewers.IFilteredTableContentProvider;
import com.pnfsoftware.jeb.rcpclient.operations.IContextMenu;
import com.pnfsoftware.jeb.rcpclient.operations.OperationCopy;
import com.pnfsoftware.jeb.rcpclient.parts.ILazyView;
import com.pnfsoftware.jeb.rcpclient.parts.units.AbstractFilteredTableView;
import com.pnfsoftware.jeb.rcpclient.parts.units.IRcpUnitView;
import com.pnfsoftware.jeb.rcpclient.parts.units.InteractiveTextView;
import com.pnfsoftware.jeb.util.events.IEvent;
import com.pnfsoftware.jeb.util.events.IEventListener;
import com.pnfsoftware.jeb.util.logging.GlobalLog;
import com.pnfsoftware.jeb.util.logging.ILogger;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
public class ReferencedMethodsView extends AbstractFilteredTableView<INativeCodeUnit<?>, INativeMethodItem> implements ILazyView {
private static final ILogger logger = GlobalLog.getLogger(ReferencedMethodsView.class);
public ReferencedMethodsView(Composite parent, int flags, RcpClientContext context, INativeCodeUnit<?> unit, IRcpUnitView unitView) {
super(parent, flags, unit, unitView, context, new ContentProvider());
setLayout(new FillLayout());
}
public void lazyInitialization() {
Composite container = new Composite(this, 0);
container.setLayout(new FillLayout());
String[] columnNames = {"Name", "Signature"};
FilteredTableViewer viewer = buildFilteredViewer(container, columnNames);
addContextMenu(new IContextMenu() {
public void fillContextMenu(IMenuManager menuMgr) {
menuMgr.add(new Separator());
menuMgr.add(new OperationCopy(ReferencedMethodsView.this));
menuMgr.add(new Action("Jump to first reference") {
public void run() {
ReferencedMethodsView.this.jumpToFirstMethodReference();
}
});
menuMgr.add(new Action("Cross References") {
public void run() {
ReferencedMethodsView.this.openXref();
}
});
}
});
viewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
ReferencedMethodsView.this.jumpToFirstMethodReference();
}
});
layout();
}
protected boolean isCorrectRow(Object obj) {
return obj instanceof INativeMethodItem;
}
public INativeMethodItem getSelectedRow() {
Object row = getSelectedRawRow();
if (!(row instanceof INativeMethodItem)) {
return null;
}
return (INativeMethodItem) row;
}
private void jumpToFirstMethodReference() {
INativeMethodItem m = getSelectedRow();
if (m != null) {
String address = m.getAddress();
jumpToFirstMethodReference(m, address);
}
}
private boolean jumpToFirstMethodReference(INativeMethodItem m, String originAddress) {
if (this.unitView == null) {
return false;
}
String address = originAddress;
long id;
if (address == null) {
id = m.getItemId();
if (id != 0L) {
ActionContext actionContext = new ActionContext(this.unit, 4, id, null);
ActionXrefsData data = new ActionXrefsData();
if (this.unit.prepareExecution(actionContext, data)) {
List<String> addresses = data.getAddresses();
if ((addresses != null) && (!addresses.isEmpty())) {
address = addresses.get(0);
}
}
}
}
if (address != null) {
for (IUnitFragment fragment : this.unitView.getFragments()) {
if ((fragment instanceof InteractiveTextView)) {
logger.i("Jumping to address: %s", address);
if (((InteractiveTextView) fragment).isValidActiveAddress(address, null)) {
this.unitView.setActiveFragment(fragment);
boolean found = this.unitView.setActiveAddress(address, null, false);
if (found) {
return true;
}
this.unitView.setActiveFragment(this);
}
}
}
}
if (originAddress != null) {
jumpToFirstMethodReference(m, null);
}
return false;
}
private void openXref() {
INativeMethodItem m = getSelectedRow();
if (m == null) {
return;
}
if (this.unitView == null) {
return;
}
long id = m.getItemId();
if (id != 0L) {
IUnitFragment textFragment = null;
for (IUnitFragment fragment : this.unitView.getFragments()) {
if ((fragment instanceof InteractiveTextView)) {
textFragment = fragment;
}
}
if (textFragment == null) {
return;
}
ActionContext actionContext = new ActionContext(this.unit, 4, id, null);
ActionUIContext uictx = new ActionUIContext(actionContext, textFragment);
new GraphicalActionExecutor(getShell(), getContext()).execute(uictx);
}
}
static class ContentProvider implements IFilteredTableContentProvider {
INativeCodeUnit<?> codeunit;
IEventListener listener;
private ViewerRefresher refresher = null;
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
if ((oldInput != null) && (this.listener != null)) {
((INativeCodeUnit) oldInput).removeListener(this.listener);
this.listener = null;
}
this.codeunit = ((INativeCodeUnit) newInput);
this.codeunit = ((INativeCodeUnit) newInput);
if (this.codeunit == null) {
return;
}
if (this.refresher == null) {
this.refresher = new ViewerRefresher(viewer.getControl().getDisplay(), viewer) {
protected void performRefresh() {
if (ReferencedMethodsView.ContentProvider.this.codeunit != null) {
super.performRefresh();
}
}
};
}
this.listener = new IEventListener() {
public void onEvent(IEvent e) {
ReferencedMethodsView.logger.i("Event: %s", e);
if ((ReferencedMethodsView.ContentProvider.this.codeunit != null) && (e.getSource() == ReferencedMethodsView.ContentProvider.this.codeunit)) {
ReferencedMethodsView.ContentProvider.this.refresher.request();
}
}
};
this.codeunit.addListener(this.listener);
}
public Object[] getElements(Object inputElement) {
List<INativeMethodItem> list = new ArrayList<>();
for (INativeMethodItem m : this.codeunit.getMethods()) {
if (m.getData() == null) {
list.add(m);
}
}
return list.toArray();
}
public Object[] getRowElements(Object row) {
INativeMethodItem m = (INativeMethodItem) row;
String name = m.getName(true);
String signature = m.getSignature(true);
return new Object[]{name, signature};
}
public boolean isChecked(Object row) {
return false;
}
}
}
|
Go
|
UTF-8
| 2,213 | 2.890625 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
package hijinks
import (
"sort"
"net/http"
)
const (
ContentType = "application/x.hijinks-html-partial+xml"
)
type ResponseData interface {
http.ResponseWriter
// render the template with the supplied data
Data(interface{})
// load data from specified child handler
Delegate(string, *http.Request) (interface{}, bool)
}
type Block interface {
WithDefault(string, HandlerFunc) Block
Default() Handler
Extend(string, HandlerFunc) Handler
Container() Handler
}
type Handler interface {
http.Handler
Func() HandlerFunc
Template() string
Extends() Block
DefineBlock(string) Block
GetBlocks() map[string]Block
Includes(...Handler) Handler
GetIncludes() map[Block]Handler
}
type HandlerFunc func(ResponseData, *http.Request)
// assemble an index of how each block in the hierarchy is mapped to a handler based upon a 'primary' handler
func resolveTemplatesForHandler(block Block, primary Handler) (map[Block]Handler, []string) {
var handler Handler
if primary != nil {
if block == primary.Extends() {
handler = primary
} else if include, found := primary.GetIncludes()[block]; found {
handler = include
} else if blockDefault := block.Default(); blockDefault != nil {
handler = blockDefault
}
}
var templates []string
var blockMap map[Block]Handler
if handler != nil {
blockMap = map[Block]Handler{
block: handler,
}
templates = []string{
handler.Template(),
}
var subBlockMap map[Block]Handler
var subTemplates []string
var names []string
var childBlock Block
blocks := handler.GetBlocks()
// sort block names because we want the order of templates to be stable even if it
// isn't a total order in general
for k := range blocks {
names = append(names, k)
}
sort.Strings(names)
for _, name := range names {
childBlock = blocks[name]
subBlockMap, subTemplates = resolveTemplatesForHandler(childBlock, primary)
for childBlock, childHandler := range subBlockMap {
blockMap[childBlock] = childHandler
}
templates = append(templates, subTemplates...)
}
}
filtered := templates[:0]
for _, templ := range templates {
if templ != "" {
filtered = append(filtered, templ)
}
}
return blockMap, filtered
}
|
Markdown
|
UTF-8
| 575 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
# React Application: Video Browser from Youtube
This is my first attempt in learning React.js building a SPA to browse videos from Youtube website.
1 - In the "01_first_component" branch I create my first React component rendering it to the web page.
2 - In the "02_more_components_and_organization" branch I create the "components" folder with 4 different kind of component: search bar, video details, video list and video list items. I work on the two kinds of component: functional and class components. I also use user events handler inside the search bar component.
|
Java
|
UTF-8
| 10,430 | 1.914063 | 2 |
[] |
no_license
|
package alcoholmod.Mathioks.Final.UtilityItems;
import alcoholmod.Mathioks.AlcoholMod;
import alcoholmod.Mathioks.ExtendedPlayer;
import alcoholmod.Mathioks.ExtraFunctions.SyncJutsuPointsMessage;
import alcoholmod.Mathioks.PacketDispatcher;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List;
import lc208.tools;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
public class RegularJutsuItem extends Item {
public void onUpdate(ItemStack par1ItemStack, World par2World, Entity par3Entity, int par4, boolean par5) {
if ((EntityPlayer)par3Entity != null) {
if (par1ItemStack.stackTagCompound == null) {
ExtendedPlayer props = ExtendedPlayer.get((EntityPlayer)par3Entity);
if (props.getWaterRelease() == 0) {
int rand = par2World.rand.nextInt(20);
par1ItemStack.stackTagCompound = new NBTTagCompound();
if (rand == 4 || rand == 5 || rand == 6 || rand == 7)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Shuriken Technique");
if (rand == 8 || rand == 9 || rand == 10 || rand == 11)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Kunai Technique");
if (rand == 17 || rand == 18)
par1ItemStack.stackTagCompound.setString("Jutsu", "Summoning: Rolling Log");
}
if (props.getWaterRelease() == 1) {
int rand = par2World.rand.nextInt(22);
par1ItemStack.stackTagCompound = new NBTTagCompound();
if (rand == 4 || rand == 5 || rand == 6 || rand == 7)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Shuriken Technique");
if (rand == 8 || rand == 9 || rand == 10 || rand == 11)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Kunai Technique");
if (rand == 17 || rand == 18)
par1ItemStack.stackTagCompound.setString("Jutsu", "Water Release: Takigakure Sword");
if (rand == 19 || rand == 20)
par1ItemStack.stackTagCompound.setString("Jutsu", "Summoning: Rolling Log");
}
}
if (par1ItemStack.stackTagCompound != null && par1ItemStack.stackTagCompound.getString("Jutsu").equals("")) {
ExtendedPlayer props = ExtendedPlayer.get((EntityPlayer)par3Entity);
if (props.getWaterRelease() == 0) {
int rand = par2World.rand.nextInt(20);
par1ItemStack.stackTagCompound = new NBTTagCompound();
if (rand == 4 || rand == 5 || rand == 6 || rand == 7)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Shuriken Technique");
if (rand == 8 || rand == 9 || rand == 10 || rand == 11)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Kunai Technique");
if (rand == 17 || rand == 18)
par1ItemStack.stackTagCompound.setString("Jutsu", "Summoning: Rolling Log");
}
if (props.getWaterRelease() == 1) {
int rand = par2World.rand.nextInt(22);
par1ItemStack.stackTagCompound = new NBTTagCompound();
if (rand == 4 || rand == 5 || rand == 6 || rand == 7)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Shuriken Technique");
if (rand == 8 || rand == 9 || rand == 10 || rand == 11)
par1ItemStack.stackTagCompound.setString("Jutsu", "Kage Kunai Technique");
if (rand == 17 || rand == 18)
par1ItemStack.stackTagCompound.setString("Jutsu", "Water Release: Takigakure Sword");
if (rand == 19 || rand == 20)
par1ItemStack.stackTagCompound.setString("Jutsu", "Summoning: Rolling Log");
}
}
}
}
public ItemStack onItemRightClick(ItemStack par1ItemStack, World par2World, EntityPlayer player) {
if (!par2World.isRemote && !player.capabilities.isCreativeMode && tools.freeSpace(player.inventory.mainInventory) > 0) {
ExtendedPlayer props = ExtendedPlayer.get(player);
if (props.getJutsuPoints() >= 5) {
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Sexy Technique")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.KageBunshinSexy, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You learned the Sexy Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Kage Shuriken Technique")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.KageSmallShurikenJutsu, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You learned the Kage Shuriken Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Kage Kunai Technique")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.KageKunaiJutsu, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You learned the Kage Kunai Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Chakra for Health Charge")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.ChakraRechargeUltimate, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You Learned the Chakra for Health Charge Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Explosion Clone")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.SuperExplosionItem, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You learned the Explosion Clone Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Mist Servant Technique")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.MistServantTechnique, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You Learned the Mist Servant Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Summoning: Rolling Log")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.SummonLog, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You Learned the Summoning: Rolling Log Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Water Release: Takigakure Sword")) {
if (props.getWaterRelease() != 1) {
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You cannot learn this jutsu as you do not"));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("have the Water chakra nature type!"));
return par1ItemStack;
}
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.ItemWatercuttingSword, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You Learned the Takigakure: WaterCutting Sword Technique!"));
}
if (par1ItemStack.stackTagCompound.getString("Jutsu").equals("Bind Clone")) {
player.inventory.addItemStackToInventory(new ItemStack(AlcoholMod.GenjutsuBindClone, 1, 0));
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You Learned the Genjutsu: Bind Clone!"));
}
props.setJutsuPoints(props.getJutsuPoints() - 5);
PacketDispatcher.sendTo((IMessage)new SyncJutsuPointsMessage(player), (EntityPlayerMP)player);
par1ItemStack.stackSize--;
} else {
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You do not have enough Jutsu Points!"));
}
} else if (tools.freeSpace(player.inventory.mainInventory) <= 0) {
player.addChatComponentMessage((IChatComponent)new ChatComponentText("You do not have enough free space"));
}
return par1ItemStack;
}
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack par1ItemStack, EntityPlayer par2EntityPlayer, List par3List, boolean par4) {
par3List.add(EnumChatFormatting.RED + "Learn a D-B rank Jutsu");
par3List.add(EnumChatFormatting.RED + "JP Cost: 5");
if (par1ItemStack.stackTagCompound == null) {
ExtendedPlayer props = ExtendedPlayer.get(par2EntityPlayer);
if (props.getWaterRelease() == 0) {
par3List.add(EnumChatFormatting.GREEN + "Possible Jutsu:");
par3List.add(EnumChatFormatting.BLUE + "- Sexy Technique");
par3List.add(EnumChatFormatting.BLUE + "- Kage Shuriken Technique");
par3List.add(EnumChatFormatting.BLUE + "- Kage Kunai Technique");
par3List.add(EnumChatFormatting.DARK_PURPLE + "- Chakra for Health Charge");
par3List.add(EnumChatFormatting.DARK_PURPLE + "- Summoning: Rolling Log");
par3List.add(EnumChatFormatting.RED + "- Bind Clone");
par3List.add(EnumChatFormatting.RED + "- Explosion Clone");
par3List.add(EnumChatFormatting.RED + "- Mist Servant Technique");
}
if (props.getWaterRelease() == 1) {
par3List.add(EnumChatFormatting.GREEN + "Possible Jutsu:");
par3List.add(EnumChatFormatting.BLUE + "- Sexy Technique");
par3List.add(EnumChatFormatting.BLUE + "- Kage Shuriken Technique");
par3List.add(EnumChatFormatting.BLUE + "- Kage Kunai Technique");
par3List.add(EnumChatFormatting.DARK_PURPLE + "- Chakra for Health Charge");
par3List.add(EnumChatFormatting.DARK_PURPLE + "- Summoning: Rolling Log");
par3List.add(EnumChatFormatting.DARK_PURPLE + "- Water Release: Takigakure Sword");
par3List.add(EnumChatFormatting.RED + "- Bind Clone");
par3List.add(EnumChatFormatting.RED + "- Explosion Clone");
par3List.add(EnumChatFormatting.RED + "- Mist Servant Technique");
}
}
if (par1ItemStack.stackTagCompound != null)
par3List.add(EnumChatFormatting.GREEN + par1ItemStack.stackTagCompound.getString("Jutsu"));
}
}
|
Java
|
UTF-8
| 7,369 | 2.09375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.huaweicloud.sdk.mpc.v1.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
/**
* OutputSetting
*/
public class OutputSetting {
/**
* 剪切或拼接的输出封装格式。
*/
public static final class FormatEnum {
/**
* Enum MP4 for value: "MP4"
*/
public static final FormatEnum MP4 = new FormatEnum("MP4");
/**
* Enum HLS for value: "HLS"
*/
public static final FormatEnum HLS = new FormatEnum("HLS");
/**
* Enum TS for value: "TS"
*/
public static final FormatEnum TS = new FormatEnum("TS");
/**
* Enum FLV for value: "FLV"
*/
public static final FormatEnum FLV = new FormatEnum("FLV");
private static final Map<String, FormatEnum> STATIC_FIELDS = createStaticFields();
private static Map<String, FormatEnum> createStaticFields() {
Map<String, FormatEnum> map = new HashMap<>();
map.put("MP4", MP4);
map.put("HLS", HLS);
map.put("TS", TS);
map.put("FLV", FLV);
return Collections.unmodifiableMap(map);
}
private String value;
FormatEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static FormatEnum fromValue(String value) {
if (value == null) {
return null;
}
return java.util.Optional.ofNullable(STATIC_FIELDS.get(value)).orElse(new FormatEnum(value));
}
public static FormatEnum valueOf(String value) {
if (value == null) {
return null;
}
return java.util.Optional.ofNullable(STATIC_FIELDS.get(value))
.orElseThrow(() -> new IllegalArgumentException("Unexpected value '" + value + "'"));
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FormatEnum) {
return this.value.equals(((FormatEnum) obj).value);
}
return false;
}
@Override
public int hashCode() {
return this.value.hashCode();
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "format")
private FormatEnum format;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "video")
private EditVideoInfo video;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "audio")
private EditAudioInfo audio;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "hls")
private EditHlsInfo hls;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonProperty(value = "output")
private ObsObjInfo output;
public OutputSetting withFormat(FormatEnum format) {
this.format = format;
return this;
}
/**
* 剪切或拼接的输出封装格式。
* @return format
*/
public FormatEnum getFormat() {
return format;
}
public void setFormat(FormatEnum format) {
this.format = format;
}
public OutputSetting withVideo(EditVideoInfo video) {
this.video = video;
return this;
}
public OutputSetting withVideo(Consumer<EditVideoInfo> videoSetter) {
if (this.video == null) {
this.video = new EditVideoInfo();
videoSetter.accept(this.video);
}
return this;
}
/**
* Get video
* @return video
*/
public EditVideoInfo getVideo() {
return video;
}
public void setVideo(EditVideoInfo video) {
this.video = video;
}
public OutputSetting withAudio(EditAudioInfo audio) {
this.audio = audio;
return this;
}
public OutputSetting withAudio(Consumer<EditAudioInfo> audioSetter) {
if (this.audio == null) {
this.audio = new EditAudioInfo();
audioSetter.accept(this.audio);
}
return this;
}
/**
* Get audio
* @return audio
*/
public EditAudioInfo getAudio() {
return audio;
}
public void setAudio(EditAudioInfo audio) {
this.audio = audio;
}
public OutputSetting withHls(EditHlsInfo hls) {
this.hls = hls;
return this;
}
public OutputSetting withHls(Consumer<EditHlsInfo> hlsSetter) {
if (this.hls == null) {
this.hls = new EditHlsInfo();
hlsSetter.accept(this.hls);
}
return this;
}
/**
* Get hls
* @return hls
*/
public EditHlsInfo getHls() {
return hls;
}
public void setHls(EditHlsInfo hls) {
this.hls = hls;
}
public OutputSetting withOutput(ObsObjInfo output) {
this.output = output;
return this;
}
public OutputSetting withOutput(Consumer<ObsObjInfo> outputSetter) {
if (this.output == null) {
this.output = new ObsObjInfo();
outputSetter.accept(this.output);
}
return this;
}
/**
* Get output
* @return output
*/
public ObsObjInfo getOutput() {
return output;
}
public void setOutput(ObsObjInfo output) {
this.output = output;
}
@Override
public boolean equals(java.lang.Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
OutputSetting that = (OutputSetting) obj;
return Objects.equals(this.format, that.format) && Objects.equals(this.video, that.video)
&& Objects.equals(this.audio, that.audio) && Objects.equals(this.hls, that.hls)
&& Objects.equals(this.output, that.output);
}
@Override
public int hashCode() {
return Objects.hash(format, video, audio, hls, output);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OutputSetting {\n");
sb.append(" format: ").append(toIndentedString(format)).append("\n");
sb.append(" video: ").append(toIndentedString(video)).append("\n");
sb.append(" audio: ").append(toIndentedString(audio)).append("\n");
sb.append(" hls: ").append(toIndentedString(hls)).append("\n");
sb.append(" output: ").append(toIndentedString(output)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
C++
|
GB18030
| 2,982 | 2.515625 | 3 |
[] |
no_license
|
#include "pthread_list.h"
#include "server_socket.cpp"
#include <signal.h>
#define STATE 0
void create_epoll(struct thread_list_node*);
void setnumber(struct thread_list_node* head);
pthread_mutexattr_t mutexattr;
pthread_mutex_t mutex;
pthread_key_t mytmp;
struct thread_list_node* head =
new struct thread_list_node;
pthread_key_t epoll_root;
void signal_catch(int signum)
{
#if STATE
if(signum == SIGPIPE)
cout<<" signall SIGPIPE recive! "<<endl;
else
cout<<"other SIG recived1 "<<endl;
#endif
}
int create_thread()
{
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mutex,&mutexattr);
head->init_num=0;
pthread_key_create(&epoll_root,NULL);
int ret;
pthread_t thr;
pthread_attr_t attr;
ret = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
// if(ret != 0) perror("pthread_attr_setdetached:");
ret = pthread_attr_init(&attr);
// if(ret != 0)perror("pthread_attr_init:");
ret = pthread_create(&thr,&attr,loop_thread_func,(void*)NULL);
// if(ret!=0) perror("pthread_create:");
}
void* loop_thread_func(void* args)
{
pthread_mutex_lock(&mutex);
struct sigaction myaction,oldaction;
myaction.sa_handler = signal_catch;
int res = sigaction(SIGPIPE,&myaction,&oldaction);
if(res != 0) perror("sigaction:");
struct thread_list_node* tmp = new struct thread_list_node;
tmp->next = head->next;
head->next = tmp;
setnumber(head);
tmp->max_event = MAX_EVENT;
tmp->conned = 0;
tmp->disconned=0;
tmp->session_head = NULL;
create_epoll(tmp);
struct epoll_event* evt = (struct epoll_event*)malloc
(sizeof(struct epoll_event)*tmp->max_event);
int nready;
++head->init_num;
tmp->init_num = head->num;
pthread_mutex_unlock(&mutex);
while(head->init_num<THREAD_NUM);//ʼ
int* myepoll_fd = (int*)pthread_getspecific(epoll_root);
struct thread_list_node*h = head->next;
while(h->next!=NULL)
{
if(h->epoll_root == *myepoll_fd) break;
h = h->next;
}
struct cnn_event myevent;
while(1)
{
// cout<<"[ pthread_list.cpp 79 ]:thread id ["<<h->num<<"]: waiting"<<endl;
nready = epoll_wait(tmp->epoll_root,evt,MAX_EVENT,-1);
for(int i=0;i<nready;++i)
{
if(evt[i].events & EPOLLIN){
// cout<<"EOLLIN coming"<<endl;
myevent.cnn_read(&evt[i]);
}
else if(evt[i].events & EPOLLOUT){
// cout<<"EPOLLOUT COMING"<<endl;
myevent.cnn_write(&evt[i]);
}
else if(evt[i].events & EPOLLRDHUP)
myevent.cnn_close(&evt[i]);
//ᴥRD ͨEPOLLIN readж
}
}
}
#if 1
void done(struct thread_list_node* h,int& count)
{
if(h==NULL) return;
done(h->next,count);
h->num = count;
++count;
}
void setnumber(struct thread_list_node* h)
{
int count = 0;
done(h,count);
}
#endif
void create_epoll(struct thread_list_node*tmp)
{
int epfd = epoll_create(MAX_EVENT);
if(epfd <0)perror("epoll_create:");
tmp->epoll_root = epfd;
pthread_setspecific(epoll_root,(void*)&tmp->epoll_root);
}
|
Swift
|
UTF-8
| 4,636 | 2.671875 | 3 |
[] |
no_license
|
//
// DropDownList.swift
// ShoppingCartApp
//
// Created by Vikash Kumar on 22/07/17.
// Copyright © 2017 Vikash Kumar. All rights reserved.
//
import UIKit
//Class function
extension DropDownList {
class func show(in view: UIView, listFrame senderFrame: CGRect, listData: ([String], String), actionHandler: @escaping (String)-> Void){
let list = DropDownList(frame: view.bounds)
list.listData = listData
list.actionHandler = actionHandler
list.alpha = 0
//list.backgroundColor = UIColor.clear
view.addSubview(list)
list.setTableFrame(with: senderFrame)
UIView.animate(withDuration: 0.2) {
list.alpha = 1
}
}
}
//DropDown list
class DropDownList: UIView {
var tableView = UITableView()
var tblHeight: CGFloat = 120
let cellHeight: CGFloat = 30
let shadowLayer = CALayer()
var listData: (items: [String], selectedItem: String) = ([], "") {
didSet {
}
}
var actionHandler: (String)-> Void = {_ in}
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
deinit {
print("list view removed")
}
private func setupViews() {
//add background button for handle event for hide the dropdown
let button = UIButton(frame: self.bounds)
self.addSubview(button)
tableView.frame = self.bounds
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = UIColor.white
tableView.clipsToBounds = true
tableView.layer.cornerRadius = 5
self.addSubview(tableView)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
//add a shadow layer behide tableview
shadowLayer.backgroundColor = UIColor.white.cgColor
shadowLayer.shadowOffset = CGSize(width: 0, height: 0)
shadowLayer.cornerRadius = 3.0
shadowLayer.shadowOpacity = 0.6
shadowLayer.masksToBounds = false
self.layer.insertSublayer(shadowLayer, at: 0)
self.layer.masksToBounds = true
self.backgroundColor = UIColor.black.withAlphaComponent(0.05)
button.addTarget(self, action: #selector(self.tapHandler(sender:)), for: .touchUpInside)
}
//handler for background button action for hide dropdownlist
func tapHandler(sender: UIButton?) {
UIView.animate(withDuration: 0.2, animations: {
self.alpha = 0
}) { (success) in
self.removeFromSuperview()
}
}
//Set table's frame at give position
func setTableFrame(with senderFrame: CGRect) {
if listData.items.count < 5 {
tblHeight = cellHeight * CGFloat(listData.items.count)
}
let y: CGFloat
let showAtUpSide = (self.frame.height - senderFrame.origin.y) < (tblHeight + 10 )
if showAtUpSide {
y = senderFrame.origin.y - tblHeight - 10 - senderFrame.height
} else {
y = senderFrame.origin.y - 8
}
let listFrame = CGRect(x: senderFrame.origin.x, y: y, width: senderFrame.width, height: tblHeight)
setDropDownFrame(rect: listFrame)
}
private func setDropDownFrame(rect: CGRect) {
tableView.frame = rect
shadowLayer.frame = tableView.frame
}
}
extension DropDownList: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listData.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
let item = listData.items[indexPath.row]
cell.textLabel?.text = item
cell.accessoryType = item == listData.selectedItem ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return cellHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
actionHandler(listData.items[indexPath.row])
self.tapHandler(sender: nil)
}
}
|
Java
|
UTF-8
| 499 | 3.09375 | 3 |
[] |
no_license
|
package ejemplo2;
public class Profesor extends Persona {
private String materia;
public Profesor(String nombre, String materia) {
super(nombre);
this.materia = materia;
}
public String getMateria() {
return materia;
}
public void setMateria(String materia) {
this.materia = materia;
}
public void mostrar(){
System.out.println("Nombre: " + nombre + " materia: " + materia);
}
}
|
JavaScript
|
UTF-8
| 2,307 | 4.3125 | 4 |
[] |
no_license
|
function hola(nombre, miCallback) {
setTimeout(function () {
console.log("Hola " + nombre);
miCallback(nombre)
}, 1000)
}
function hablar(callbackHablar) {
setTimeout(function () {
console.log("Bla bla bla...")
callbackHablar()
}, 100)
}
function adios(nombre, otroCallback) {
setTimeout(function () {
console.log("Adiós", nombre);
otroCallback()
}, 1000)
}
// Declaramos una función que recibe el nombre con quien estamos hablando, las veces que queremos hablar y un callback que será lo queremos que pase después de terminar de hablar
function conversación(nombre, veces, callback) {
// Si el numbero de las veces es mayor que 0, continua hablando
if (veces > 0) {
// Para solucionar el callback hell usaremos la RECURSIVIDAD, la cual es simplemente llamar a la misma función pero con información ligeramente distinta
// Por lo tanto llamaremos a la función hablar la cual ejecuta lo que tenga que en este caso es un bla bla bla y luego recibe como parámetro otra función (que es la misma conversación), se ejecutará una vez termine el proceso propio de la función hablar
hablar(function () {
// Lo que queremos que haga es que haya una conversación, llamamos la función conversación a la cual le pasamos los parametros necesarios para su ejecución
conversación(nombre, --veces, callback)
})
} else {
// De lo contrario ejecutamos mi función adios con un nombre al que se tiene que despedir y el segundo parámetro que recibe es el callback
adios(nombre, callback)
}
}
// Esto es un callback hell
console.log("Iniciando proceso...")
// Llamo a mi función y le envío un nombre y un callback con el parametro nombre
hola("Stiven", function (nombre) {
// Y dentro de este callback llamo mi función conversación a la cual le envio como parámetro, el nombre, el número de veces y le envío el callback con un console.log que diga "Proceso terminado"
conversación(nombre, 3, function () {
console.log("Proceso terminado")
})
})
// hola("Stiven", function (nombre) {
// hablar(function () {
// hablar(function () {
// hablar(function () {
// adios(nombre, function () {
// console.log("Terminando proceso...")
// })
// })
// })
// })
// })
|
C++
|
UTF-8
| 1,588 | 3.328125 | 3 |
[] |
no_license
|
#include "dictionary.h"
#include <fstream>
using std::ifstream;
dictionary::dictionary() {}
dictionary::dictionary(string & fileName)
{
ifstream fin;
fin.open(fileName.ctr());
char content[100];
while (fin.getline(content, 100))
{
string new_word(content);
int k = key(new_word);
data[k].add(new_word);
}
}
dictionary::dictionary(char *fileName)
{
ifstream fin;
fin.open(fileName);
char content[100];
while (fin.getline(content, 100))
{
string new_word(content);
int k = key(new_word);
data[k].add(new_word);
}
}
dictionary::~dictionary(){}
int dictionary::key(string & word)
{
int k1 = static_cast<int>(word[1] + 128) << 10;
int k2 = static_cast<int>(word[4] + 128) << 3;
int k3 = static_cast<int>(word[2] + 128) >> 4;
int k = k1 + k2 + k3;
return k;
}
void dictionary::addWords(string & fileName)
{
ifstream fin;
fin.open(fileName.ctr());
char content[100];
while (fin.getline(content, 100))
{
string new_word(content);
int k = key(new_word);
if (k > 65535)
{
std::cout << "键值越界\n";
exit(2);
}
data[k].add(new_word);
}
}
void dictionary::addWords(char *fileName)
{
ifstream fin;
fin.open(fileName);
char content[100];
while (fin.getline(content, 100))
{
string new_word(content);
int k = key(new_word);
data[k].add(new_word);
if (k > 65535)
{
std::cout << "键值越界\n";
exit(2);
}
}
}
bool dictionary::findWords(string & fileName)
{
int k = key(fileName);
if (k > 65535)
return false;
int result = data[k].search(fileName);
if (result == -1)
return false;
else
return true;
}
|
C
|
UTF-8
| 556 | 3.484375 | 3 |
[] |
no_license
|
#include <stdio.h>
void drawPine(int height, int width ){
for (int i = 0; i < height; ++i){
int starsLimit = i*2+1;
int spaceLimit = i+height-starsLimit;
for (int j = 0; j < spaceLimit; ++j){
printf(" ");
}
for (int j = 0; j < starsLimit; ++j){
printf("*");
}
printf("\n");
}
for (int k = 0; k < 2; ++k){
for (int i = 0; i < height-width/2-1; ++i){
printf(" ");
}
for (int i = 0; i < width+1; ++i){
printf("|");
}
printf("\n");
}
}
int main(int argc, char const *argv[]){
drawPine(6,2);
return 0;
}
|
Python
|
UTF-8
| 11,691 | 3.703125 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
# Imports.
import numpy as np
import math
# Classes for a basic neural network.
# Class for a single neuron. Specialized to use with a multi-layer feed-
# forward neural network using the logistic sigmoid activation funcion.
class Neuron:
# Fields:
# _aWeights - Array of the neuron's weights.
# _fcnActFcn - Activation function used to compute the output.
# _dBeta - Scale factor applied to the activation function.
# _dActLevel - Actvity level of the neuron.
# Constructor.
def __init__(self, iNumInputs, fcnAF, dBeta = 1.0):
# Initialize the weights to random values. Distribution is uniform in
# range -1/sqrt(iNumInputs) to 1/sqrt(iNumInputs).
dSqrtNumInputs = 1/math.sqrt(iNumInputs)
self._aWeights = np.random.uniform(-dSqrtNumInputs, dSqrtNumInputs, iNumInputs)
# The activation function and scale factor are passed in.
self._fcnActFcn = fcnAF
self._dBeta = dBeta
# Initialize the activity level to zero.
self._dActLevel = 0.0
# Calculate the output, given a vector of inputs.
def dOutput(self, aInputs):
# Calculate the activity level.
self._dActLevel = np.dot(self._aWeights, aInputs)
# Calculate and return the output.
dOut = self._fcnActFcn(self._dBeta * self._dActLevel)
return dOut
# Adjust the weights to reduce the error in the output for the given input.
def vLearn(self, aInputs, dError, dEta):
# Calculate the output from this neuron.
dY = self.dOutput(aInputs)
# Calculate the factor to multiply aInputs by when adjusting weights.
dFactor = dEta * dError * self._dBeta * dY * (1.0 - dY)
# Adjust the weights by adding on the factor times the inputs.
self._aWeights += dFactor * aInputs
# Possible activation functions.
# Heaviside fcn.
def Heaviside(dX):
if dX < 0.0:
return 0.0
else:
return 1.0
# Logistic sigmoid function.
def Sigmoid(dX):
return 1.0 / (1.0 + math.exp(-dX))
# A class for a group of neurons arranged into a single layer. Any input put into
# the layer is fed into each neuron in the layer, and the outputs from all of the
# neurons are combined into a vector, which becomes the output of the layer.
class NNLayer:
# Field:
# _aNeurons - Array of the neurons in this layer.
# Constructor.
# Parameters are the same as for the Neuron class, except that we also need
# a parameter for the number of neurons in the layer.
def __init__(self, iNumInputs, iNumNeurons, fActFcn, dBeta = 1.0):
# Bulid up a list of the proper number of neurons, then convert the list
# into an array.
lstNeurons = []
for iCount in range(iNumNeurons):
lstNeurons.append(Neuron(iNumInputs, fActFcn, dBeta))
# Create the array and put it into the field _aNeurons.
self._aNeurons = np.array(lstNeurons)
# For convenience, keep track of the the number of inputs and number of
# neurons.
self._iNumInputs = iNumInputs
self._iNumNeurons = iNumNeurons
# Calculate the array of outputs from all neurons in the layer, given an
# array of inputs.
def aOutput(self, aInputs):
# Create a list of the outputs from each of the neurons in the layer,
# then convert it to an array.
lstOuts = []
for neuOne in self._aNeurons:
lstOuts.append(neuOne.dOutput(aInputs))
# Finished. Counvert list to an array and return it.
return np.array(lstOuts)
# Adjust the weights of all of the neurons in this layer, given an input
# array and an array of errors in the outputs of the neurons. At the same
# time, calculate the errors in the outputs of the previous layer and
# return them.
def aLearn(self, aInputs, aErrors, dEta):
# Loop through the neurons in this layer and calculate each one's
# contribution to the errors in the previous layer, then adjust its
# weights. When finished, return the array of errors in the previous
# layer.
# Start with zeros for the errors in the previous layer.
aPrevErrors = np.zeros((self._iNumInputs,))
for k in range(self._iNumNeurons):
# Get the current (kth) neuron, calcualte its output, and get its
# error.
neuCurrNeu = self._aNeurons[k]
dY = neuCurrNeu.dOutput(aInputs)
dCurrError = aErrors[k]
dFactor = dY * (1.0 - dY) * dCurrError
# This neuron's contribution to the error in the previous layer is
# the above factor times its weights.
aPrevErrors += dFactor * neuCurrNeu._aWeights
# Now we can adjust this neuron's weights.
neuCurrNeu.vLearn(aInputs, dCurrError, dEta)
# Once we have finished the loop, all neurons have had their weights
# updated, and we have calculated the contribution of all neurons to
# the errors in the previous layer. Return the array of errors in the
# previous layer.
return aPrevErrors
# A class for a full multi-layer neural network.
class NeuralNet:
# Fields:
# _aLayers - Array of the layers in the network.
# _iNumLayers - Number of layers.
# _iNumInputs - Number of inputs to the first layer.
# _iNumOutputs - Number of outputs from the final layer.
# Constructor.
def __init__(self, iNumInputs, lstNumNeurons, fActFcn, dBeta = 1.0):
# Bulid up the list of layers one by one.
lstLayers = []
# Loop through list of numbers of neurons in each layer, create each
# layer in turn. Have to keep track of the number of inputs for the
# current layer, because it changes from layer to layer.
iCurrNumInputs = iNumInputs
for iCurrNumNeurons in lstNumNeurons:
lstLayers.append(NNLayer(iCurrNumInputs, iCurrNumNeurons, fActFcn, dBeta))
# Number of inputs for the next layer is the number of neurons in
# the current layer.
iCurrNumInputs = iCurrNumNeurons
# List of layers complete. Convert to an array and put into field
# _aLayers. Also, set other fields.
self._aLayers = np.array(lstLayers)
self._iNumLayers = len(self._aLayers)
self._iNumInputs = iNumInputs
self._iNumOutputs = lstNumNeurons[-1]
# Compute the output, given an array of inputs.
def aOutput(self, aInputs):
# Loop through the layers in the network, putting the appropriate
# input into each layer and having it calculate the corresponding
# output. The output from one layer becomes the input to the next
# layer. The output from the last layer is the final output.
aCurrInputs = aInputs
for nnlOneLayer in self._aLayers:
aCurrOutputs = nnlOneLayer.aOutput(aCurrInputs)
aCurrInputs = aCurrOutputs
# Finished. Outputs from last time through loop are the outputs from
# the network.
return aCurrOutputs
# Adjust the weights in all of the neurons in all of the layers of this
# network, given the initial input and an array of the targets.
def vLearn(self, aInputs, aTargets, dEta):
# Start by building up a list of the layers together with their inputs.
aCurrInputs = aInputs
lstLayersInputs = []
for nnlCurrLayer in self._aLayers:
# Add tuple of current layer and its inputs to the list.
lstLayersInputs.append((aCurrInputs, nnlCurrLayer))
# Update the current inputs: The inputs to the next layer are the
# outputs from the current layer.
aCurrOutputs = nnlCurrLayer.aOutput(aCurrInputs)
aCurrInputs = aCurrOutputs
# Now we have a list of the layers and inputs. Now, calculate errors
# and adjust the weights in each layer, working from the last layer
# back to the first layer.
# Note that "aCurrOutputs" at the end of the for loop is the output
# from the last layer. We use it
# together with the array of targets to calculate the errors in the
# last layer.
aCurrErrors = aTargets - aCurrOutputs
# Loop through the the layers from the last to the first, training each
# layer and getting the errors for the previous layer.
for tLayerInputs in lstLayersInputs[::-1]:
# Extract current layer and inputs from the tuple.
(aCurrInputs, nnlCurrLayer) = tLayerInputs
# Update weights in the current layer, obtaining at the same time
# the errors in the previous layer, which will be the next layer
# we train.
aCurrErrors = nnlCurrLayer.aLearn(aCurrInputs, aCurrErrors, dEta)
# Train the neural network on a given training set, going through the set
# single time.
def vLearnOnePass(self, tsSet, dEta):
# Loop through the training pairs in the training set. Train on each
# one individually.
for tOnePair in tsSet:
# Extract the inputs and targets.
(aInputs, aTargets) = tOnePair
# Train this neural network with the given inputs and targets.
self.vLearn(aInputs, aTargets, dEta)
# Train the network on a given training set by going through the training
# set multiple times.
def vLearnManyPasses(self, tsSet, dEta, iNumReps):
# Repeat calling vLearnOnePass multiple times.
for k in range(iNumReps):
# Make a copy of the training set, then shuffle it in a random order,
# and train using the shuffled set.
tsShuffled = list(tsSet)
np.random.shuffle(tsShuffled)
# Train ourselves using the shuffled training set.
self.vLearnOnePass(tsShuffled, dEta)
# Find the maximum difference between an output and the corresponding target
# for all of the examples (pairs) in a given training set.
def dShowMaxError(self, tsSet):
# Keep track of the largest differnce found so far. Initially 0.
dMaxDiffSoFar = 0.0
# Loop through the training set and compare outputs with targets.
for (aInputs, aTarget) in tsSet:
# Calculate output, then difference between output and target.
aOutput = self.aOutput(aInputs)
dDiff = np.linalg.norm(aOutput - aTarget)
# If new difference is bigger than max difference so far, update
# max difference so far.
if dDiff > dMaxDiffSoFar:
dMaxDiffSoFar = dDiff
# Finished with loop, so max diff so far is the overall max difference.
return dMaxDiffSoFar
# Show what fraction of the training pairs yield outputs that are within
# a given tolerance of their targets.
def dShowTSPerform(self, tsSet, dTolerance):
# Set up to count the number of training pairs for which the output is
# within the given tolerance of the target.
iCount = 0
for (aInputs, aTarget) in tsSet:
# Calculate output, then difference between output and target.
aOutput = self.aOutput(aInputs)
dDiff = np.linalg.norm(aOutput - aTarget)
# Check whether the difference is less than or equal to the tolerance.
# If so, increment the count.
if dDiff <= dTolerance:
iCount += 1
# Checked all pairs. Calculate fraction and return it.
return iCount / len(tsSet)
|
Shell
|
UTF-8
| 1,881 | 3.4375 | 3 |
[] |
no_license
|
#!/bin/bash
#
##################################################################################################################
# Written to be used on 64 bits computers
# Author : Erik Dubois
# Website : http://www.erikdubois.be
##################################################################################################################
##################################################################################################################
#
# DO NOT JUST RUN THIS. EXAMINE AND JUDGE. RUN AT YOUR OWN RISK.
#
##################################################################################################################
echo "################################################################"
echo "Checking if git is installed"
echo "Install git for an easy installation"
# G I T
# check if git is installed
if which git > /dev/null; then
echo "git was installed. Proceding..."
else
echo "################################################################"
echo "installing git for this script to work"
echo "################################################################"
sudo apt-get install git -y
fi
rm -rf /tmp/Plank-Themes
git clone https://github.com/erikdubois/Plank-Themes /tmp/Plank-Themes
find /tmp/Plank-Themes -maxdepth 1 -type f -exec rm -rf '{}' \;
# if there is no hidden folder then make one
[ -d $HOME"/.local/share/plank" ] || mkdir -p $HOME"/.local/share/plank"
# if there is no hidden folder then make one
[ -d $HOME"/.local/share/plank/themes" ] || mkdir -p $HOME"/.local/share/plank/themes"
cp -r /tmp/Plank-Themes/* ~/.local/share/plank/themes/
rm -rf /tmp/Plank-Themes
echo "################################################################"
echo "################### plank themes installed ############"
echo "################################################################"
|
C
|
UTF-8
| 1,720 | 2.53125 | 3 |
[] |
no_license
|
#include "app.h"
#include "debug.h"
#include "sock.h"
int debug;
int main(int argc, char *argv[]){
int retv, sockfd;
uint8_t mip_dst;
uint16_t port;
uint16_t filesize;
char *filename;
char *sockpath;
char *file;
retv = handle_argv(argc, argv, 5, 'c');
if(retv == -1)
exit(EXIT_SUCCESS);
mip_dst = strtol(argv[optind], NULL, 10);
port = strtol(argv[optind+1], NULL, 10);
filename = argv[optind+2];
sockpath = argv[optind+3];
if(debug)
DLOG("loading file");
file = load_file(filename, &filesize);
if(file == NULL)
exit(EXIT_FAILURE);
if(debug)
DLOG("creating socket");
sockfd = socket(AF_UNIX, SOCK_SEQPACKET, 0);
if(sockfd == -1){
perror("main(): socket()");
return -1;
}
if(debug)
DLOG("connecting to MIPTP-daemon");
retv = connect_socket(sockfd, sockpath);
if(retv == -1){
close(sockfd);
free(file);
exit(EXIT_FAILURE);
}
if(debug)
DLOG("sending fileinfo to MIPTP-daemon");
retv = send_fileinfo(sockfd, mip_dst, port, filesize);
if(retv == -1){
free(file);
close(sockfd);
exit(EXIT_SUCCESS);
}
if(debug)
DLOG("sending file to MIPTP-daemon");
retv = send_file(sockfd, file, filesize);
if(retv == -1){
close(sockfd);
free(file);
exit(EXIT_FAILURE);
}
// test-print
if(debug)
fprintf(stderr, "send_file(): number of bytes sent: %d\n", retv);
// end
// have a ping test here, miptp sends an ack to ping_client when it
// receives the last ack from the server-miptp.
// start_timer();
// recv_ack();
// end_timer();
// print_timespent();
if(debug)
DLOG("shutting down ping-client");
close(sockfd);
free(file);
return EXIT_SUCCESS;
}
|
Java
|
UTF-8
| 411 | 2.265625 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package revisao_aula2;
/**
*
* @author matheusroberto
*/
class Aluno {
int idade;
String nome;
float nota;
public Aluno(int i, String n, float nt){
idade = i;
nome = n;
nota = nt;
}
}
|
Python
|
UTF-8
| 460 | 2.796875 | 3 |
[] |
no_license
|
import sys
sys.stdin = open("같은모양찾기.txt")
T = int(input())
data = [list(map(int, input())) for _ in range(T)]
t = int(input())
target = [list(map(int, input())) for _ in range(t)]
find = 0
for i in range(T-t+1):
for j in range(T-t+1):
cnt = 0
for k in range(t):
for L in range(t):
if data[i+k][j+L] == target[k][L]:
cnt +=1
if cnt == 9:
find +=1
print(find)
|
Java
|
UTF-8
| 2,399 | 2.609375 | 3 |
[] |
no_license
|
package me.togo.demo.disruptor.quickstart;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import me.togo.demo.disruptor.Const;
import me.togo.demo.disruptor.Data;
import org.junit.Test;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import static me.togo.demo.disruptor.Const.NUM_OHM;
public class FirstTest {
@Test
public void testBookingQueueBySingleThread() {
final ArrayBlockingQueue<Data> queue = new ArrayBlockingQueue<>(NUM_OHM);
final CountDownLatch countDownLatch = new CountDownLatch(NUM_OHM);
long startTime = System.currentTimeMillis();
new Thread(() -> {
long i = 0;
while (i < NUM_OHM) {
try {
queue.put(new Data(i, "ccc_" + i));
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
}
}).start();
new Thread(() -> {
long k = 0;
while (k < NUM_OHM) {
try {
queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
k++;
countDownLatch.countDown();
}
long endTime = System.currentTimeMillis();
System.out.println("BlockingQueue build " + NUM_OHM + " data set of cost total time:" + (endTime - startTime) + "ms.");
}).start();
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testDisruptorBySingleThread() {
final int rinngBufferSize = 65536;
final Random random = new Random(31);
Disruptor<Data> disruptor = new Disruptor<Data>(new EventFactory<Data>() {
@Override
public Data newInstance() {
return new Data(random.nextLong(), "ccc_" + random.nextLong());
}
},
rinngBufferSize,
Executors.newSingleThreadScheduledExecutor(),
ProducerType.SINGLE, new YieldingWaitStrategy());
}
}
|
Java
|
UTF-8
| 2,090 | 2.859375 | 3 |
[
"MIT"
] |
permissive
|
package callete.api.services.music.model;
import org.apache.commons.lang.StringUtils;
/**
* The model that represents an album.
*/
public class Album extends Playlist {
private String artist;
private String genre;
private int year;
private String id;
public Album(String artist, String name) {
super(name);
this.artist = artist;
}
@Override
public void addSong(Song song) {
super.addSong(song);
song.setAlbum(this);
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getId() {
if(id == null) {
StringBuilder key = new StringBuilder();
if(!StringUtils.isEmpty(getName())) {
key.append(getName());
}
key.append("-");
if(!StringUtils.isEmpty(getArtist())) {
key.append(getArtist());
}
id = key.toString();
id = id.replaceAll(" ", "-");
id = id.replaceAll("'", "-");
id = id.replaceAll("%", "-");
id = id.replaceAll(":", "-");
id = id.replaceAll("!", "");
id = id.replaceAll("/", "-");
id = id.replaceAll("\\\\", "-");
id = id.replaceAll("\\?", "-");
id = id.replaceAll("\\&", "-");
id = id.replaceAll("\\$", "-");
id = id.replaceAll("\\.", "-");
id = id.replaceAll("'", "");
id = id.replaceAll(",", "-");
id = id.replaceAll("ó", "o");
id = id.replaceAll("í", "i");
id = id.replaceAll("á", "ai");
id = id.replaceAll("é", "e");
id = id.replaceAll("ö", "oe");
id = id.replaceAll("ä", "ae");
id = id.replaceAll("ü", "ue");
id = id.replaceAll("--", "-");
id = id.toLowerCase();
}
return id;
}
@Override
public String toString() {
return "Album '" + getName() + "' by '" + artist + "', tracks: " + getSize();
}
}
|
Markdown
|
UTF-8
| 2,318 | 2.8125 | 3 |
[] |
no_license
|
# ApkDecompiler
Linux版apk反编译工具,主要使用GUI包装了以下几个工具。
<br />
1、反编译资源(可能需要有此框架才能正常反编译:framework-res.apk)
./apktool/apktool d ./test.apk
```
usage: apktool
-advance,--advanced prints advance information.
-version,--version prints the version then exits
usage: apktool if|install-framework [options] <framework.apk>
-p,--frame-path <dir> Stores framework files into <dir>.
-t,--tag <tag> Tag frameworks using <tag>.
usage: apktool d[ecode] [options] <file_apk>
-f,--force Force delete destination directory.
-o,--output <dir> The name of folder that gets written. Default is apk.out
-p,--frame-path <dir> Uses framework files located in <dir>.
-r,--no-res Do not decode resources.
-s,--no-src Do not decode sources.
-t,--frame-tag <tag> Uses framework files tagged by <tag>.
usage: apktool b[uild] [options] <app_path>
-f,--force-all Skip changes detection and build all files.
-o,--output <dir> The name of apk that gets written. Default is dist/name.apk
-p,--frame-path <dir> Uses framework files located in <dir>.
```
2、dex2jar,将apk转为jar
./dex2jar/d2j-dex2jar.sh ./test.apk
```
usage: d2j-dex2jar [options] <file0> [file1 ... fileN]
options:
-d,--debug-info translate debug info
-e,--exception-file <file> detail exception file, default is $current_dir/[fi
le-name]-error.zip
-f,--force force overwrite
-h,--help Print this help message
-n,--not-handle-exception not handle any exception throwed by dex2jar
-o,--output <out-jar-file> output .jar file, default is $current_dir/[file-na
me]-dex2jar.jar
-os,--optmize-synchronized optmize-synchronized
-p,--print-ir print ir to Syste.out
-r,--reuse-reg reuse regiter while generate java .class file
-s same with --topological-sort/-ts
-ts,--topological-sort sort block by topological, that will generate more
readable code
-v,--verbose show progress
```
3、 使用jd-gui查看jar源代码
./jd-gui ./test.jar
|
Java
|
UTF-8
| 1,219 | 2.640625 | 3 |
[] |
no_license
|
package org.cacheframework.memorystore.command;
import java.util.List;
import org.cacheframework.memorystore.annotations.Command;
import org.cacheframework.memorystore.annotations.ParamLength;
import org.cacheframework.memorystore.request.RequestData;
import org.cacheframework.memorystore.response.ResponseData;
import org.cacheframework.memorystore.server.ValueHolder;
import org.cacheframework.memorystore.utilities.Constants;
/**
* Remove command with one parameter
* to be passed. This command makes
* server remove value against
* parameter as key.
*
* Usage: REMOVE <text>
*
* @author Vijay
* @version 0.1
* @since JDK 1.8
*
*/
@Command("remove")
@ParamLength(1)
public class RemoveDataCommand implements ICommand {
/**
*
* Execute methiod
*
* @param requestData
* @return responseData
*
*/
public ResponseData execute(RequestData request) {
ValueHolder instance = ValueHolder.getInstance();
List<Object> keyValuePair = request.getParams();
instance.removeValue((String) keyValuePair.get(0));
ResponseData data = new ResponseData();
data.setResponseCode(Constants.SUCCESS);
data.setOutput("Data removed from cache");
return data;
}
}
|
Python
|
UTF-8
| 4,599 | 2.546875 | 3 |
[
"Artistic-1.0"
] |
permissive
|
#!/usr/bin/env python3
import argparse
import fileinput
import sys
import os
import numpy as np
# author Giovanna Migliorelli
# version beta 02.06.2020
parser = argparse.ArgumentParser(description='Extract transcripts from some Ensembl annoation on the base of given chunks.')
parser.add_argument('-c', '--chunks',
#required=True,
nargs='+',
help='a list of one or more positive integers indicating the chunk/s for which we want to build a minimal annotation from given Ensembl.')
args = parser.parse_args()
# helper function to extract values for some key (e.g. gene_id, transcript_id) from ENSEMBL like 8th field in some gff line
def extractTransId(str, key):
value = ''
for x in str.split(';'):
pos = x.find(key)
if pos>-1:
value = x.split("\"")[1]
return value
# reads in some annotation file and filters in those transcripts which fall in the interval [left,right]
def extractAnno(infile, outfile, mode, left, right, overlap, subset):
transcripts = {}
with open(infile, 'r') as input:
while True:
line = input.readline()
if not line:
break
if line.find('#')==-1 and line!='\n':
split = [x for x in line.split("\t") if x != ""]
if split[0] == '1':
trans_id = extractTransId(split[8], 'transcript_id')
if trans_id != '':
if trans_id not in subset:
# just in case gff contains some unordered pair
start = min(int(split[3]), int(split[4]))
end = max(int(split[3]), int(split[4]))
if trans_id in transcripts:
transcripts[trans_id][0] = min(transcripts[trans_id][0], start)
transcripts[trans_id][1] = max(transcripts[trans_id][1], end)
else:
transcripts[trans_id] = [start, end]
# read once again and filter (not smart but helps saving mem)
with open(infile, 'r') as input, open(outfile, mode) as output:
while True:
line = input.readline()
if not line:
break
if line.find('#')==-1 and line!='\n': # here comments and blank lines are purged, we can change it though
split = [x for x in line.split("\t") if x != ""]
trans_id = extractTransId(split[8], 'transcript_id')
if trans_id != '':
if trans_id in transcripts:
if overlap == 'full':
if transcripts[trans_id][0]>=left and transcripts[trans_id][0]<=right:
output.write(line)
subset[trans_id] = True
elif overlap == 'partial':
if not(transcripts[trans_id][0]>=right or transcripts[trans_id][0]<=left):
output.write(line)
subset[trans_id] = True
if __name__ == '__main__':
if args.chunks is None:
print('No chunks specified, please make use of --chunks to pass a non empty list of positive integers...')
sys.exit()
chunks = [int(x) for x in list(dict.fromkeys(args.chunks))]
chunks = [x for x in chunks if x>0 and x<126] # range valid for chr1 chunk size 2.5 Mb, chunk overlap 0.5 Mb
if len(chunks) == 0:
sys.exit()
# should be synced with chunk_size, chunk_overlap, dir names used in the project see executeTestCGP.py for details
chunk_size = 2500000
chunk_overlap = 500000
infile = '../examples/cgp12way/ENSEMBL/ensembl.ensembl_and_ensembl_havana.chr1.CDS.gtf.dupClean.gtf'
outfile = '../examples/cgp12way/ENSEMBL/ensembl.ensembl_and_ensembl_havana.chr1.CDS.gtf.dupClean.FILTERED.gtf'
subset = {} # used to keep track of those transcripts which have been already included and avoid duplicates
print('Cleaning up old', outfile)
if os.path.exists(outfile):
os.remove(outfile)
for chunk in chunks:
left = (chunk_size-chunk_overlap)*(chunk-1)
right = left + chunk_size - 1
print('Including transcripts entirely contained within chunk', chunk, '[', left, ',', right, ']')
extractAnno(infile, outfile, 'a+', left, right, 'full', subset)
|
Java
|
UTF-8
| 3,566 | 1.945313 | 2 |
[] |
no_license
|
package com.maxcar.user.service.impl;
import com.maxcar.base.dao.BaseDao;
import com.maxcar.base.service.impl.BaseServiceImpl;
import com.maxcar.user.dao.ResourceMapper;
import com.maxcar.user.dao.RoleResourceMapper;
import com.maxcar.user.entity.Resource;
import com.maxcar.user.entity.ResourceOption;
import com.maxcar.user.entity.RoleResource;
import com.maxcar.user.entity.RoleResourceExample;
import com.maxcar.user.service.ResourceService;
import com.maxcar.user.service.RoleResourceOptionService;
import com.maxcar.user.service.RoleResourceService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description: 角色资源服务层
* @Param:
* @return:
* @Author: 罗顺锋
* @Date: 2018/4/24
*/
@Service("roleResourceService")
public class RoleResourceServiceImpl extends BaseServiceImpl<RoleResource,String> implements RoleResourceService {
@Autowired
private RoleResourceMapper roleResourceMapper;
@Autowired
private ResourceMapper resourceMapper;
@Autowired
private RoleResourceOptionService roleResourceOptionService;
@Autowired
private ResourceService resourceService;
@Override
public BaseDao<RoleResource, String> getBaseMapper() {
return roleResourceMapper;
}
@Override
public Integer ValidRoleResource(String roleId, String resource) {
String resourceId = resourceService.getResourceIdByUrl(resource);
//该链接不在资源时,提示用户无盖请求资源,404
if(StringUtils.isEmpty(resourceId)) {
return 0;
}
//再验证改角色是否有此资源访问权限
RoleResourceExample example = new RoleResourceExample();
example.createCriteria().andResourceIdEqualTo(resourceId);
List<RoleResource> resources = roleResourceMapper.selectByExample(example);
return (resources!=null&&resources.size()>0)?1:2;
}
@Override
public List<Resource> getResourcesByUserId(String userId,Boolean ifAll) {
Map map = new HashMap();
map.put("userId",userId);
map.put("ifAll",ifAll);
map.put("level",1);//一级菜单
List<Resource> resources = roleResourceMapper.findMenuByUserId(map);
resources = getChildResources(resources,userId);
return resources;
}
@Override
public List<Resource> getChildResources(List<Resource> resources,String userId) {
for(Resource resource:resources) {
Map map = new HashMap();
map.put("userId",userId);
map.put("parentId",resource.getResourceId());//一级菜单
// ResourceExample resourceExample = new ResourceExample();
// resourceExample.createCriteria().andParentIdEqualTo(resource.getResourceId()).
// andResourceTypeEqualTo(0);
// List<Resource> childRes = resourceMapper.selectByExample(resourceExample);
List<Resource> childRes = roleResourceMapper.findMenuByUserId(map);
//插入角色资源操作信息
List<ResourceOption> roleResourceOptions = roleResourceOptionService.getResourceOptionByUserIdAndResourceId(map);
resource.setChildList(childRes);
resource.setResourceOptions(roleResourceOptions);
if(childRes!=null) {
getChildResources(childRes,userId);
}
}
return resources;
}
}
|
Ruby
|
UTF-8
| 893 | 2.625 | 3 |
[] |
no_license
|
class WeatherController < ApplicationController
def show
@weather = Weather.find(params[:id]) rescue nil
if @weather
render json: { weather: @weather }
else
render json: { error: 'That weather id does not exist.' }, status: :not_found
end
end
def by_location
if params[:latitude] && params[:longitude]
set_forecast
if @forecast
render json: { weather: @forecast }
else
render json: {
error: "We couldn't find that location. "\
"Please make sure your lat/long coordinates aren't mixed up."
}, status: :not_found
end
else
render json: { error: 'Missing latitude and/or longitude paramters' }, status: :unprocessable_entity
end
end
private
def set_forecast
@forecast = ForecastIO.forecast(params[:latitude].to_f, params[:longitude].to_f)
end
end
|
Python
|
UTF-8
| 564 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
import time
class Timer:
def __init__(self):
self.startTime = time.time()
self.pauseTime = 0
self.invalidTime = 0
def setTime(self, t):
self.startTime = t
def getTime(self):
return time.time() - self.startTime - self.invalidTime
def getNow(self):
return time.time()
def getModifiedTime(self):
return round(self.getTime(), 1)
def pause(self):
self.pauseTime = time.time()
def restart(self):
self.invalidTime += time.time() - self.pauseTime
|
Java
|
UTF-8
| 1,513 | 3.015625 | 3 |
[] |
no_license
|
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class NonRandom {
private List<Vertex> vertices = new LinkedList<>();
int n;
public NonRandom(int n,int y) {
this.n=n;
//generate ring base
if(n>0) {
vertices.add(new Vertex(0));
for(int i=1;i<n;i++) {
vertices.add(new Vertex(i));
vertices.get(i).addNeighbor(vertices.get(i-1));
}
vertices.get(n-1).addNeighbor(vertices.get(0));
}
for(int j=0;j<y;j++) {
for(int i=0+j*n/(2*y);i<n/2+j*n/(2*y);i++) {
if(vertices.get(i%n).getNeighbor().contains(vertices.get((2*i+2)%n))||i%n==(2*i+2)%n) {
continue;
} else {
vertices.get(i%n).addNeighbor(vertices.get((2*i+2)%n));
}
}
for(int i=n/2+j*n/(2*y);i<n+j*n/(2*y);i++) {
if(vertices.get(i%n).getNeighbor().contains(vertices.get((2*i+2+n/2)%n))||i%n==(2*i+2+n/2)%n) {
continue;
} else {
vertices.get(i%n).addNeighbor(vertices.get((2*i+2+n/2)%n));
}
}
}
try {
FileWriter myWriter = new FileWriter("C:\\Users\\An Chao\\eclipse-workspace\\RingRndSC\\src\\Ring.txt");
myWriter.write(toString());
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public String toString(){
String result=""+n+"\r";
for(Vertex v:vertices) {
result+=v.toString();
}
return result;
}
}
|
Markdown
|
UTF-8
| 1,889 | 3.296875 | 3 |
[
"MIT"
] |
permissive
|
# Walle.Excel.Extension
可以快速使用的跨平台Excel帮助类,可选NPOI版本和EPPLUS版本.
- 针对NCC社区的NPOI版本进行的一些扩展类.
- 针对EPPLUS进行的一些扩展类.
## 安装
https://www.nuget.org/packages/Walle.Excel.EPPlus.Extension/1.2.2
## 查看部分Demo 或运行测试项目
- 将你的实体类继承于```ISheetRow```接口,实体类Demo如下:
```csharp
public class Person : ISheetRow
{
[Column(Title = "Id")]
public int Id { get; set; }
[Column(Title = "名字", DefaultValue = "未知")]
public string Name { get; set; }
[Column(Title = "生日", DateFormat = "yyyy-MM-dd")]
public DateTime Birthday { get; set; } = new DateTime(1900, 1, 1);
[Column(Ignore = true)]
public string Remark { get; set; } = string.Empty;
}
```
- 放在```IEnumable<T>```中,如下:
```csharp
static void Main(string[] args)
{
Console.WriteLine("Press any key!");
Console.ReadKey();
List<Person> people = new List<Person>
{
new Person
{
Id = 1,
Name = "Peter",
Birthday = new DateTime(1991, 12, 1)
},
new Person
{
Id = 2,
Name = "Harry",
Birthday = new DateTime(1993, 9, 16)
},
new Person
{
Id = 3,
Name = "Amy",
Birthday = new DateTime(1994, 6, 16)
}
};
people.ToExcel("c:/people.xlsx");
// 也可以直接使用byte[]
byte[] result = people.ToExcelContent();
}
```
|
Python
|
UTF-8
| 412 | 3.625 | 4 |
[] |
no_license
|
def sort_array(source_array):
odds = []
for x in source_array:
if x % 2 == 1:
odds.append(x)
odds = sorted(odds)
index = 0
lens = len(source_array)
for i in range(len(source_array)):
if source_array[i] % 2 == 1:
source_array[i] = odds[index]
index += 1
# print(" ".join([str(x) for x in source_array]))
return source_array
|
Python
|
UTF-8
| 2,492 | 3.140625 | 3 |
[] |
no_license
|
import sys
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
import scipy.fftpack as fftpack
# proper ecgs
# 4
f = open("ecg_test_data5")
fig_size = (10, 6)
# process the input data
data = []
time = []
value = []
for line in f:
entry = line.strip().split(',')
x, y = entry
time.append(int(x))
value.append(int(y))
time = np.array(time)
value = np.array(value) * -1
# 1 original signal
print("========================")
# get last time and first time to determine duration (s)
Ts = abs(time[-1] - time[0]) / 1000.0
N = len(time)
print("Duration: {}s | Number of Samples: {}".format(Ts, N))
# sampling frequency (N/Ts)
Fs = int(round(N/Ts))
print("Sampling Frequency: {}".format(Fs))
# 2 fft of the original signal
T = 1.0 / 800
fft_freqs = np.linspace(0.0, 1.0/(2.0*T), N//2)
fft_value = fftpack.fft(value)
plot_fft_value = 2.0/N * np.abs(fft_value[0:N//2])
# 3 low pass butterworth filter
sos = signal.butter(10, 10, 'lowpass', fs=Fs, output='sos')
filtered_value = np.round(signal.sosfiltfilt(sos, value), 4) # zero-phase
# filtered_value = np.round(signal.sosfilt(sos, value), 4) # conventional
sos = signal.butter(5, 0.5, 'highpass', fs=Fs, output='sos')
filtered_value = np.round(signal.sosfiltfilt(sos, filtered_value), 4) # zero-phase
# 4 fft of the filtered signal
filtered_fft_value = fftpack.fft(filtered_value)
filtered_plot_fft_value = 2.0/N * np.abs(fft_value[0:N//2])
# Output
# 1st figure
fig1 = plt.figure(1, figsize=fig_size)
plt.subplot(221)
plt.title("Original Signal")
plt.ylabel("ADC Value")
plt.xlabel("Time (ms)")
plt.plot(time, value)
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
# 2 fft of the original signal
plt.subplot(222)
plt.title("FFT of Original Signal")
plt.ylabel("ADC Value")
plt.xlabel("Frequency (Hz)")
plt.ylim(top=100, bottom=-5)
# plt.plot(fft_freqs, np.abs(fft_value[0:N//2]))
plt.plot(fft_freqs, 2.0/N * np.abs(fft_value[:N//2]))
# 3 low pass butterworth filter
plt.subplot(223)
# plt.title("5th Order 10 Hz Low Pass\nZero-Phase Butterworth Filter")
plt.ylabel("ADC Value")
plt.xlabel("Time (ms)")
plt.plot(time, filtered_value)
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
# 4 fft of the filtered signal
plt.subplot(224)
plt.title("FFT of Filtered Signal")
plt.ylabel("ADC Value")
plt.xlabel("Frequency (Hz)")
plt.ylim(top=100, bottom=-5)
plt.plot(fft_freqs, 2.0/N * np.abs(filtered_fft_value[0:N//2]))
plt.tight_layout()
plt.show()
|
Python
|
UTF-8
| 2,075 | 2.984375 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import scrapy
# 导入item抓取的节点信息
from scrapy_demo.items import ScrapyDemoItem
'''
爬虫文件
'''
class DoubanSpidersSpider(scrapy.Spider):
# 爬虫名称
name = 'douban_spiders'
# 允许的域名 爬虫
allowed_domains = ['movie.douban.com']
# 入口url,扔到调度器
start_urls = ['http://movie.douban.com/top250']
# 默认解析 用xPath
def parse(self, response):
## xpath解析 最外层需要// ->里面就可以用/ 不然可能存在解析问题
movie_list = response.xpath("//div[@class='article']//ol[@class='grid_view']/li")
for i in movie_list:
# 遍历数据 放入节点中
douban_item = ScrapyDemoItem()
# 当前目录下 xpath 前面+.
# 序号
douban_item['movie_num'] = i.xpath(".//div[@class='item']//em/text()").extract_first()
# 电影名称
douban_item['movie_name'] = i.xpath(
".//div[@class='item']//div[@class='hd']/a//span[1]/text()").extract_first()
# 电影简介 多行数据处理
content = i.xpath(".//div[@class='info']//div[@class='bd']/p[1]/text()").extract()
for i_content in content:
douban_item['introduce'] = "".join(i_content.split())
# 星级
douban_item['star'] = i.xpath(".//span[@class='rating_num']/text()").extract_first()
# 评论
douban_item['evaluate'] = i.xpath(".//div[@class='star']/span[4]/text()").extract_first()
# 描述
douban_item['describe'] = i.xpath(".//p[@class='quote']/span/text()").extract_first()
# 传输数据进入管道
yield douban_item
# 下一页
next_link = response.xpath("//span[@class='next']/link/@href").extract()
if next_link:
next_link = next_link[0]
# 提交管道进行 下一页处理
yield scrapy.Request("http://movie.douban.com/top250" + next_link, callback=self.parse)
|
C++
|
UTF-8
| 3,521 | 3.203125 | 3 |
[] |
no_license
|
#include "Mochila.hpp"
Mochila::Mochila(int capacidad)
{
if(capacidad > 0){
this->capacidad_maxima = capacidad;
this->volumen_usado = 0;
}else{
this->volumen_usado = 0;
}
};
Mochila::~Mochila()
{
this->volumen_usado = 0;
this->conjunto.clear();
};
float Mochila::getMochila(){
list<Material>::iterator it;
float aux = 0.0;
// Calculamos el precio total de la mochila sumando todos los precios por unidades de volumen
for(it=this->conjunto.begin(); it != this->conjunto.end(); it++){
aux = aux + it->getPrecio() * it->getVolumen();
}
return aux;
};
void Mochila::getContenidoMochila(){
list<Material>::iterator it;
for(it=this->conjunto.begin(); it != this->conjunto.end(); it++){
cout<<"Etiqueta: "<<it->getEtiqueta()<<endl;
cout<<"Precio: "<<it->getPrecio()<<endl;
cout<<"Volumen usado: "<<it->getVolumen()<<endl;
cout<<"Estado: "<<it->getState()<<endl;
cout<<"Valor total: "<<it->getPrecio()*it->getVolumen()<<endl;
cout<<endl;
}
};
bool Mochila::setCapacidad(int capacidad){
if(capacidad<=0){
return false;
}else{
this->capacidad_maxima = capacidad;
return true;
}
};
bool Mochila::nuevoMaterial(Material &M){
// Si el volumen que hemos usado es menor que la capacidad de la mochila
if(this->volumen_usado != this->capacidad_maxima){
Material auxM;
// El volumen del material entra en la mochila
if(this->getVolumenQueda() > M.getVolumen()){
M.setState("usado");
auxM = M;
this->volumen_usado += auxM.getVolumen();
}// El volumen del material no entra entero en la mochila
else{
M.setState("parcial");
auxM = M;
auxM.setVolumen(this->capacidad_maxima - this->volumen_usado);
this->volumen_usado = this->capacidad_maxima;
}
this->conjunto.push_back(auxM);
return true;
}// El material no cabe en la mochila
else{
return false;
}
};
void Mochila::vaciarMochila(){
this->volumen_usado = 0;
this->conjunto.clear();
};
void Mochila::rellenarMochila(vector<Material> &materiales){
int precio_maximo;
int material_maximo;
bool material_esta_disponible;
Material auxM;
// Inicializamos la mochila a zero
vaciarMochila();
// Inicializamos los materiales
for(int i = 0; i < materiales.size(); i++){
materiales[i].setState("no_usado");
}
// Rellenamos la mochila hasta que sea posible
do{
precio_maximo = 0;
material_maximo = 0;
material_esta_disponible = false;
// Recorremos todos los materiales disponibles
for(int i = 0; i < materiales.size(); i++){
// Si el material no ha sido usado
if(materiales[i].getState() == "no_usado"){
material_esta_disponible = true;
// Si el precio del material es mayor que el precio maximo guardamos el material en la mochila
if(materiales[i].getPrecio() > precio_maximo){
material_maximo = i;
precio_maximo = materiales[i].getPrecio();
}
}
}
// Introducimos el material en la mochila
if(material_esta_disponible == true){
nuevoMaterial(materiales[material_maximo]);
}
}while(this->getVolumenQueda() != 0 && material_esta_disponible==true);
};
|
Markdown
|
UTF-8
| 1,483 | 2.734375 | 3 |
[] |
no_license
|
# restful-blog-microservices-phase3
This project is part of the transformation to microservices of project https://github.com/benjsicam/restful-blog, it was splitted in 4 stages for educational purposes
Take into account that for this stage you have to complete all stage 2, for this stage you will need to create three new databases with the following tables:
**restful_blog_categories**
```sql
CREATE TABLE IF NOT EXISTS `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `category` (`id`, `name`) VALUES
(1, 'General'),
(2, 'News'),
(3, 'Announcements');
CREATE TABLE IF NOT EXISTS `post_category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`post_id` bigint(20) NOT NULL,
`category_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK4BC509BD1CD41CA0` (`category_id`),
CONSTRAINT `FKqly0d5oc4npxdig2fjfoshhxg` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
INSERT INTO `post_category` (`id`, `post_id`, `category_id`) VALUES
(1, 1, 1),
(2, 4, 1),
(3, 2, 2),
(4, 5, 2),
(5, 3, 3),
(6, 6, 3);
```
Also you will need to setup include a new file in git repository for the spring cloud configurtion service, if you are using windows you can use gitstack free version. The repository was named restful_blog_configuration_properties, that is category.properties
|
C++
|
UTF-8
| 864 | 3.0625 | 3 |
[] |
no_license
|
#include <cstdlib>
#include <iostream>
#include "FragTrap.hpp"
FragTrap::FragTrap(std::string name)
{
_hitpt = 100;
_maxhitpt = 100;
_nrjpt = 100;
_maxnrjpt = 100;
_lvl = 1;
_name = name;
_meleedmg = 30;
_rangedmg = 20;
_armorreduc = 5;
std::cout << "FR4G-TP " << _name << " is born !" << std::endl;
}
FragTrap::~FragTrap(void)
{
std::cout << "FR4G-TP " << _name << " ended !" << std::endl;
}
void FragTrap::vaulthunter_dot_exe(std::string const & target)
{
std::string tab[] = {
"pen",
"apple",
"pine",
"applepen",
"pineapple",
"penpineappleapplepen"
};
size_t sz = sizeof(tab) / sizeof(*tab);
if (_nrjpt < 25) {
std::cout << "You don't have enough energy to attack !!!" << std::endl;
return;
}
_nrjpt -= 25;
std::cout << "FR4G-TP " << _name << " attack " << target << " with " << tab[rand() % sz] << " !!!" << std::endl;
}
|
Java
|
UTF-8
| 357 | 2.171875 | 2 |
[] |
no_license
|
package dados;
import basicas.Usuario;
public class UsuarioDAO {
public void inserirUsuario (Usuario u){
}
public Usuario pesquisarUsuario (String login){
return null;
}
public boolean efetuarLogin (String log, String senha){
if (log.equals (senha)){
return true;
}else {
return false;
}
}
}
|
Python
|
UTF-8
| 132 | 2.515625 | 3 |
[] |
no_license
|
class ListNode:
def __init__(self, x):
self.val
class Solution:
def addTwoNumbers(self, l1, l2):
res =
|
SQL
|
UTF-8
| 538 | 3.8125 | 4 |
[] |
no_license
|
-- Creates a stored procedure ComputeAverageWeightedScoreForUser that computes
-- and stores the average score for a student
-- Procedure AddBonus takes 1 input:
-- user_id, a users.id value, can assume user_id is linked to existing users
DELIMITER //
CREATE PROCEDURE ComputeAverageWeightedScoreForUser (IN user_id_new INTEGER)
BEGIN
UPDATE users SET average_score=(
SELECT SUM(score * weight) / SUM(weight) FROM corrections
JOIN projects
ON corrections.project_id=projects.id
WHERE user_id=user_id_new);
END; //
DELIMITER ;
|
Java
|
UTF-8
| 12,917 | 3.046875 | 3 |
[] |
no_license
|
package parsleyj.arucoslam;
/**
* Collections of the all native methods used by the app, which were all collected here because the
* linking between Kotlin and the C++ JNI functions does not recognise the types of some parameters
* (in particular, {@code Array<Array<Double>>} were translated to {@code jobject[]} in C++,
* instead of {@code jdouble[][]}.
*/
public class NativeMethods {
/**
* Given an image, detects all the markers and computes their poses in it. Each "pose"
* is an RT transformation which switches points from the marker's coordinate system
* to the coordinate system of the camera?
* Moreover, copies the input image on the output image, and adds the "contours"
* to the detected markers.
*
* @param markerDictionary the dictionary of markers
* @param cameraMatrixAddr the camera matrix
* @param distCoeffsAddr the distortion coefficients of the camera
* @param inputMatAddr the input image
* @param resultMatAddr the output image
* @param markerSize the side length (in meters) of the markers
* @param maxMarkers the maximum numbers of markers expected to be found in an image
* @param detectedIDsVect an array which will be filled with the IDs of the found markers
* @param outRvects an array (of size 3*N) which contains the rotation vectors of the marker
* poses
* @param outTvects an array (of size 3*N) which contains the translation vectors of the marker
* poses
* @return the number of markers found (N)
*/
public static native int detectMarkers(
int markerDictionary,
long cameraMatrixAddr,
long distCoeffsAddr,
long inputMatAddr,
long resultMatAddr,
double markerSize,
int maxMarkers,
int[] detectedIDsVect,
double[] outRvects,
double[] outTvects
);
/**
* Given the camera parameters, a set of known poses of various markers and a set of poses of
* markers in an image, attempts to compute an estimate of the pose of the camera in the world
* coordinate system. The returned RT transformation is the one that changes from the world
* coordinate system to the camera coordinate system.
* When there are no pose indicators (i.e. the various poses of the camera, each one obtained
* from the markers which pose in the world is known), nothing is done on the output vectors.
* When there is only an indicator, it is copied as-is on the output vectors.
* When exactly 2 indicators are passed, the "pose centroid" of the two indicators are computed
* and returned as result.
* When more than 2 indicators of such pose are available, the estimate is computed by using
* the RANSAC method.
* Moreover, this function draws the 3D axis of the poses of the markers on the image Mat.
*
* @param cameraMatrixAddr the camera matrix
* @param distCoeffsAddr the distortion coefficients of the camera
* @param inputMatAddr the input image
* @param fixedMarkerCount the count of known markers
* @param fixedMarkers the ids of the known markers
* @param fixedRVects the rotation vectors of the known markers
* @param fixedTVects the translation vectors of the known markers
* @param fixedLength the side length of the markers
* @param foundPoses the count of found marker poses
* @param inMarkers the ids of the found markers
* @param inRvects the rotation vectors of the found markers
* @param inTvects the translation vectors of the found markers
* @param outRvec the output rotation vector of the computed camera pose estimate
* @param outTvec the output translation vector of the computed camera pose estimate
* @param tvecInlierThreshold (RANSAC) threshold of the distance in meters used to determine
* if an estimated pose is an inlier
* @param tvecOutlierProbability (RANSAC) the (pre-estimated) probability that a position in a
* random subset of poses is an outlier (p)
* @param rvecInlierThreshold (RANSAC) threshold of the "angular" distance in radians used to
* determine if an estimated pose is an inlier
* @param rvecOutlierProbability (RANSAC) the (pre-estimated) probability that an orientation
* in a random subset of poses is an outlier (p)
* @param maxRansacIterations (RANSAC) the maximum number of iterations to be performed (M)
* @param optimalModelTargetProbability (RANSAC) probability (P) that the returned pose estimate
* is the optimal pose (i.e. the one with the most inliers);
* this and the previous parameters are used to compute the
* number of effective RANSAC iterations by using this
* formula: min(N, M) where N = log(1-P)/log(1-(1-p^S)) and
* S is the size of the random subset of poses of each
* iteration, which is equal to 5 if the number of total
* poses is >= 10, 2 otherwise.
* @return the number of inliers (w.r.t. the poses used to estimate the pose) of the returned
* estimate.
*/
public static native int estimateCameraPosition(
long cameraMatrixAddr,
long distCoeffsAddr,
long inputMatAddr,
int fixedMarkerCount,
int[] fixedMarkers,
double[] fixedRVects,
double[] fixedTVects,
double fixedLength,
int foundPoses,
int[] inMarkers,
double[] inRvects,
double[] inTvects,
double[] outRvec,
double[] outTvec,
double tvecInlierThreshold,
double tvecOutlierProbability,
double rvecInlierThreshold,
double rvecOutlierProbability,
int maxRansacIterations,
double optimalModelTargetProbability
);
/**
* Computes the inverse of an RT transformation. Note that such computation is not as costly
* as the computation of the inverse of a generic matrix, since the inverse of <br>
* [ R, T, <br>
* 0, 1 ] <br>
* is equal to <br>
* [ R', -R'T, <br>
* 0, 1 ] <br>
* where R' is the transpose of R.
*
* @param inrvec the input rotation vector
* @param intvec the input translation vector
* @param outrvec the rotation vector of the inverse
* @param outtvec the translation vector of the inverse
*/
public static native void invertRT(
double[] inrvec,
double[] intvec,
double[] outrvec,
double[] outtvec
);
/**
* Computes the composition of two RT transformation. If the transformation 1 switches from the
* coordinate system S_a to the coordinate system S_b, and the transformation 2 switches from
* the coordinate system S_b to the coordinate system S_c, the transfromation resulting from
* this operation switches from the coordinate system S_a to the cooordinate system S_c.
*
* @param inRvec1 first input rotation vector
* @param inTvec1 first input translation vector
* @param inRvec2 first input rotation vector
* @param inTvec2 first input translation vector
* @param outRvec the rotation vector of the composed transformation
* @param outTvec the translation vector of the composed transformation
*/
public static native void composeRT(
double[] inRvec1,
double[] inTvec1,
double[] inRvec2,
double[] inTvec2,
double[] outRvec,
double[] outTvec
);
/**
* Computes the "angular distance" i.e. the difference between two rotations as a single angle
* in degrees.
* @param inRvec1 the first rotation
* @param inRvec2 the second rotation
* @return the angular distance
*/
public static native double angularDistance(
double[] inRvec1,
double[] inRvec2
);
/**
* Computes the "pose centroid" i.e. the pose which is the average of the all the poses in the
* input data arrays between offset*3 and offset*3+count*3.
* @param inRvecs the N*3 array of N rotation vectors
* @param inTvecs the N*3 array of N translation vectors
* @param offset the first pose to be considered
* @param count how many poses to use from the arrays (starting from offset)
* @param outRvec the output rotation
* @param outTvec the output translation
*/
public static native void poseCentroid(
double[] inRvecs,
double[] inTvecs,
int offset,
int count,
double[] outRvec,
double[] outTvec
);
/**
* The pose of the phone is found, but is invalidated by a validity check
*/
public static final int PHONE_POSE_STATUS_INVALID = -1;
/**
* No pose of the phone is available yet
*/
public static final int PHONE_POSE_STATUS_UNAVAILABLE = 0;
/**
* The pose of the phone is new and valid
*/
public static final int PHONE_POSE_STATUS_UPDATED = 1;
/**
* No new pose of the phone is available, the indicated pose is the last known
*/
public static final int PHONE_POSE_STATUS_LAST_KNOWN = 2;
/**
* Renders a 2D map on the mat. It shows the poses of all found markers, the pose of the camera
* (if available) and its status, the track of previous positions of the camera.
*
* @param markerLength the side length of all the markers
* @param markerRVects the rotation vector of the pose of the known markers
* @param markerTVects the translation vector of the pose of the known markers
* @param fixedMarkerCount the number of known markers to be rendered
* @param mapCameraPoseRotation the orientation in the world of the virtual map camera
* @param mapCameraPoseTranslation the position in the world of the virtual map camera
* @param mapCameraFovX the angle in radians which defines the horizontal Field Of View of the
* virtual map camera
* @param mapCameraFovY the angle in radians which defines the vertical Field Of View of the
* virtual map camera
* @param mapCameraApertureX the "sensor" width of the virtual map camera
* @param mapCameraApertureY the "sensor" heigth of the virtual map camera
* @param phonePoseStatus the current status code of the phone pose
* @param phonePositionRvect the rotation vector of the phone pose
* @param phonePositionTvect the translation vector of the phone pose
* @param previousPhonePosesCount the count of previous phone poses
* @param previousPhonePosesRvects the 3*N array for the rotation vectors of the previous poses
* @param previousPhonePosesTvects the 3*N array for the translation vectors of the previous poses
* @param mapCameraPixelsX the number of pixels in the resulting mat which will be used to
* render the mat when not in fullscreen mode
* @param mapCameraPixelsY the number of pixels in the resulting mat which will be used to
* render the mat when not in fullscreen mode
* @param mapTopLeftCornerX the x coordinate in the mat of the top-left corner of the map
* @param mapTopLeftCornerY the x coordinate in the mat of the top-left corner of the map
* @param resultMatAddr the mat on which the map will be rendered
* @param fullScreenMode whether the map should be rendered in fullscreen mode or not
*/
public static native void renderMap(
double markerLength,
double[] markerRVects,
double[] markerTVects,
int fixedMarkerCount,
double[] mapCameraPoseRotation,
double[] mapCameraPoseTranslation,
double mapCameraFovX,
double mapCameraFovY,
double mapCameraApertureX,
double mapCameraApertureY,
int phonePoseStatus,
double[] phonePositionRvect,
double[] phonePositionTvect,
int previousPhonePosesCount,
double[] previousPhonePosesRvects,
double[] previousPhonePosesTvects,
int mapCameraPixelsX,
int mapCameraPixelsY,
int mapTopLeftCornerX,
int mapTopLeftCornerY,
long resultMatAddr,
boolean fullScreenMode
);
}
|
Java
|
UTF-8
| 4,348 | 2.71875 | 3 |
[] |
no_license
|
/**
*
*/
package com.doughalperin.scheduler;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Tests Track class
*
*@see Track
*/
public class TrackTest {
final BlockFormat[][] passing = {
{
new BlockFormat("Morning Sessions", new TimeOffset(2, 9, 0), true, true, 180, 180),
new BlockFormat("Lunasd asch", new TimeOffset(3, 12, 0), false, true, 60, 60),
new BlockFormat("Afternoon Sessions", new TimeOffset(4, 13, 0), true, true, 180, 240)
},
{
new BlockFormat("Morning Sessions", new TimeOffset(0, 9, 0), true, true,180,180),
new BlockFormat("Lunch", new TimeOffset(0, 12, 0), false, true, 60, 60),
new BlockFormat("Afternoon Sessions", new TimeOffset(0, 13, 0), true, true,180, 240),
new BlockFormat("Networking Event", new TimeOffset(0, 16, 0), false, false, 180, 300)
}
};
final BlockFormat[][] failing = {
{
new BlockFormat("Morning Sessions", new TimeOffset(0, 9, 0), true, true, 180, 180),
null
},
{
new BlockFormat("Morning Sessions", new TimeOffset(0, 9, 0), true, true,180,180),
new BlockFormat("Lunch", new TimeOffset(0, 4, 0), false, true, 60, 60)
},
null
};
final String[] passingLabels = {"Track", " ok"};
final String[] failingLabels = {null, " "};
/**
* Test method for {@link com.doughalperin.scheduler.Track#Track(com.doughalperin.scheduler.BlockFormat[])}.
*/
@Test
public void testTrack() {
for (int i = 0; i < passing.length; i++) {
BlockFormat[] c = passing[i];
Track ret = new Track(c);
assertNotNull("passing case#" + i + " returns null", ret);
}
for (int i = 0; i < failing.length; i++) {
BlockFormat[] c = failing[i];
boolean exceptionOccurred = false;
try {
new Track(c);
} catch (IllegalArgumentException e) {
// what we expect
exceptionOccurred = true;
}
assertTrue("Unexpectedly succeeded for case#" + i, exceptionOccurred);
}
}
/**
* Test method for {@link com.doughalperin.scheduler.Track#getLabel()}.
*/
@Test
public void testGetLabel() {
for (int i = 0; i < passing.length; i++) {
BlockFormat[] c = passing[i];
Track t = new Track(c);
String ret = t.getLabel();
assertTrue("passing case#" + i + " not set", ret != null && ret.length() > 0);
}
}
/**
* Test method for {@link com.doughalperin.scheduler.Track#setLabel(java.lang.String)}.
*/
@Test
public void testSetLabel() {
BlockFormat[] c = passing[0];
for (int i = 0; i < passingLabels.length; i++) {
String value = passingLabels[i];
// reset each time
Track t = new Track(c);
t.setLabel(value);
String ret = t.getLabel();
assertTrue("case#" + i + " not equal", value.trim().equals(ret));
}
//now test failed values
for (int i = 0; i < failingLabels.length; i++) {
String value = failingLabels[i];
// reset each time
Track t = new Track(c);
boolean exceptionOccurred = false;
try {
t.setLabel(value);
} catch (IllegalArgumentException e) {
// what we expect
exceptionOccurred = true;
}
assertTrue("Unexpectedly succeeded for case#" + i, exceptionOccurred);
}
}
/**
* Test method for {@link com.doughalperin.scheduler.Track#getOriginalBlocks()}.
*/
@Test
public void testGetOriginalBlocks() {
BlockFormat[] c = passing[0];
Track t = new Track(c);
BlockFormat[] ret = t.getOriginalBlocks();
assertTrue(c == ret);
}
/**
* Test method for {@link com.doughalperin.scheduler.Track#getWorkingBlocks()}.
*/
@Test
public void testGetWorkingBlocks() {
BlockFormat[] c = passing[0];
Track t = new Track(c);
ScheduleBlock[] ret = t.getWorkingBlocks();
assertNotNull(ret);
}
/**
* Test method for {@link com.doughalperin.scheduler.Track#getScheduleBlocks()}.
*/
@Test
public void testGetScheduleBlocks() {
BlockFormat[] c = passing[0];
Track t = new Track(c);
ScheduleBlock[] ret = t.getScheduleBlocks();
assertNotNull(ret);
}
/**
* Test method for {@link com.doughalperin.scheduler.Track#getBlockUsedMinutes()}.
*/
@Test
public void testGetBlockUsedMinutes() {
BlockFormat[] c = passing[0];
Track t = new Track(c);
int[] ret = t.getBlockUsedMinutes();
assertNotNull(ret);
}
}
|
Java
|
UTF-8
| 454 | 2.3125 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.hiabby.flytools.gof.singleton;
/**
* @desc 静态内部类
* @date 2018/09/20
**/
public class HolderSingleton {
private static HolderSingleton singleton = null;
private HolderSingleton() {
}
public static HolderSingleton getSingleton() {
return singletonHolder.singleton;
}
;
private static class singletonHolder {
private static HolderSingleton singleton = new HolderSingleton();
}
}
|
TypeScript
|
UTF-8
| 1,442 | 2.53125 | 3 |
[] |
no_license
|
import {Component, OnInit} from '@angular/core';
import {Task} from '../shared/models/task';
import * as _ from 'lodash';
import {TaskStorageService} from '../shared/services/task-storage.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Mes tâches à faire !';
/**
* creation d'un tableau de tâches
* il contiendera toutes les tâches
* de notre application
* @type {any[]}
*/
tasks: Task[] = [];
/**
* L'utilisateur vient de
* terminer une tache
* @param {Task} task
*/
taskIsDone(task: Task) {
task.status = true;
this.taskStorageService.save(this.tasks);
}
/**
* L'utilisateur vient de supprimer
* une tâche. On la retire du tableau.
* @param {Task} task
*/
removeTask(task: Task) {
_.pullAllWith(this.tasks, [task], _.isEqual);
}
/**
* Cette fonction se déclanche dans
* l'application lorsqu'une nouvelle
* tâche est créee par l'utilisateur
* dans le composant app-add-task.
* @param (task) task
*/
newTask(task: Task) {
this.tasks.push(task);
}
constructor(private taskStorageService: TaskStorageService) {}
ngOnInit(): void {
/**
* Au chargement de l'application,
* je récuper mes tâches dans le localStorage.
*/
this.tasks = this.taskStorageService.getTasks();
}
}
|
C#
|
UTF-8
| 5,109 | 2.78125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Mvc;
using UserTest.Models;
namespace UserTest.Controllers
{
public class PersonController : Controller
{
// GET: Person
public ActionResult Index()
{
return View();
}
#region CRUD methods
public static Guid CreateCustomer(Customer customer)
{
using (EntityContext db = new EntityContext())
{
customer.Id = Guid.NewGuid();
byte[] salt = CreateSalt();
customer.Salt = System.Text.Encoding.Default.GetString(salt);
byte[] password = System.Text.ASCIIEncoding.Default.GetBytes(customer.Password);
byte[] stringpassword = GenerateSaltedHash(password, salt);
customer.Password = System.Text.Encoding.Default.GetString(stringpassword);
db.Persons.Add(customer);
db.SaveChanges();
return customer.Id;
}
}
public static Guid CreateEmployee(Employee employee)
{
using (EntityContext db = new EntityContext())
{
employee.Id = Guid.NewGuid();
byte[] salt = CreateSalt();
employee.Salt = System.Text.Encoding.Default.GetString(salt);
byte[] password = System.Text.ASCIIEncoding.Default.GetBytes(employee.Password);
byte[] stringpassword = GenerateSaltedHash(password, salt);
employee.Password = System.Text.Encoding.Default.GetString(stringpassword);
db.Persons.Add(employee);
db.SaveChanges();
return employee.Id;
}
}
public static Customer FindCustomer(Guid id)
{
using (EntityContext db = new EntityContext())
{
return db.Persons.Find(id) as Customer;
}
}
public static Employee FindEmployee(Guid id)
{
using (EntityContext db = new EntityContext())
{
return db.Persons.Find(id) as Employee;
}
}
public static bool DeleteEmployee(Employee employee)
{
using (EntityContext db = new EntityContext())
{
db.Entry(employee).State = EntityState.Deleted;
return db.SaveChanges() == 1;
}
}
public static bool DeleteCustomer(Customer customer)
{
using (EntityContext db = new EntityContext())
{
db.Entry(customer).State = EntityState.Deleted;
return db.SaveChanges() == 1;
}
}
#endregion
#region Salt and hashing
public static byte[] CreateSalt()
{
//Generate a cryptographic random number.
byte[] random = Guid.NewGuid().ToByteArray();
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(random);
return random;
}
public static byte[] GenerateSaltedHash(byte[] password, byte[] salt)
{
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextWithSaltBytes =
new byte[password.Length + salt.Length];
for (int i = 0; i < password.Length; i++)
{
plainTextWithSaltBytes[i] = password[i];
}
for (int i = 0; i < salt.Length; i++)
{
plainTextWithSaltBytes[password.Length + i] = salt[i];
}
return algorithm.ComputeHash(plainTextWithSaltBytes);
}
//metode til at checke om password der er givet også er identisk til det hashede password som er i databasen
public static bool ComparePW(string checkpassword, string email)
{
using (EntityContext db = new EntityContext())
{
Person person = db.Persons.FirstOrDefault(x => x.Email == email);
string personSalt = person.Salt;
string personPassword = person.Password;
byte[] checkpasswordbyte = System.Text.ASCIIEncoding.Default.GetBytes(checkpassword);
byte[] checkPersonSalt = System.Text.ASCIIEncoding.Default.GetBytes(personSalt);
byte[] compareHash = GenerateSaltedHash(checkpasswordbyte, checkPersonSalt);
string compareHashString = System.Text.Encoding.Default.GetString(compareHash);
if (compareHashString == personPassword)
{
return true;
}
else
{
return false;
}
}
}
#endregion
}
}
|
JavaScript
|
UTF-8
| 2,941 | 2.953125 | 3 |
[] |
no_license
|
// Add smooth scrolling to all links
const smoothScroll = function () {
$("a").on('click', function (event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
const hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function () {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
}
// variable for page
const page = $("html, body");
//variable for height of window minus nav
let navHeight = $(window).height() - 50;
const line1 = document.getElementById("line1");
const line2 = document.getElementById("line2");
const line3 = document.getElementById("line3");
const lineAnimation = function() {
$('.menuLink').click(function () {
$(".toggle").toggle("slide right");
line1.classList.toggle("change");
line2.classList.toggle("change");
line3.classList.toggle("change");
})
};
const navSlide = function() {
//sticky nav for menu
$(window).bind('scroll', function () {
//if window height is larger than the height minus the menu
if ($(window).scrollTop() > navHeight) {
$('.menuContainer').addClass('sticky');
$(".click").removeClass("mobileContainer");
$(".menuToggle").addClass("lines");
$(".menuToggle").removeClass("menuLines");
} else {
$('.menuContainer').removeClass('sticky');
$(".click").addClass("mobileContainer");
$(".menuToggle").addClass("menuLines");
$(".menuToggle").removeClass("lines");
}
})
}
//grab the past projects grid
const $container = $('.grid');
//make a variable of the settings to call later
const $grid = $($container).isotope({
// options
itemSelector: '.gridItem',
layoutMode: 'masonry',
});
// layout Isotope again after all images have loaded
$grid.imagesLoaded().progress(function () {
$grid.isotope('layout');
});
// filter items on button click
$('.filter-button-group button').on('click', function () {
if( $(this).hasClass('checked') && $(this).hasClass('filter')) {
$(this).removeClass('checked');
$container.isotope({ filter: '*'})
$('.all').addClass('checked');
} else {
$('.filter-button-group button').removeClass('checked');
const filterValue = $(this).attr('data-filter');
$grid.isotope({ filter: filterValue });
$(this).addClass('checked')
}
});
//header slide
const headerSlide = function() {
$(".header").animate({
left: "+=115%",
}, {
duration: 2000
});
}
const init = function() {
navSlide();
headerSlide();
lineAnimation();
smoothScroll();
accessibleNav();
}
//document ready
$(document).ready(function(){
init();
})
|
Java
|
UTF-8
| 1,698 | 2.328125 | 2 |
[] |
no_license
|
package com.yuniss.remotecarcontrol.model;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
@Entity(tableName = "cars")
public class Car {
public Car() {
}
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "title")
private String title;
@ColumnInfo(name = "phone")
private String phone;
@ColumnInfo(name = "user_id")
private int user_id;
@ColumnInfo(name = "password")
private String password;
@Ignore
public Car(String title, String phone, int user_id, String password) {
this.title = title;
this.phone = phone;
this.user_id = user_id;
this.password = password;
}
@Ignore
public Car(int uid, String title, String phone, int user_id, String password) {
this.id = uid;
this.title = title;
this.phone = phone;
this.user_id = user_id;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int uid) {
this.id = uid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
Java
|
UTF-8
| 1,033 | 2.4375 | 2 |
[] |
no_license
|
package com.googlecode.propidle.client.loaders;
import static com.googlecode.propidle.properties.Properties.compose;
import com.googlecode.totallylazy.Callables;
import com.googlecode.totallylazy.Sequence;
import static com.googlecode.totallylazy.Sequences.sequence;
import java.util.Properties;
import java.util.concurrent.Callable;
public class ComposeProperties implements Callable<Properties> {
private final Sequence<Callable<Properties>> properties;
public static ComposeProperties composeProperties(Callable<Properties>... properties) {
return composeProperties(sequence(properties));
}
public static ComposeProperties composeProperties(Iterable<Callable<Properties>> properties) {
return new ComposeProperties(properties);
}
protected ComposeProperties(Iterable<Callable<Properties>> properties) {
this.properties = sequence(properties);
}
public Properties call() throws Exception {
return compose(properties.map(Callables.<Properties>call()));
}
}
|
Java
|
UTF-8
| 879 | 1.875 | 2 |
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
package org.crosswalk.engine;
import android.util.Log;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import org.apache.cordova.ResourceLoader;
import org.xwalk.core.XWalkView;
public class OfflineXWalkCordovaResourceClient extends XWalkCordovaResourceClient {
static final String TAG = "OfflineXWalkCordovaResourceClient";
public OfflineXWalkCordovaResourceClient(XWalkWebViewEngine parentEngine) {
super(parentEngine);
}
@Override
public WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) {
WebResourceResponse result = ResourceLoader.load(this.parentEngine.cordova, url);
if (result == null) {
result = super.shouldInterceptLoadRequest(view, url);
return result;
} else {
return result;
}
}
}
|
Java
|
UTF-8
| 2,389 | 1.992188 | 2 |
[] |
no_license
|
package com.viptrip.wetrip.controller;
import etuf.v1_0.common.Common;
import etuf.v1_0.common.Constant;
import etuf.v1_0.model.base.output.OutputResult;
import etuf.v1_0.model.base.output.OutputSimpleResult;
import com.viptrip.base.common.support.ApplicationContextHelper;
import com.viptrip.util.RegUtil;
import com.viptrip.wetrip.TicketClient;
import com.viptrip.wetrip.model.Request_H5UserLogin;
import com.viptrip.wetrip.model.Response_H5UserLogin;
import com.viptrip.wetrip.model.base.UserInfo4Bind;
import com.viptrip.wetrip.service.impl.H5UserLoginServiceImpl;
public class H5UserLogin extends TicketClient<Request_H5UserLogin, Response_H5UserLogin>{
@Override
protected OutputSimpleResult DataValid(Request_H5UserLogin ul) {
OutputSimpleResult osr=new OutputSimpleResult();
//获取service层实例
H5UserLoginServiceImpl userLoginSer = ApplicationContextHelper.getInstance().getBean(H5UserLoginServiceImpl.class);
if(ul.data!=null){
if(ul.data.platformId!=null){
if(userLoginSer.checkHasPlatformId(ul.data.platformId)){
if(!Common.IsNullOrEmpty(ul.data.user.uid)){
if(!Common.IsNullOrEmpty(ul.data.user.name)){
if(!Common.IsNullOrEmpty(ul.data.user.mobile)){
if(RegUtil.isValidMobile(ul.data.user.mobile)){
osr.code=Constant.Code_Succeed;
}else osr.result="无效的手机号码,请确认后重试。";
}else osr.result="手机号码为空。";
}else osr.result="用户姓名为空。";
}else osr.result="用户平台的id为空。";
}else osr.result="平台信息错误!";
}else osr.result="平台id为空。";
}else osr.result="请求数据为null,请确认后重试。";
return osr;
}
@Override
protected OutputResult<Response_H5UserLogin, String> DoBusiness(
Request_H5UserLogin arg0) {
//获取service层实例
H5UserLoginServiceImpl userLoginSer = ApplicationContextHelper.getInstance().getBean(H5UserLoginServiceImpl.class);
OutputResult<Response_H5UserLogin, String> or = new OutputResult<Response_H5UserLogin, String>();
Response_H5UserLogin resultObj = new Response_H5UserLogin();
//根据合作方提供的信息,注册或者登录用户账户前的绑定操作
UserInfo4Bind userInfo = userLoginSer.doUserLoginMap(arg0.data,or);//如果未关联,添加
resultObj.data=userInfo;
or.setResultObj(resultObj);
return or;
}
}
|
JavaScript
|
UTF-8
| 340 | 2.5625 | 3 |
[] |
no_license
|
/**
* - đặt các export name vào trong dấu ngoặc nhọn {} đúng tên đã đặt bên export.
* - có thể đặt lại định danh khác khi import.
*
*/
import {PI, product as sanPham, tongHaiSo, student} from './module-export-name.js';
console.log(PI);
console.log(sanPham);
console.log(tongHaiSo(2,3));
new student();
|
C
|
UTF-8
| 249 | 2.703125 | 3 |
[] |
no_license
|
#include <stdio.h>
int main()
{
int khaddo[5] = { 300, 1500, 600, 1000, 150 };
int a, ans=0, i;
for (i = 0; i < 5; ++i)
scanf("%d", &a), ans += a * khaddo[i];
ans += 225;
printf("%d\n", ans);
return 0;
}
|
Java
|
UTF-8
| 495 | 2.40625 | 2 |
[
"NCSA"
] |
permissive
|
/*
* - 04/2009: Class created by Nicolas Richasse
*/
package net.nlanr.jperf.core;
public enum IperfPacketSizeUnit
{
BITS("b", "Bits"), BYTES("B", "Bytes"), KBITS("k", "KBits"), KBYTES("K", "KBytes");
private String shortcut;
private String description;
IperfPacketSizeUnit(String shortcut, String description)
{
this.shortcut = shortcut;
this.description = description;
}
public String getShortcut()
{
return shortcut;
}
public String toString()
{
return description;
}
}
|
C
|
UTF-8
| 8,174 | 3.03125 | 3 |
[] |
no_license
|
#include "ast.h"
TreeNode* CreateTreeNode(Lex_Unit_Cont l_cont, char* value, int lineno) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->u_type = lex_unit;
node->s_cont = 0;
node->l_cont = l_cont;
node->childnum = 0;
node->child = NULL;
node->lineno = lineno;
switch (node->l_cont) {
case L_ID: {
node->id_name = (char*)malloc(strlen(value));
strcpy(node->id_name, value);
break;
}
case L_TYPE: {
node->type_name = (char*)malloc(strlen(value));
strcpy(node->type_name, value);
break;
}
case L_INT: {
node->int_value = atoi(value);
break;
}
case L_STRING: {
node->string_value = (char*)malloc(strlen(value));
strcpy(node->string_value, value);
break;
}
case L_ANYTHINGELSE: {
node->anything_else_name = (char*)malloc(strlen(value));
strcpy(node->anything_else_name, value);
break;
}
}
return node;
}
TreeNode* GenerateTreeNode(Syn_Unit_Cont s_cont, char* syn_name, int lineno,
int childnum, ...) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->u_type = syn_unit;
node->s_cont = s_cont;
node->l_cont = 0;
node->childnum = childnum;
node->lineno = lineno;
va_list args;
va_start(args, childnum);
node->child = (TreeNode**)malloc(sizeof(TreeNode*) * abs(childnum));
int count = 0;
for (; count < abs(childnum); count++) {
TreeNode* temp = va_arg(args, TreeNode*);
node->child[count] = temp;
}
node->syn_name = syn_name;
return node;
}
void DisplayTree(TreeNode* Head, int curdeepth) {
PrintBlank(curdeepth);
// if (Head->u_type == syn_unit)
// printf("%s (%d)\n", Head->syn_name, Head->lineno);
// else {
// if (Head->l_cont == L_ID)
// printf("ID: %s\n", Head->id_name);
// else if (Head->l_cont == L_TYPE)
// printf("TYPE: %s\n", Head->type_name);
// else if (Head->l_cont == L_INT)
// printf("INT: %d\n", Head->int_value);
// else if (Head->l_cont == L_STRING)
// printf("STRING: %d\n", Head->string_value);
// else
// printf("%s\n", Head->anything_else_name);
// }
printf("%d)", curdeepth);
shownode(Head);
if (Head->childnum < 0) return;
if (Head->childnum > 0 && Head->child[0] != NULL) {
int i;
for (i = 0; i < Head->childnum; i++) {
DisplayTree(Head->child[i], curdeepth + 1);
}
}
}
void PrintBlank(int deepth) {
int temp = 0;
for (; temp < deepth; temp++) printf(" ");
}
const char* unit_type_arr[] = {"", "lex_unit", "syn_unit"};
const char* lex_unit_arr[] = {"", "L_ID", "L_TYPE",
"L_INT", "L_STRING", "L_ANYTHINGELSE"};
const char* syn_unit_arr[] = {"",
"S_empty",
"S_Program",
"S_VarDecl",
"S_Type",
"S_FnDecl",
"S_Parameters",
"S_FormalsList",
"S_FormalDecl",
"S_Block",
"S_DeclList",
"S_StmtList",
"S_Stmt",
"S_Exp",
"S_Atom",
"S_FnCallExpr",
"S_FnCallStmt",
"S_ActualList",
"S_SubscriptExpr",
"S_Id"};
void shownode(TreeNode* node) {
printf("%s ", unit_type_arr[node->u_type]);
printf("%s ", lex_unit_arr[node->l_cont]);
printf("%s ", syn_unit_arr[node->s_cont]);
printf("line %d ", node->lineno);
if (node->u_type == 2) printf("%s ", node->syn_name);
// if (node->u_type == 1) {
// printf("%s ", node->type_name);
// printf("%s \n", node->anything_else_name);
// }
printf("\n");
}
void shownodeln(TreeNode* node) {
printf("%d\n", node->u_type);
printf("%d\n", node->s_cont);
printf("%d\n", node->l_cont);
printf("%d\n", node->lineno);
}
void SaveTreeToFile(TreeNode* Head, int curdeepth, FILE* file) {
AppendBlank(curdeepth, file);
if (Head->u_type == syn_unit)
fprintf(file, "%s (%d)\n", Head->syn_name, Head->lineno);
else {
if (Head->l_cont == L_ID)
fprintf(file, "ID: %s\n", Head->id_name);
else if (Head->l_cont == L_TYPE)
fprintf(file, "TYPE: %s\n", Head->type_name);
else if (Head->l_cont == L_INT)
fprintf(file, "INT: %d\n", Head->int_value);
else if (Head->l_cont == L_STRING)
fprintf(file, "STRING: %d\n", Head->string_value);
else
fprintf(file, "%s\n", Head->anything_else_name);
}
if (Head->childnum < 0) return;
if (Head->childnum > 0 && Head->child[0] != NULL) {
int i;
for (i = 0; i < Head->childnum; i++) {
SaveTreeToFile(Head->child[i], curdeepth + 1, file);
}
}
}
void AppendBlank(int deepth, FILE* file) {
int temp = 0;
for (; temp < deepth; temp++) fprintf(file, " ");
}
void FreeTree(TreeNode* Head) {
if (Head->childnum < 0) {
free(Head);
return;
};
if (Head->childnum > 0 && Head->child[0] != NULL) {
int i;
for (i = 0; i < Head->childnum; i++) {
FreeTree(Head->child[i]);
}
}
}
TreeNode** idNodes;
int indexIdNodes;
int CountIdentifiers(TreeNode* Head, TreeNode* previousNode,
TreeNode* prePreviousNode, int level) {
int counter = 0;
if (Head->childnum > 0 && Head->child[0] != NULL) {
int i;
for (i = 0; i < Head->childnum; i++) {
counter += CountIdentifiers(Head->child[i], Head, previousNode, ++level);
}
}
// if (Head->l_cont == L_ID &&
// strcmp(prePreviousNode->syn_name, "VarDecl") == 0) {
// printf("%s %s %d ", prePreviousNode->syn_name, Head->syn_name, level);
// printf("%d\n", Head->l_cont);
// }
if (Head->l_cont == L_ID && strcmp(prePreviousNode->syn_name, "VarDecl") == 0)
return ++counter;
return counter;
}
void GetIdentifiers(TreeNode* Head, TreeNode* previousNode,
TreeNode* prePreviousNode) {
if (Head->childnum > 0 && Head->child[0] != NULL) {
int i;
for (i = 0; i < Head->childnum; i++) {
GetIdentifiers(Head->child[i], Head, previousNode);
}
}
if (Head->l_cont == L_ID &&
strcmp(prePreviousNode->syn_name, "VarDecl") == 0) {
idNodes[indexIdNodes] = Head;
indexIdNodes++;
}
}
// void CheckErrors(TreeNode** nodeList, int size) {
// int i, j;
// for (i = 0; i < size; i++) {
// for (j = 0; j < size; j++) {
// if (i != j && strcmp(nodeList[i]->id_name, nodeList[j]->id_name) == 0)
// {
// printf("Same identifier used - '%s' lines:%d, %d \n",
// idNodes[i]->id_name, idNodes[i]->lineno, idNodes[j]->lineno);
// break;
// }
// }
// }
// }
void CheckErrors(TreeNode** nodeList, int size, FILE* f) {
int i, j;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
if (i != j && strcmp(nodeList[i]->id_name, nodeList[j]->id_name) == 0) {
fprintf(f, "Same identifier used - '%s' lines:%d, %d \n",
idNodes[i]->id_name, idNodes[i]->lineno, idNodes[j]->lineno);
break;
}
}
}
}
// void AnalyzeTree(TreeNode* Head) {
// int identifiers = CountIdentifiers(Head);
// idNodes = (TreeNode**)malloc(sizeof(TreeNode*) * identifiers);
// indexIdNodes = 0;
// GetIdentifiers(Head);
// CheckErrors(idNodes, identifiers);
// free(idNodes);
// }
void AnalyzeTree(TreeNode* Head, FILE* f) {
int identifiers = CountIdentifiers(Head, NULL, NULL, 0);
printf("%d identifiers \n", identifiers);
idNodes = (TreeNode**)malloc(sizeof(TreeNode*) * identifiers);
indexIdNodes = 0;
GetIdentifiers(Head, NULL, NULL);
CheckErrors(idNodes, identifiers, f);
free(idNodes);
}
// de schimbat
// in analyzetree doar extragem nodurile din parser si le punem in alt tree (
// asta e symbol table) dupa trebuie sa facem ce zice pe site aka error
// checking, sa vedem ca nu exista duplicate, sa vedem ca nu sunt variabile
// nefolosite , etc
|
Java
|
UTF-8
| 4,713 | 2.515625 | 3 |
[] |
no_license
|
package Modelos;
import java.time.LocalDate;
/**
*
* @author Grupo2
*/
public class Persona implements Comparable<Persona> {
private int idPersona = -1;
private Patologia patologia;
private int dni;
private String nombre;
private String apellido;
private String email;
private double peso;
private double altura;
private boolean trabajo;
private String celular;
private LocalDate fechaDeNacimiento;
private String ciudad;
private String departamento;
public Persona(int idPersona, Patologia patologia, int dni, String nombre, String apellido, double peso, double altura, String email, boolean trabajo, String celular, LocalDate fechaDeNacimiento, String ciudad, String departamento) {
this.idPersona = idPersona;
this.patologia = patologia;
this.dni = dni;
this.nombre = nombre;
this.apellido = apellido;
this.peso = peso;
this.altura = altura;
this.email = email;
this.trabajo = trabajo;
this.celular = celular;
this.fechaDeNacimiento = fechaDeNacimiento;
this.ciudad = ciudad;
this.departamento = departamento;
}
public Persona(Patologia patologia, int dni, String nombre, String apellido, double peso, double altura, String email, boolean trabajo, String celular, LocalDate fechaDeNacimiento, String ciudad, String departamento) {
this.patologia = patologia;
this.dni = dni;
this.nombre = nombre;
this.apellido = apellido;
this.peso = peso;
this.altura = altura;
this.email = email;
this.trabajo = trabajo;
this.celular = celular;
this.fechaDeNacimiento = fechaDeNacimiento;
this.ciudad = ciudad;
this.departamento = departamento;
}
public Persona() {
}
public int getIdPersona() {
return idPersona;
}
public Patologia getPatologia() {
return patologia;
}
public int getDni() {
return dni;
}
public String getNombre() {
return nombre;
}
public String getApellido() {
return apellido;
}
public double getPeso() {
return peso;
}
public double getAltura() {
return altura;
}
public String getEmail() {
return email;
}
public boolean isTrabajo() {
return trabajo;
}
public String getCelular() {
return celular;
}
public LocalDate getFechaDeNacimiento() {
return fechaDeNacimiento;
}
public String getCiudad() {
return ciudad;
}
public String getDepartamento() {
return departamento;
}
public void setIdPersona(int idPersona) {
this.idPersona = idPersona;
}
public void setPatologia(Patologia patologia) {
this.patologia = patologia;
}
public void setDni(int dni) {
this.dni = dni;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public void setPeso(double peso) {
this.peso = peso;
}
public void setAltura(double altura) {
this.altura = altura;
}
public void setEmail(String email) {
this.email = email;
}
public void setTrabajo(boolean trabajo) {
this.trabajo = trabajo;
}
public void setCelular(String celular) {
this.celular = celular;
}
public void setFechaDeNacimiento(LocalDate fechaDeNacimiento) {
this.fechaDeNacimiento = fechaDeNacimiento;
}
public void setCiudad(String ciudad) {
this.ciudad = ciudad;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
@Override
public String toString() {
return nombre + " " + apellido + " / DNI: " + dni;
}
@Override
public boolean equals(Object obj) {
final Persona other = (Persona) obj;
if (patologia == null || other.patologia == null) {
return ((dni == other.dni) && (nombre.equalsIgnoreCase(other.nombre))
&& (apellido.equalsIgnoreCase(other.apellido))
&& (fechaDeNacimiento.equals(other.fechaDeNacimiento)));
} else {
return ((patologia.equals(other.patologia)) && (dni == other.dni) && (nombre.equalsIgnoreCase(other.nombre))
&& (apellido.equalsIgnoreCase(other.apellido))
&& (fechaDeNacimiento.equals(other.fechaDeNacimiento)));
}
}
@Override
public int compareTo(Persona persona) {
return dni - persona.dni;
}
}
|
PHP
|
UTF-8
| 2,477 | 2.953125 | 3 |
[
"MIT"
] |
permissive
|
<?php
session_start();
//cek user login
if (!isset($_SESSION['userid'])) {
header("location:index.php");
}
//cekleveladmin
if ($_SESSION['level'] != "admin") {
die("ANDA BUKAN ADMIN");
}
?>
<?php
error_reporting(E_ALL ^ (E_NOTICE));
$batas = 20;
$halaman = $_GET['halaman'];
if (empty($halaman)) {
$posisi = 0;
$halaman = 1;
}else{
$posisi = ($halaman - 1) * $batas;
}
$konek = mysqli_connect("localhost", "root", "", "supermarket");
if (isset($_GET['cari'])) {
$q = $_GET['s'];
$tampil = "SELECT * FROM barang WHERE nama_barang LIKE '%$q%' OR jenis_barang LIKE '%$q%' OR jumlah_barang LIKE '%$q%' OR harga LIKE '%$q%' ORDER BY nama_barang LIMIT $posisi, $batas";
}else{
//query menampilkan data
$tampil = "SELECT * FROM barang LIMIT $posisi, $batas";
}
$hasil = mysqli_query($konek,$tampil);
$jmlhasil = mysqli_num_rows($hasil);
?>
<h3>Data Supermarket Online</h3>
<hr>
<form action="index.php" method="GET">
<input type="text" name="s">
<input type="submit" value="CARI" name="cari">
</form>
<hr>
<a href="inputan.php">Create Barang</a>
<table border="1">
<tr>
<th>kode barang</th>
<th>nama barang</th>
<th>jenis barang</th>
<th>jumlah barang</th>
<th>harga</th>
<th>aksi</th>
</tr>
<?php
if ($jmlhasil < 1) {
echo "<tr>";
echo "<td colspan='5'>data yang ada cari tidak ada</td>";
echo "</tr>";
}else{
//penomoran
$kode_barang = $posisi + 1;
//tampil nama,jenis,jumlah,tanggal,keterangan barang
while($data=mysqli_fetch_array($hasil)){
echo "<tr>";
echo "<td>$data[kode_barang]</td>";
echo "<td>$data[nama_barang]</td>";;
echo "<td>$data[jenis_barang]</td>";
echo "<td>$data[jumlah_barang]</td>";
echo "<td>$data[harga]</td>";
echo "<td><a href='inputan.php?kode_barang=$data[kode_barang]'>create</a> |
<a href='hapusbarang.php?kode_barang=$data[kode_barang]'>hapus</a> |
<a href='editbarang.php?kode_barang=$data[kode_barang]'>edit</a> |
<a href='detailbarang.php?kode_barang=$data[kode_barang]'>detail</a></td>";
echo "</tr>";
$data++;
}
}
?>
</table>
<?php
//untuk pagging
$tampil2 = "SELECT * FROM barang";
$hasil2 = mysqli_query($konek, $tampil2);
$jmldata = mysqli_num_rows($hasil2);
$jmlhalaman = ceil($jmldata / $batas);
echo " jumlah data : $jmldata <br>";
for ($i=1; $i <= $jmlhalaman; $i++) {
if ($i != $halaman) {
echo "<a href=$_SERVER[PHP_SELF]?halaman=$i> $i </a>";
}else{
echo " <b> $i </b>";
}
}
?>
<a href="log.php?op=out">LOG OUT</a>
</body>
</html>
|
C++
|
UTF-8
| 3,238 | 2.953125 | 3 |
[
"Apache-2.0"
] |
permissive
|
#include "agd_record_reader.h"
namespace tensorflow {
using namespace errors;
using namespace std;
using namespace format;
// TODO we should probably do some more checks on this
AGDRecordReader::AGDRecordReader(ResourceContainer<Data>* resource, size_t num_records) :
num_records_(num_records) {
auto idx_offset = num_records * sizeof(RelativeIndex);
auto base_data = resource->get()->data();
index_ = reinterpret_cast<const RelativeIndex*>(base_data);
cur_data_ = data_ = base_data + idx_offset;
InitializeIndex();
}
AGDRecordReader::AGDRecordReader(const char* resource, size_t num_records) :
num_records_(num_records) {
auto idx_offset = num_records * sizeof(RelativeIndex);
auto base_data = resource;
index_ = reinterpret_cast<const RelativeIndex*>(base_data);
cur_data_ = data_ = base_data + idx_offset;
InitializeIndex();
}
AGDRecordReader AGDRecordReader::fromUncompressed(ResourceContainer<Data>* resource, bool *success) {
const char* a = nullptr;
auto d = resource->get();
auto d_sz = d->size();
auto d_data = d->data();
if (d_sz < sizeof(FileHeader)) {
LOG(ERROR) << "Received a chunk with less than " << sizeof(FileHeader) << " bytes needed for the header";
*success = false;
return AGDRecordReader(a, 0);
}
auto header = reinterpret_cast<const FileHeader*>(d_data);
int64_t num_records = header->last_ordinal - header->first_ordinal;
if (num_records < 1) {
LOG(ERROR) << "Receive a chunk with " << num_records << " records";
*success = false;
return AGDRecordReader(a, 0);
}
size_t minimum_index_size = (d_sz - sizeof(FileHeader)) * sizeof(RelativeIndex);
if (minimum_index_size < num_records) {
LOG(ERROR) << "Received invalid chunk. Header specifices " << num_records << " records, but payload is only " << minimum_index_size << " bytes";
*success = false;
return AGDRecordReader(a, 0);
}
*success = true;
return AGDRecordReader(d_data + sizeof(FileHeader), num_records);
}
void AGDRecordReader::InitializeIndex() {
absolute_index_.clear();
size_t current = 0;
for (size_t i = 0; i < num_records_; ++i) {
absolute_index_.push_back(current);
current += index_[i];
}
}
void AGDRecordReader::Reset() {
cur_data_ = data_;
cur_record_ = 0;
}
Status AGDRecordReader::PeekNextRecord(const char** data, size_t* size) {
if (cur_record_ < num_records_) {
*size = (size_t) index_[cur_record_];
*data = cur_data_;
} else {
return ResourceExhausted("agd record container exhausted");
}
return Status::OK();
}
Status AGDRecordReader::GetNextRecord(const char** data, size_t* size) {
auto s = PeekNextRecord(data, size);
if (s.ok()) {
cur_data_ += index_[cur_record_++];
}
return s;
}
Status AGDRecordReader::GetRecordAt(size_t index, const char** data, size_t* size) {
if (index < num_records_) {
*size = (size_t) index_[index];
*data = data_ + absolute_index_[index];
} else {
return OutOfRange("agd record random access out of range");
}
return Status::OK();
}
} // namespace tensorflow {
|
Python
|
UTF-8
| 898 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
import sys
import socket
import time
# target_cmd = str(sys.argv[3]).lower()
server_address = (sys.argv[1], int(sys.argv[2]))
num_times = 1000
curri = 0
start = time.time()
while curri < num_times:
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# print "Starting to connect."
sock.connect(server_address)
# print "Trying to send:" + target_cmd
sock.sendall("on")
#print "Closing connection."
sock.recv(1024)
sock.close()
time.sleep(0.25)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# print "Starting to connect."
sock.connect(server_address)
# print "Trying to send:" + target_cmd
sock.sendall("off")
sock.recv(1024)
#print "Closing connection."
sock.close()
time.sleep(0.25)
curri += 1
end = time.time()
print "Total time for 1000 blinks:" + str(end-start)
|
Java
|
UTF-8
| 4,938 | 2.625 | 3 |
[] |
no_license
|
/*Notice: this program can only sort all the 7-character words by their frequency, but cant pick top 100s.
You may use command bin/hadoop fs -cat /output/part-r-00000 | head n100 to get the corrrect result.
I am still working on the code. */
/*Notice2: If you want to compile the code. Please use the command"javac -cp hadoop-1.0.3/hadoop-core
-1.0.3.jar:hadoop-1.0.3/lib/commons-cli-1.2.jar WordCount3.java"*/
import java.io.IOException;
import java.util.Random;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.map.InverseMapper;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class WordCount3 {
public static class TokenizerMapper extends
Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
String nextWord=tokenizer.nextToken();
if (nextWord.length() == 7) {
word.set(nextWord);
context.write(word, one);
}
}
}
}
public static class IntSumReducer extends
Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values,
Context context) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
private static class IntWritableDecreasingComparator extends IntWritable.Comparator {
public int compare(WritableComparable a, WritableComparable b) {
return -super.compare(a, b);
}
public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
return -super.compare(b1, s1, l1, b2, s2, l2);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
Path tempDir = new Path("wordcount-temp-" + Integer.toString(
new Random().nextInt(Integer.MAX_VALUE))); //temporary directory
Job job = new Job(conf, "word count");
job.setJarByClass(WordCount3.class);
try{
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, tempDir);
job.setOutputFormatClass(SequenceFileOutputFormat.class); //exchange key and value to sort
if(job.waitForCompletion(true))
{
Job sortJob = new Job(conf, "sort");
sortJob.setJarByClass(WordCount3.class);
FileInputFormat.addInputPath(sortJob, tempDir);
sortJob.setInputFormatClass(SequenceFileInputFormat.class);
sortJob.setMapperClass(InverseMapper.class);
sortJob.setNumReduceTasks(1);
FileOutputFormat.setOutputPath(sortJob, new Path(otherArgs[1]));
sortJob.setOutputKeyClass(IntWritable.class);
sortJob.setOutputValueClass(Text.class);
sortJob.setSortComparatorClass(IntWritableDecreasingComparator.class);
System.exit(sortJob.waitForCompletion(true) ? 0 : 1);
}
}finally{
FileSystem.get(conf).deleteOnExit(tempDir);
}
}
}
|
Java
|
UTF-8
| 1,332 | 2.1875 | 2 |
[] |
no_license
|
package kz.regto.json;
import android.os.AsyncTask;
import android.os.SystemClock;
import kz.regto.database.d_balance;
public class SupportBalance extends AsyncTask<String, Balance, Balance> {
Network ntw = new Network();
int currentBalance=0;
int currentID = 0;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void onProgressUpdate(Balance... progress) {
currentBalance = progress[0].getBalance();
currentID = progress[0].getId_balance();
}
protected void onPostExecute(Balance... result) {
}
//Выполняем бесконечный цикл опроса сервера о текущем балансе
protected Balance doInBackground(String... parameter) {
String url = parameter[0];
Balance tProgress;
do {
tProgress = ntw.getBalance(url);
if (tProgress!=null){
publishProgress(tProgress);
try {Thread.sleep(500);}
catch (InterruptedException Ex){}
}
}while (!this.isCancelled());
return tProgress;
}
public int getCurrentBalance() {
return currentBalance;
}
public int getCurrentID() {
return currentID;
}
}
|
Java
|
UTF-8
| 4,842 | 2.703125 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
package org.sakaiproject.assignment2.logic;
import java.io.OutputStream;
import java.util.regex.Pattern;
import org.sakaiproject.assignment2.model.Assignment2;
public interface ZipExportLogic
{
/**
* The regular expression used for extracting identifying information from the
* folder names. This pattern extracts the value within parentheses.
* For instance, the submitter folder is in the format "Wagner, Michelle (wagnermr)".
* This expression will extract the username for use in uploading info.
* Also used for the version folder which is in the format "20090225_12:45PM (34)" where
* the value in parens is the version id.
*/
public static final String FILE_NAME_REGEX = "(?<=\\()[^\\(\\)]+(?=\\))";
/**
* the file can't be extracted and is considered "corrupt" if the folder
* name is longer than this for some reason
*/
public static final int MAX_FILE_NAME_LENGTH = 83;
/**
* Zip up the submissions for the given assignment. Will only include
* submissions that the current user is allowed to view or grade.
* Each student has a folder that contains every submission version. Each version
* folder contains the submitted text and attachments. It also contains a
* "Feedback" folder. If there are no submitted versions, the student's folder
* will only contain a "Feedback" folder for the instructor to provide feedback
* without submission. The "Feedback" folder contains a file for feedback comments and
* a file for annotating the submitted text (if it exists). If assignment is graded, includes a csv file containing
* the grade information. Only gradable students are include in the grades csv file.
* @param outputStream
* @param assignmentId
* @throws SecurityException if current user is not authorized to access
* the given assignment from a grading perspective
*/
void getSubmissionsZip(OutputStream outputStream, Long assignmentId);
/**
* Zip up the submissions for the given assignment. Will only include
* submissions that the current user is allowed to view or grade.
* Each student has a folder that contains every submission version. Each version
* folder contains the submitted text and attachments. It also contains a
* "Feedback" folder. If there are no submitted versions, the student's folder
* will only contain a "Feedback" folder for the instructor to provide feedback
* without submission. The "Feedback" folder contains a file for feedback comments and
* a file for annotating the submitted text (if it exists). If assignment is graded, includes a csv file containing
* the grade information. Only gradable students are include in the grades csv file.
* @param outputStream
* @param assignmentId
* @param filterGroupId
* @throws SecurityException if current user is not authorized to access
* the given assignment from a grading perspective
*/
void getSubmissionsZip(OutputStream outputStream, Long assignmentId, String filterGroupId);
/**
*
* @param folderName
* @param pattern the Pattern for extracting the id compiled using {@link ZipExportLogic#FILE_NAME_REGEX}
* @return the unique identifier associated with the given folder.
* Returns null if id cannot be derived from folder name. For instance,
* for the student submission folder will return the student's displayId. For
* a version folder will return the version id.
*/
public String extractIdFromFolderName(String folderName, Pattern pattern);
/**
*
* @param value
* @param replaceSpaces will replace all spaces with the given value. leave
* null if you want to preserve spaces
* @return Formats and escapes the given String value. This is useful for user-supplied text
* (such as the assignment title) so we don't run into trouble with special
* characters or exceed the length for folder names when decompressing
*/
public String escapeZipEntry(String value, String replaceSpaces);
/**
*
* @return the folder name used for the Feedback folder in the download
*/
public String getFeedbackFolderName();
/**
*
* @return the file name for the feedback comments in the download
*/
public String getFeedbackFileName();
/**
*
* @return the file name for the annotated submitted text in the download
*/
public String getAnnotatedTextFileName();
/**
*
* @param assignment
* @return the name of the top level folder for this download.
* built from the assignment title and site title
* for example "My Assignment Title_SP09 MATH 413"
*/
public String getTopLevelFolderName(Assignment2 assignment);
}
|
C++
|
UTF-8
| 758 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#include "Application.h"
#include "Resource.h"
Resource::Resource(RESOURCE_TYPE _type, uint UID)
{
if (UID == 0)
id = App->GenerateNewId();
else
id = UID;
type = _type;
}
Resource::~Resource()
{
}
Resource::RESOURCE_TYPE Resource::GetType() const
{
return type;
}
uint Resource::GetId() const
{
return id;
}
void Resource::SetId(uint UID)
{
id = UID;
}
const char* Resource::GetName() const
{
return name.c_str();
}
void Resource::SetName(std::string _name)
{
name = _name;
}
const char* Resource::GetFile() const
{
return file.c_str();
}
void Resource::SetFile(std::string _file)
{
file = _file;
}
const uint Resource::GetCantities() const
{
return cantity;
}
void Resource::SetCantities(uint _cantity)
{
cantity += _cantity;
}
|
Java
|
UTF-8
| 219 | 2.625 | 3 |
[] |
no_license
|
package datastructures.Tries.Contacts;
public class Trie {
TrieNode root;
public Trie() {
this.root = new TrieNode();
}
public void insert(String word) {
root.addWord(word);
}
}
|
Java
|
UTF-8
| 5,048 | 2.75 | 3 |
[] |
no_license
|
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
class DirectoryServer extends TCPServer {
private InetAddress rightNeighbor;
private HashMap<String, String> clientLookup;
DirectoryServer(String IPAddress, int directoryServerID) throws UnknownHostException {
super(IPAddress, directoryServerID, Constants.DIRECTORY_SERVER_TCP_PORT);
clientLookup = new HashMap<>();
}
private InetAddress getRightNeighbor() {
return rightNeighbor;
}
void setRightNeighbor(String rightNeighbor) throws UnknownHostException {
this.rightNeighbor = InetAddress.getByName(rightNeighbor);
}
void printAllRecords() {
System.out.println();
System.out.println("**********************************************");
System.out.println("Directory Server: " + getServerID() + " has the following entries:");
for (HashMap.Entry<String, String> entry : clientLookup.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(" (" + key + ":" + value + ")");
}
System.out.println("**********************************************");
}
private void createUDPSocket() throws IOException, InterruptedException {
DatagramSocket serverSocket = new DatagramSocket(Constants.DIRECTORY_SERVER_UDP_PORT, this.getIPAddress());
System.out.println("DirectoryServer: " + this.getServerID() + " creating UDP Socket at: " + serverSocket.getLocalAddress() + ":" + serverSocket.getLocalPort());
byte[] receiveData = new byte[1024];
byte[] sendData;
while (true) {
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
switch (message.substring(0, 1)) {
case Constants.INIT:
sendData = init();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
break;
case Constants.INFORM_AND_UPDATE:
this.informAndUpdate(receivePacket.getAddress().toString().substring(1), message.substring(1));
sendData = "updated".getBytes();
DatagramPacket sendPacket1 = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket1);
break;
case Constants.QUERY_FOR_CONTENT:
sendData = this.queryForContent(message.substring(1)).getBytes();
DatagramPacket sendPacket2 = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket2);
break;
case Constants.EXIT:
sendData = this.exit((receivePacket.getAddress().toString().substring(1))).getBytes();
DatagramPacket sendPacket3 = new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket3);
break;
default:
System.out.println("Host #" + this.getServerID() + " received a bad message: " + message.substring(1) + " should have received " + Constants.INIT);
}
}
}
void openUDPSocket() {
Thread thread1 = new Thread(() -> {
try {
this.createUDPSocket();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
}
private byte[] init() {
return getRightNeighbor().toString().substring(1).getBytes();
}
private void informAndUpdate(String clientIp, String contentName) {
clientLookup.put(contentName, clientIp);
}
public String queryForContent(String contentName) {
return clientLookup.getOrDefault(contentName, "Key not found: " + contentName + "at server: " + getServerID());
}
private String exit(String clientIP) {
Set<String> keys = new HashSet<>();
for (HashMap.Entry<String, String> entry : clientLookup.entrySet()) {
if (entry.getValue().equals(clientIP)) {
keys.add(entry.getKey());
}
}
clientLookup.keySet().removeAll(keys);
String rc = String.valueOf(keys.size());
return "Directory Server: " + getServerID() + " removed " + rc + " records associated with client: " + clientIP;
}
}
|
Markdown
|
UTF-8
| 415 | 2.5625 | 3 |
[] |
no_license
|
+++
title = "Prediction is the Essence of Intelligence"
author = ["Jethro Kuan"]
slug = "prediction_is_the_essence_of_intelligence"
draft = false
+++
We learn models of the world by making predictions. We know how our view of the
world changes when we move our heads and shift our eyes. This is how we obtain
our notion of depth.
These low level concepts compound hierarchically to form larger, more abstract
concepts.
|
C#
|
UTF-8
| 4,682 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
using Projeto3Camadas.Code.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Projeto3Camadas.Code.DAL;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Projeto3Camadas.Code.BLL
{
public class ClienteBLLSQL
{
private int contador = 0;
AcessoBancodeDadosSQLSERVER sql;
public int Contador { get => contador; set => contador = value; }
public void Inserir(ClienteDTO dto)
{
try
{
sql = new AcessoBancodeDadosSQLSERVER();
string nome = dto.Nome.Replace("'", "''");
sql.Conectar();
string comando = "insert into usuarios (usuario,nome,email,senha) VALUES ('" + dto.Usuario + "','" + nome + "','" + dto.Email + "','" + dto.Senha + "')";
sql.ExecutarComandoSQL(comando);
}
catch(Exception ex)
{
throw new Exception("Erro ao tentar Cadastrar o cliente: " + ex.Message);
}
finally
{
sql = null;
}
}
public void Atualizar(ClienteDTO dto)
{
try
{
string nome = dto.Nome.Replace("'", "''");
sql = new AcessoBancodeDadosSQLSERVER();
sql.Conectar();
string comando = "update usuarios set nome = '" + nome +"', email = '" + dto.Email + "' where id = " + dto.Id ;
sql.ExecutarComandoSQL(comando);
}
catch (Exception ex)
{
throw new Exception("Erro ao tentar Cadastrar o cliente: " + ex.Message);
}
finally
{
sql = null;
}
}
public void AlterarSenha(ClienteDTO dto)
{
try
{
sql = new AcessoBancodeDadosSQLSERVER();
sql.Conectar();
string comando = "update usuarios set senha = '" + dto.Senha + "' where id = " + dto.Id;
sql.ExecutarComandoSQL(comando);
}
catch (Exception ex)
{
throw new Exception("Erro ao tentar Alterar senha: " + ex.Message);
}
finally
{
sql = null;
}
}
public void Excluir(ClienteDTO dto)
{
try
{
string nome = dto.Nome.Replace("'", "''");
sql = new AcessoBancodeDadosSQLSERVER();
sql.Conectar();
string comando = "delete from usuarios where id = " + dto.Id;
sql.ExecutarComandoSQL(comando);
}
catch (Exception ex)
{
throw new Exception("Erro ao tentar Excluir o cliente: " + ex.Message);
}
finally
{
sql = null;
}
}
public DataTable SelecionaTodosUsuarios()
{
DataTable dt = new DataTable();
try
{
sql = new AcessoBancodeDadosSQLSERVER();
sql.Conectar();
dt = sql.RetDataTable("Select id,usuario,nome, email from usuarios");
return dt;
}
catch (Exception ex)
{
throw new Exception("Erro ao tentar Listar todos os Usuarios: " + ex.Message);
}
finally
{
sql = null;
}
}
// FAz login no sistema
public bool Verificalogin(String usuario, String senha)
{
bool logar = false;
try
{
SqlDataReader dr;
sql = new AcessoBancodeDadosSQLSERVER();
sql.Conectar();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * from usuarios where usuario = '"+ usuario + "' and senha = '" + Projeto3Camadas.Code.DTO.ClienteDTO.AcertaSenha(senha) + "'";
cmd.Parameters.AddWithValue("@usuario", usuario);
cmd.Parameters.AddWithValue("@senha", Projeto3Camadas.Code.DTO.ClienteDTO.AcertaSenha(senha));
dr = sql.RetDataReader(cmd.CommandText);
if(dr.HasRows)
{
logar = true;
}
}
catch (SqlException erro)
{
MessageBox.Show("Erro no login: " +erro.Message);
}
return logar;
}
}
}
|
TypeScript
|
UTF-8
| 169 | 2.65625 | 3 |
[] |
no_license
|
export interface Product {
id:number;
title:string;
description:string;
rating:rating;
}
export interface rating
{
rate:number;
count:number;
}
|
PHP
|
UTF-8
| 86 | 2.546875 | 3 |
[] |
no_license
|
<?php
interface IndentInterface
{
public function all();
public function get($id);
}
|
PHP
|
UTF-8
| 5,499 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* {LIBRARY_NAME}
*
* PHP Version 5.3
*
* @copyright Emil Johansson 2013
* @license http://www.opensource.org/licenses/mit-license.php MIT
* @link https://github.com/emiljohansson
*/
//---------------------------------------------------------------
// Public class
//---------------------------------------------------------------
/**
* Base for the construction of a web-document.
*
* The Document class handles and are responsible for everything related
* to the construction of a HTML, JSON or XML page. All elements created in a project
* will eventually be stored in this object.
*
* It is possible to add header information, such as meta, css and js content.
*
* To create new elements see the DOM object. Don't refer this object, only the
* Engine needs to communicate with the Document object.
*
* @version 0.1.1
* @author Emil Johansson <emiljohansson.se@gmail.com>
* @todo Support json
*/
abstract class Document {
//-----------------------------------------------------------
// Private static properties
//-----------------------------------------------------------
/**
* A singleton Document object.
* @var Document
*/
private static $instance;
//-----------------------------------------------------------
// Public static methods
//-----------------------------------------------------------
/**
* Returns an instance of the Document.
*
* @return DocumentInterface
*/
public static final function get() {
if (!isset(self::$instance)) {
self::init();
}
return self::$instance;
}
/**
* Returns an instance of the Document.
*
* @return Document
*/
public static final function init($format = null) {
if ($format === 'xml') {
self::$instance = new XMLDocument();
return;
}
if ($format === 'json') {
self::$instance = new JsonDocument();
return;
}
self::$instance = new HTMLDocument();
}
//-----------------------------------------------------------
// Public properties
//-----------------------------------------------------------
/**
* The language attribute for the html tag; <html lang="en">.
* @var string
*/
public $lang = 'en';
/**
* The inner html for the title tag; <title>Default title</title>
* @var string
*/
public $title = 'Default title';
//-----------------------------------------------------------
// Protected properties
//-----------------------------------------------------------
/**
* An instance to the native DOMDocument class.
* @var DOMDocument
*/
protected $document;
/**
* The head tag; <head></head>. Meta, css and js files will
* be appendend to this property.
* @var DOMElement
*/
protected $head;
/**
* The body tag; <body></body>. All display elements for the
* application will be placed here.
* @var DOMElement
*/
protected $body;
//-----------------------------------------------------------
// Constructor method
//-----------------------------------------------------------
/**
* Initializes the document and creates the head and body tags.
*
* @return void
*/
protected function __construct() {
$this->document = new DOMDocument();
$this->head = $this->document->createElement('head');
$this->body = $this->document->createElement('body');
}
//-----------------------------------------------------------
// Public methods
//-----------------------------------------------------------
/**
* Adds a meta tag to the head node.
*
* @param string $name
* @param array $arr
* @return void
*/
public final function addMetaTag(array $arr) {
$element = $this->document->createElement('meta');
foreach ($arr as $key => $value) {
$element->setAttribute($key, $value);
}
$this->head->appendChild($element);
}
/**
* Adds a stylesheet tag to the head node.
*
* @param string $url
* @return void
*/
public final function addStylesheet($url) {
$element = $this->document->createElement('link');
$element->setAttribute('rel', 'stylesheet');
$element->setAttribute('type', 'text/css');
$element->setAttribute('href', $url);
$this->head->appendChild($element);
}
/**
* Adds a faicon tag to the head node.
*
* @param string $url
* @return void
*/
public final function addFavicon($url) {
$element = $this->document->createElement('link');
$element->setAttribute('rel', 'shortcut icon');
$element->setAttribute('type', 'image/x-icon');
$element->setAttribute('href', $url);
$this->head->appendChild($element);
}
/**
* Adds a script tag to the head node.
*
* @param string $name
* @param string $url
* @return void
*/
public final function addScript($url) {
$element = $this->document->createElement('script');
$element->setAttribute('type', 'text/javascript');
$element->setAttribute('src', $url);
$this->head->appendChild($element);
}
/**
* Appends an element to the body element.
*
* @param Element $element
* @return void
*/
public final function appendChild($element) {
$this->body->appendChild($element);
}
/**
* Creates a new element.
*
* @param string $nodeName
* @param string $nodeValue
* @return Element
*/
public final function createElement($nodeName, $nodeValue = null) {
return new Element($nodeName, $nodeValue);
}
/**
* Returns the reference to the body element.
*
* @return DOMElement
*/
public final function getBody() {
return $this->body;
}
/**
* Constructs the page.
*
* @return void
*/
abstract public function assemble();
}
|
Python
|
UTF-8
| 1,043 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
from pyecharts.charts import Line
from pyecharts import options as opts
import pandas as pd
import time
def charthtml(FileName):
data = pd.read_csv(FileName)
# 发布时间类别
category = list(set(data["发布时间"].values.tolist()))
line = Line()
# line.add_xaxis(data['当地时间'].tolist())
for i in category:
line.add_xaxis(data[data["发布时间"] == i]['当地时间'].to_list())
line.add_yaxis(i, data[data["发布时间"] == i]['播放数'].to_list())
line.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
line.render('ACI单个作品实时数据.csv.html')
if __name__ == '__main__':
FileName = ['D:\Smile\DataAnalysisProject\DouyinBuyinLiveDate\ACI号\ACI单个作品实时数据.csv', ]
# FileName = ['ACI直播间流量速度.csv']
# FileName = 'ACI直播间流量速度.csv'
# FileName = '誉马线直播间流量速度.csv'
while True:
for i in FileName:
charthtml(i)
time.sleep(60)
|
C++
|
UTF-8
| 14,433 | 2.828125 | 3 |
[] |
no_license
|
//
// Created by 谢威宇 on 2019-06-07.
//
#include "genetic_worker.h"
#include <random>
#include <algorithm>
#define RAND(a, b) ((rand() % ((b)-(a)))+ (a))
genetic_worker::genetic_worker(port *port1) : worker_base(port1) {}
unsigned seed = time(nullptr);
void genetic_worker::work() {
//initialize the cargo_rule_group
std::cout << "-----------genetic algorithm---------" << std::endl
<< "population:" << population << " max generation:" << max_generation << std::endl
<< "single cross:" << single_cross_possibility << " double cross:" << double_cross_possibility
<< " mutant:" << mutant_possibility << std::endl;
get_first_generation();
int generation = 1;
while (generation <= max_generation) {
std::cout << "generation (" << generation << "/" << max_generation << ")";
get_fit_score();
if (generation == max_generation)
break;
//reproduce the next generation
std::vector<std::vector<cargo *> > new_cargo_group;
std::vector<std::vector<cargo *> > new_transport_group;
int i = 0;
double possibility_sum = 0;
//single cross
possibility_sum += single_cross_possibility;
for (; i < (int)(possibility_sum * population); i++) {
//select parents
int
father_id = RAND(0, population),
mother_id = RAND(0, population);
std::vector<cargo *>
cargo_boy = cargo_rule_group[father_id],
cargo_girl = cargo_rule_group[mother_id],
transport_boy = transport_rule_group[father_id],
transport_girl = transport_rule_group[mother_id];
//select a point in [1,n-1];
int point = RAND(1, cargo_boy.size());
//cross
for (int i = point; i < cargo_boy.size(); i++) {
std::swap(cargo_boy[i], cargo_girl[i]);
}
//repair
std::set<cargo *> inset;
for (int i = 0; i < point; i++) {
inset.insert(cargo_boy[i]);
}
for (int i = point; i < cargo_boy.size(); i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(cargo_boy[i])) {
while (j < cargo_boy.size() && inset.count(cargo_rule_group[mother_id][j]))
j++;
cargo_boy[i] = cargo_rule_group[mother_id][j];
}
inset.insert(cargo_boy[i]);
}
inset.clear();
for (int i = 0; i < point; i++) {
inset.insert(cargo_girl[i]);
}
for (int i = point; i < cargo_girl.size(); i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(cargo_girl[i])) {
while (j < cargo_girl.size() && inset.count(cargo_rule_group[father_id][j]))
j++;
cargo_girl[i] = cargo_rule_group[father_id][j];
}
inset.insert(cargo_girl[i]);
}
//select a point in [1,n-1];
point = RAND(1, cargo_boy.size());
//cross
for (int i = point; i < transport_boy.size(); i++) {
std::swap(transport_boy[i], transport_girl[i]);
}
//repair
inset.clear();
for (int i = 0; i < point; i++) {
inset.insert(transport_boy[i]);
}
for (int i = point; i < transport_boy.size(); i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(transport_boy[i])) {
while (j < transport_boy.size() && inset.count(transport_rule_group[mother_id][j]))
j++;
transport_boy[i] = transport_rule_group[mother_id][j];
}
inset.insert(transport_boy[i]);
}
inset.clear();
for (int i = 0; i < point; i++) {
inset.insert(transport_girl[i]);
}
for (int i = point; i < transport_girl.size(); i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(transport_girl[i])) {
while (j < transport_girl.size() && inset.count(transport_rule_group[father_id][j]))
j++;
transport_girl[i] = transport_rule_group[father_id][j];
}
inset.insert(transport_girl[i]);
}
//add them to the new rule_group
new_cargo_group.push_back(cargo_boy);
new_transport_group.push_back(transport_boy);
i++;
if (i < possibility_sum * population) {
new_cargo_group.push_back(cargo_girl);
new_transport_group.push_back(transport_girl);
}
}
//double cross
possibility_sum += double_cross_possibility;
for (; i < (int)(possibility_sum * population); i++) {
//select parents
int
father_id = RAND(0, population),
mother_id = RAND(0, population);
std::vector<cargo *>
cargo_boy = cargo_rule_group[father_id],
cargo_girl = cargo_rule_group[mother_id],
transport_boy = transport_rule_group[father_id],
transport_girl = transport_rule_group[mother_id];
//select two points in [1,n-1];
int
point1 = RAND(1, cargo_boy.size()),
point2 = RAND(1, cargo_boy.size());
if (point1 > point2)
std::swap(point1, point2);
//cross
for (int i = point1; i <= point2; i++) {
std::swap(cargo_boy[i], cargo_girl[i]);
}
//repair
std::set<cargo *> inset;
for (int i = 0; i < cargo_boy.size(); i++) {
if (i < point1 || i > point2)
inset.insert(cargo_boy[i]);
}
for (int i = point1; i <= point2; i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(cargo_boy[i])) {
while (j < cargo_boy.size() && inset.count(cargo_rule_group[mother_id][j]))
j++;
cargo_boy[i] = cargo_rule_group[mother_id][j];
}
inset.insert(cargo_boy[i]);
}
inset.clear();
for (int i = 0; i < cargo_girl.size(); i++) {
if (i < point1 || i > point2)
inset.insert(cargo_girl[i]);
}
for (int i = point1; i <= point2; i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(cargo_girl[i])) {
while (j < cargo_girl.size() && inset.count(cargo_rule_group[father_id][j]))
j++;
cargo_girl[i] = cargo_rule_group[father_id][j];
}
inset.insert(cargo_girl[i]);
}
//select two points in [1,n-1];
point1 = RAND(1, cargo_boy.size());
point2 = RAND(1, cargo_boy.size());
if (point1 > point2)
std::swap(point1, point2);
//cross
for (int i = point1; i <= point2; i++) {
std::swap(transport_boy[i], transport_girl[i]);
}
//repair
inset.clear();
for (int i = 0; i < transport_boy.size(); i++) {
if (i < point1 || i > point2)
inset.insert(transport_boy[i]);
}
for (int i = point1; i <= point2; i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(transport_boy[i])) {
while (j < transport_boy.size() && inset.count(transport_rule_group[mother_id][j]))
j++;
transport_boy[i] = transport_rule_group[mother_id][j];
}
inset.insert(transport_boy[i]);
}
inset.clear();
for (int i = 0; i < transport_girl.size(); i++) {
if (i < point1 || i > point2)
inset.insert(transport_girl[i]);
}
for (int i = point1; i <= point2; i++) {
int j = 0;
//if this cargo already showed up
if (inset.count(transport_girl[i])) {
while (j < transport_girl.size() && inset.count(transport_rule_group[father_id][j]))
j++;
transport_girl[i] = transport_rule_group[father_id][j];
}
inset.insert(transport_girl[i]);
}
//add them to the new rule_group
new_cargo_group.push_back(cargo_girl);
new_transport_group.push_back(transport_girl);
i++;
if (i < possibility_sum * population) {
new_cargo_group.push_back(cargo_boy);
new_transport_group.push_back(transport_boy);
}
}
//migrant
possibility_sum += migrant_possibility;
for (; i < (int)(possibility_sum * population); i++) {
std::shuffle(cargo_rule.begin(), cargo_rule.end(), std::default_random_engine(seed));
new_cargo_group.push_back(cargo_rule);
std::shuffle(transport_rule.begin(), transport_rule.end(), std::default_random_engine(seed));
new_transport_group.push_back(transport_rule);
}
//mutant
possibility_sum += mutant_possibility;
for (; i < (int)(possibility_sum * population); i++) {
std::vector<cargo *> mutant_unit = cargo_rule_group[get_proportional_random_unit()];
std::swap(mutant_unit[RAND(0, mutant_unit.size())], mutant_unit[RAND(0, mutant_unit.size())]);
new_cargo_group.push_back(mutant_unit);
mutant_unit = transport_rule_group[get_proportional_random_unit()];
std::swap(mutant_unit[RAND(0, mutant_unit.size())], mutant_unit[RAND(0, mutant_unit.size())]);
new_transport_group.push_back(mutant_unit);
}
//stable
for (; new_cargo_group.size() < population; i++) {
new_cargo_group.push_back(cargo_rule_group[get_proportional_random_unit()]);
new_transport_group.push_back(transport_rule_group[get_proportional_random_unit()]);
}
//make sure the best one stay
// new_cargo_group.push_back(best_cargo_rule);
// new_transport_group.push_back(best_transport_rule);
cargo_rule_group = new_cargo_group;
transport_rule_group = new_transport_group;
generation++;
}
finish_work();
}
void genetic_worker::finish_work() {
worker_base::finish_work();
}
void genetic_worker::get_first_generation() {
cargo_rule_group.clear();
for (int i = 0; i < population; i++) {
std::shuffle(cargo_rule.begin(), cargo_rule.end(), std::default_random_engine(seed));
cargo_rule_group.push_back(cargo_rule);
std::shuffle(transport_rule.begin(), transport_rule.end(), std::default_random_engine(seed));
transport_rule_group.push_back(transport_rule);
}
}
void genetic_worker::get_fit_score() {
//clear existing score
fit_score.clear();
for (int i = 0; i < population; i++) {
std::sort(ship_rule.begin(), ship_rule.end());
int this_best_time = 0x3f3f3f3f;
while (std::next_permutation(ship_rule.begin(), ship_rule.end())) {
//to be changed
int time = port1->simulate_greedy(ship_rule, cargo_rule_group[i],transport_rule_group[i]);
if (time < this_best_time) {
this_best_time = time;
}
if (time < best_time) {
best_time = time;
best_cargo_rule = cargo_rule_group[i];
best_transport_rule = transport_rule_group[i];
best_ship_rule = ship_rule;
}
}
fit_score.push_back(this_best_time);
}
std::vector<std::pair<double, int>> score_to_id;
double max_time = 0, min_time = 0x3f3f3f3f;
for (int i = 0; i < fit_score.size(); i++) {
score_to_id.push_back(std::make_pair(fit_score[i], i));
max_time = std::max(max_time, fit_score[i]);
min_time = std::min(min_time, fit_score[i]);
}
std::cout << " this generation best time:"
<< min_time
<<" global best:"
<<best_time
<< std::endl;
if (debug&&min_time <= best_time) {
std::cout << "The best schedule is:";
port1->simulate_greedy(best_ship_rule, best_cargo_rule, best_transport_rule,10);
std::cout << "\n";
std::cout << "The best ship rule is:\n";
for (int i = 0; i < best_ship_rule.size(); i++) {
std::cout << best_ship_rule[i]->get_name() << "\n";
}
}
sort(score_to_id.begin(), score_to_id.end());
//compute a new score
double total = 0;
int selected_num = population * reserve_ration;
double setted_score = score_to_id[population - 1].first;
for (int i = 0; i < score_to_id.size(); i++) {
if (i < selected_num) {
fit_score[i] = (setted_score - fit_score[i]);
} else {
fit_score[i] = 0;
}
total += fit_score[i];
}
//normalize the new score
for (int i = 0; i < fit_score.size(); i++) {
fit_score[i] = fit_score[i] * population / total;
}
//calculate the pre sum
fit_score_presum.clear();
fit_score_presum.push_back(fit_score[0]);
for (int i = 1; i < fit_score.size(); i++) {
fit_score_presum.push_back(fit_score[i] + fit_score_presum.back());
}
}
int genetic_worker::get_proportional_random_unit() {
double r = rand() * population / double(RAND_MAX);
return std::lower_bound(fit_score_presum.begin(), fit_score_presum.end(), r) - fit_score_presum.begin();
}
|
Go
|
UTF-8
| 842 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
package proxy
import (
"io/ioutil"
"testing"
"github.com/stretchr/testify/assert"
)
const testdata = "testdata/avengers.txt"
func TestFileProxy(t *testing.T) {
fp := NewFileProxy(testdata)
data := make([]byte, 8)
n, err := fp.Read(data)
assert.NoError(t, err)
assert.Equal(t, 8, n)
assert.Equal(t, "Iron Man", string(data))
data = make([]byte, 24)
n, err = fp.Read(data)
assert.NoError(t, err)
assert.Equal(t, 24, n)
assert.Equal(t, "Iron Man, Ant-Man, Hulk\n", string(data))
}
func BenchmarkReadFile(b *testing.B) {
for n := 0; n < b.N; n++ {
_, err := ioutil.ReadFile(testdata)
if err != nil {
b.Fatal(err)
}
}
}
func BenchmarkFileProxy(b *testing.B) {
data := make([]byte, 24)
fp := NewFileProxy(testdata)
for n := 0; n < b.N; n++ {
_, err := fp.Read(data)
if err != nil {
b.Fatal(err)
}
}
}
|
JavaScript
|
UTF-8
| 1,643 | 3.125 | 3 |
[] |
no_license
|
// El codigo se trajo desde el server.js para limpiar ese archivo
// importamos io desde server.js
const { io } = require('../server');
// Lanzar eventos con socket, el primero conecction, se envia al ciente desde el servidor
io.on('connection', function(socket) {
// Rescatar la ip
console.log("El cliente con IP: " + socket.handshake.address + " Se ha conectado..");
// emitir un mensaje para que el cliente lo escuche
socket.emit('enviarMensaje', {
usuario: 'Administrador',
mensaje: 'Bienvenidos a esta aplicación'
});
// cliente se desconecta de la sesion
socket.on('disconnect', function() {
console.log(socket.name + ' ha desconectado del chat.' + socket.id);
});
// Escuchar el cliente, se agrega la función que se definio en el emit de index.html
socket.on('enviarMensaje', (data, callback) => {
console.log(data); // para probar
// la propiedad broadcast se agrega despues de socket para que todos los usuarios vean los mensajes
socket.broadcast.emit('enviarMensaje', { // socket.emit('enviarMensaje',data); tb puede ser asi
usuario: data.usuario,
mensaje: data.mensaje
});
// Si viene el usuario, con el callback podemos indicar que salio ok o hay un error
/* if (mensaje.usuario) {
// funcion que quier llamar cuando sale todo bien
callback({
resp: 'TODO SALIO BIEN!'
});
} else {
callback({
resp: 'TODO SALIO MAL!!!!'
});
}*/
});
});
|
JavaScript
|
UTF-8
| 3,892 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
d3.csv("tutorial_conposition.csv", function(dataset) {
function gridData() {
var data = new Array();
var xpos = 1; //starting xpos and ypos at 1 so the stroke will show when we make the grid below
var ypos = 1;
var width = 50;
var height = 50;
var click = 0;
// iterate for rows
//data.push(new Array());
var temp = new Array();
for (var row = 1; row < Object.keys(dataset['0']).length; row++) {
temp.push({
x: xpos,
y: 0,
topic: Object.keys(dataset['0'])[row]
})
xpos = xpos+width;
// temp.push(Object.keys(dataset['0'])[row]);
}
data.push(temp);
console.log(data);
xpos = 1;
ypos = 50;
console.log(data);
for (var column = 1; column < dataset.length; column++) {
data.push( new Array());
// console.log("hi"+dataset[column]['filename']);
data[column].push({
x: 0,
y: ypos,
name: dataset[column]['filename']
})
ypos = ypos +height;
}
//for (var row = 2; row < Object.keys(dataset['0']).length; row++) {
//}
ypos = 50;
xpos = 250;
//ypos = ypos +height;
console.log(data);
for (var row = 1; row < dataset.length; row++) {
//data.push( new Array() );
// iterate for cells/columns inside rows
for (var column = 1; column <= 20; column++) {
data[row].push({
x: xpos,
y: ypos,
val: dataset[row]['Topic'+(column+1)]
})
// txtfiles.push(dataset[row]['filename']);
//console.log(data);
// increment the x position. I.e. move it over by 50 (width variable)
xpos += width;
}
// reset the x position after a row is complete
xpos = 250;
// increment the y position for the next row. Move it down 50 (height variable)
ypos += height;
}
console.log(data);
return data;
}
var margin = {top: 50, right: 30, bottom: 30, left: 50},
width = 800 - margin.left - margin.right,
height = 800 - margin.top - margin.bottom;
var y = d3.scale.ordinal().rangeBands([0, height],0,1),
x = d3.scale.ordinal().rangeBands([0, width],0,1),
c = d3.scale.category20().domain(d3.range(36));
var gridData = gridData();
// I like to log the data to the console for quick debugging
var txtfiles = new Array();
var topics = new Array();
//for (var row = 0; row < gridData.length; row++) {
// console.log(dataset[row]['filename']);
// console.log(gridData[row]);
//txtfiles.push(dataset[row]['filename']);
// }
var grid = d3.select("#grid")
.append("svg")
.attr("width","1200px")
.attr("height","1200px");
var row = grid.selectAll(".row")
.data(gridData)
.enter().append("g")
.attr("class", "row");
console.log(gridData);
row.append("text")
.attr("class", "label")
.attr("x",function(row,i) { var temp =0; return row[0].x;})
.attr("y",function(row,i) { var temp =0; return row[0].y;})
.attr("dy", ".32em")
.text(function(d, i) { return d[0].name; });
console.log(gridData);
var column = row.selectAll(".circle")
.data(function(d) { return d; })
.enter().append("circle")
.attr("class","label")
.attr("x",function(row,i) { if(row.topic) return row.x;})
.attr("y",function(row,i) { if(row.topic) return row.y;})
.attr("dx", ".32em")
.text(function(d, i) { console.log(d.topic); if(d.topic) return d.topic; })
.attr("class","circle")
.attr("cx", function (d,i) { if(!d.topic) return (d.x);})
.attr("cy", function (d) { if(!d.topic) return (d.y);})
.attr("r", function (d) { if(!d.name && !d.topic) return (d.val*10); else return 0; })
.attr("width", function(d) { return d.width; })
.attr("height", function(d) { return d.height; })
.style("fill", "#fff")
.style("stroke", "#222")
.on('click', function(d) {
d.click ++;
if ((d.click)%4 == 0 ) { d3.select(this).style("fill","#fff"); }
if ((d.click)%4 == 1 ) { d3.select(this).style("fill","#2C93E8"); }
if ((d.click)%4 == 2 ) { d3.select(this).style("fill","#F56C4E"); }
if ((d.click)%4 == 3 ) { d3.select(this).style("fill","#838690"); }
});
});
|
C#
|
UTF-8
| 933 | 2.65625 | 3 |
[] |
no_license
|
using Shop.Domain.Infrastructure;
using System.Collections.Generic;
namespace Shop.Application.ProductsAdmin
{
[Service]
public class GetProducts
{
private readonly IProductManager _productManager;
public GetProducts(IProductManager productManager)
{
_productManager = productManager;
}
public IEnumerable<Response> Do() => _productManager.GetProducts(x => true, x => new Response
{
Id = x.Id,
Name = x.Name,
Description = x.Description,
ValueInRubles = x.Value
});
public class Response
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal ValueInRubles { get; set; }
public string ValueStrRubles { get => $"\x20bd{ValueInRubles:N2}"; }
}
}
}
|
C
|
UTF-8
| 2,818 | 2.890625 | 3 |
[
"Apache-2.0"
] |
permissive
|
#define N 10
#include <time.h>
#include <stdio.h>
#include <math.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stddef.h>
#include "mpi.h"
#define posicao(I, J, COLUNAS) ((I)*(COLUNAS) + (J))
int *matrizA, *matrizB, *matrizC, *matrizP, *matrizD;
double speed_up(double ts, double tp)
{
return ts/tp;
}
void imprime_matriz(int *args, int tamanho)
{
for(int i = 0; i < tamanho; i++)
{
for(int j = 0; j < tamanho; j++)
{
if(j != (tamanho-1))
{
printf("%d \t",args[posicao(i, j, tamanho)]);
}
else
{
printf("%d \n",args[posicao(i, j, tamanho)]);
}
}
}
printf("\n");
}
int *aloca_matriz(int tamanho) {
return (int *) malloc(tamanho * tamanho * sizeof(int));
}
void carrega_matriz(int *args, int tamanho)
{
for (int i=0; i < tamanho; i++) {
for (int j=0; j < tamanho; j++) {
args[posicao(i, j, tamanho)] = 2;
}
}
}
void print_results(char *prompt, int a[N][N]);
int main(int argc, char *argv[])
{
srand(time(NULL));
int i, j, k, rank, size, tag = 99, blksz, sum = 0, len;
char hostname[MPI_MAX_PROCESSOR_NAME];
matrizA = aloca_matriz(N);
matrizB = aloca_matriz(N);
matrizC = aloca_matriz(N);
matrizP = aloca_matriz(N);
matrizD = aloca_matriz(N);
// como não estamos interessados em computar o tempo do carregamento
// deixamos esta parte fora da contagem do tempo
carrega_matriz(matrizA,N);
carrega_matriz(matrizB,N);
carrega_matriz(matrizC,N);
carrega_matriz(matrizD,N);
carrega_matriz(matrizP,N);
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//scatter rows of first matrix to different processes
MPI_Scatter(matrizA, N*N/size, MPI_INT, matrizP, N*N/size, MPI_INT,0,MPI_COMM_WORLD);
//broadcast second matrix to all processes
MPI_Bcast(matrizB, N*N, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
//perform vector multiplication by all processes
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
for (int k=0; k<N; k++)
matrizP[posicao(i, j, N)] += matrizA[posicao(i, k, N)] * matrizB[posicao(k, j, N)];
MPI_Gather(matrizD, N*N/size, MPI_INT, matrizC, N*N/size, MPI_INT, 0, MPI_COMM_WORLD);
// Obtem o nome do processador (nome da maquina onde o processo sera executado)
MPI_Get_processor_name(hostname, &len);
printf ("Numero de tarefas = %d Meu rank= %d Rodando em %s\n", size,rank,hostname);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
if(rank==0) imprime_matriz(matrizP,N);
free(matrizA);
free(matrizB);
free(matrizC);
free(matrizP);
free(matrizD);
}
|
Java
|
UTF-8
| 1,218 | 2.875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.zakgof.actr.impl;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import com.zakgof.actr.IActorScheduler;
/**
* Scheduler that creates a single-thread executor for each actor.
*/
public class ThreadPerActorScheduler implements IActorScheduler {
private final Map<Object, ExecutorService> executors = new ConcurrentHashMap<>();
@Override
public void actorCreated(Object actorId) {
executors.put(actorId, Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "actr:" + actorId)));
}
@Override
public void actorDisposed(Object actorId) {
ExecutorService service = executors.remove(actorId);
service.shutdown();
}
@Override
public void schedule(Runnable task, Object actorId) {
ExecutorService executor = executors.get(actorId);
if (!executor.isShutdown()) {
executor.execute(task);
}
}
@Override
public void close() {
executors.values().forEach(ExecutorService::shutdown);
}
}
|
Java
|
UTF-8
| 2,836 | 3.21875 | 3 |
[] |
no_license
|
package com.asp.kevinbell.numbershapes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
public void makeToast(String string){
Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
}
// method to take the user's input to determine what kind of number it is
public void testNumber(View view){
// gets user's input and checks if it's empty
EditText userInput = (EditText) findViewById(R.id.userInput);
if(userInput.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter a value!", Toast.LENGTH_LONG).show();
}
else {
// create a new number
Number testNum = new Number();
testNum.number = Integer.parseInt(userInput.getText().toString());
int num = testNum.number;
Log.i("Number", userInput.getText().toString());
// checks for what type of number the user gave
if (testNum.isSquare() == true && testNum.isTriangular() == true) {
Toast.makeText(MainActivity.this, num + " is both a square and triangular number!!", Toast.LENGTH_SHORT).show();
} else if (testNum.isSquare() == true) {
Toast.makeText(MainActivity.this, num + " is a square number!!", Toast.LENGTH_SHORT).show();
} else if (testNum.isTriangular() == true) {
Toast.makeText(MainActivity.this, num + " is a triangular number!!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, num + " is neither a square and triangular number!!", Toast.LENGTH_SHORT).show();
}
}
}
// number class to do the work of determining what type of number the user gave
public class Number {
public int number;
// checks if the number is triangular
public boolean isTriangular(){
int x = 1;
int triangularNumber = 1;
while(triangularNumber <= number){
if(number == triangularNumber){ return true; }
x++;
triangularNumber = triangularNumber + x;
}
return false;
}
// checks if the number is square
public boolean isSquare(){
double squareRootNumber = Math.sqrt(number);
if(Math.floor(squareRootNumber) == squareRootNumber){return true;}
else { return false; }
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
Shell
|
UTF-8
| 382 | 2.671875 | 3 |
[] |
no_license
|
#!/bin/bash
echo "***********************"
echo "*******PUSH IMAGE******"
echo "***********************"
IMAGE=app
echo "*******LOGGING to docker********"
docker login -u chsunny548 -p $PASS
echo "***********Tagging image***********"
docker tag $IMAGE:$BUILD_TAG chsunny548/$IMAGE:$BUILD_TAG
echo "***********Pushing image************"
docker push chsunny548/$IMAGE:$BUILD_TAG
|
Java
|
UTF-8
| 2,784 | 1.859375 | 2 |
[] |
no_license
|
package com.ge.ef.ese.pocketmobile.europe.service;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for BaseReponse complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BaseReponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="errorObject" type="{http://service.europe.pocketmobile.ese.ef.ge.com}ArrayOfErrorObject"/>
* <element name="status" type="{http://service.europe.pocketmobile.ese.ef.ge.com}ServiceStatus"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BaseReponse", propOrder = {
"errorObject",
"status"
})
@XmlSeeAlso({
CheckOutSaveResults.class,
AuthenticationResponse.class,
FetchResults.class,
FetchStaticListResults.class,
AuthenticationTestResponse.class,
SaveResults.class,
SearchResults.class,
CheckOutSearchResults.class,
SearchImageChunksResponse.class,
DocUploadResponse.class,
GenerateCheckInPDFResponse.class,
ImgUploadResponse.class,
GetImageResponse.class
})
public class BaseReponse {
@XmlElement(required = true, nillable = true)
protected ArrayOfErrorObject errorObject;
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected ServiceStatus status;
/**
* Gets the value of the errorObject property.
*
* @return
* possible object is
* {@link ArrayOfErrorObject }
*
*/
public ArrayOfErrorObject getErrorObject() {
return errorObject;
}
/**
* Sets the value of the errorObject property.
*
* @param value
* allowed object is
* {@link ArrayOfErrorObject }
*
*/
public void setErrorObject(ArrayOfErrorObject value) {
this.errorObject = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link ServiceStatus }
*
*/
public ServiceStatus getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link ServiceStatus }
*
*/
public void setStatus(ServiceStatus value) {
this.status = value;
}
}
|
C++
|
UTF-8
| 4,261 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
/*
* Copyright (c) 2009 Aleksander B. Demko
* This source code is distributed under the MIT license.
* See the accompanying file LICENSE.MIT.txt for details.
*/
#include <hydra/Thumb.h>
#include <assert.h>
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <hydra/Engine.h>
#include <hydra/Exif.h>
#include <hydra/RotateCode.h>
using namespace hydra;
// current, want, output
void hydra::calcAspect(unsigned long C, unsigned long R, unsigned long WC,
unsigned long WR, unsigned long &c, unsigned long &r,
bool growtofit) {
if (!growtofit && R <= WR && C <= WC) {
r = R;
c = C;
return;
}
double scr, scc;
scr = static_cast<double>(WR) / R;
scc = static_cast<double>(WC) / C;
// assume scc is the smaller
if (scr < scc)
scc = scr; // its not?
r = static_cast<unsigned long>(scc * R);
c = static_cast<unsigned long>(scc * C);
}
Thumb::Thumb(const QString &filename) : dm_filename(filename) {}
Thumb::Thumb(QImage &srcimg) : dm_img(srcimg) { assert(!dm_img.isNull()); }
Thumb::~Thumb() {}
QString Thumb::thumbDir(void) { return Engine::dbDir() + "/thumbs"; }
void Thumb::mkThumbDir(void) { QDir("/").mkdir(thumbDir()); }
QString Thumb::fileName(const QString &hash, int rotateCode,
unsigned long desiredW, unsigned long desiredH) {
QString ret;
QTextStream str(&ret);
str << thumbDir() << "/" << hash << "." << desiredW << "x" << desiredH
<< "." << rotateCodeToDegrees(rotateCode) << ".jpg";
return ret;
}
int Thumb::generate(const QString &destfilename, QImage *destimage,
int rotateCode, unsigned long desiredW,
unsigned long desiredH, unsigned long *actualW,
unsigned long *actualH) {
assert(rotateCode >= 0);
int ret;
if (QFileInfo(destfilename).exists()) {
if (destimage) {
// the caller wants a copy of the existing image
if (destimage->load(destfilename)) {
if (actualW)
*actualW = destimage->width();
if (actualH)
*actualH = destimage->height();
return Generate_FileExists; // good load of existing thumb
}
// the loading of the existing thumb was unsuccesfull... fall
// through and try to make it again
} else
return Generate_FileExists;
}
ret = verifyLoadImage();
if (ret != Generate_Ok)
return ret;
assert(!dm_img.isNull());
unsigned long row, col;
unsigned long desiredW_rotated, desiredH_rotated;
// we want to scale first, before the exif (if any) rotation
// not technically correct, but good enough
rotateSizeByCode(rotateCode, desiredW, desiredH, desiredW_rotated,
desiredH_rotated);
calcAspect(dm_img.width(), dm_img.height(), desiredW_rotated,
desiredH_rotated, col, row, false);
QImage scaled_image;
if (!destimage)
destimage = &scaled_image;
assert(destimage);
/*unsigned long irow = row*2, icol = col*2;
// This is a thumnbnailer speedup as per
http://labs.trolltech.com/blogs/2009/01/26/creating-thumbnail-preview/
// it doesnt seem faster though, atleast not by much, so I'm not using it!
if (icol < dm_img.width() && irow < dm_img.height())
{qDebug() << "FAST::generate";
// perform a fast two-phase scale (first NN then smooted)
*destimage = dm_img.scaled(icol, irow).scaled(QSize(col, row),
Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
}
else*/
*destimage = dm_img.scaled(QSize(col, row), Qt::IgnoreAspectRatio,
Qt::SmoothTransformation);
*destimage = rotateImageByCode(rotateCode, *destimage);
(*destimage).save(destfilename);
if (actualW)
*actualW = destimage->width();
if (actualH)
*actualH = destimage->height();
return Generate_Ok;
}
int Thumb::verifyLoadImage(void) {
if (!dm_img.isNull())
return Generate_Ok; // nothing to do, already loaded
if (dm_img.load(dm_filename))
return Generate_Ok;
else
return Generate_LoadError;
}
|
C#
|
UTF-8
| 2,318 | 2.640625 | 3 |
[] |
no_license
|
using Minesweeper;
using Xunit;
using Moq;
using Minesweeper.Factory;
using Minesweeper.Service;
namespace MinesweeperTests
{
public class EndToEndTests
{
private readonly Mock<IIO> io;
private readonly ConsoleGameController gameController;
public EndToEndTests()
{
var rng = new Mock<INumberGenerator>();
rng.SetupSequence(i => i.GetRandomNumber(It.IsAny<int>(), It.IsAny<int>()))
.Returns(0)
.Returns(0);
io = new Mock<IIO>();
var coordinateService = new CoordinateService();
var fieldService = new FieldService(coordinateService);
var dimensionFactory = new DimensionFactory();
var coordinateFactory = new CoordinateFactory();
var validation = new Validation();
var mineCoordinateFactory = new MineCoordinateFactory(rng.Object);
var gridFactory = new GridFactory(coordinateService);
var gameService = new GameService(fieldService, dimensionFactory, coordinateFactory, validation, mineCoordinateFactory, gridFactory);
gameController = new ConsoleGameController(gameService, io.Object);
}
[Fact]
public void EasyDifficultyLevel_Win()
{
io.SetupSequence(i => i.GetUserInput())
.Returns("EASY")
.Returns("2,2")
.Returns("1,2")
.Returns("2,1")
.Returns("2,2");
gameController.Run();
io.Verify(x => x.Write("You've won the game :)\n"), Times.Once);
}
[Fact]
public void EasyDifficultyLevel_Quit()
{
io.SetupSequence(i => i.GetUserInput())
.Returns("EASY")
.Returns("2,2")
.Returns("q");
gameController.Run();
io.Verify(x => x.Write("You have quit the game.\n"), Times.Once);
}
[Fact]
public void EasyDifficultyLevel_Lose()
{
io.SetupSequence(i => i.GetUserInput())
.Returns("EASY")
.Returns("2,2")
.Returns("1,1");
gameController.Run();
io.Verify(x => x.Write("You've lost :(\n"), Times.Once);
}
}
}
|
SQL
|
UTF-8
| 547 | 4.3125 | 4 |
[
"Apache-2.0"
] |
permissive
|
SELECT t.subject_id,
t.cohort_start_date,
coalesce(min(o.cohort_start_date), max(t.cohort_end_date)) AS event_date,
CASE WHEN min(o.cohort_start_date) IS NULL THEN 0 ELSE 1 END AS event
FROM @cohort_database_schema.@cohort_table t
LEFT JOIN @cohort_database_schema.@cohort_table o
ON t.subject_id = o.subject_id
AND o.cohort_start_date >= t.cohort_start_date
AND o.cohort_start_date <= t.cohort_end_date
AND o.cohort_definition_id = @outcome_id
WHERE t.cohort_definition_id = @target_id
GROUP BY t.subject_id, t.cohort_start_date;
|
TypeScript
|
UTF-8
| 1,256 | 2.609375 | 3 |
[] |
no_license
|
import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { UtilsService } from "app/commons/services/utils.service";
export type SortOrder = {
sort: string,
order: string
}
@Component({
selector: 'app-sort-link',
templateUrl: 'sort-link.component.html'
})
export class SortLinkComponent implements OnInit {
private _value: SortOrder;
@Input() private sortValue: string;
@Input() private defaultOrder: string;
@Output() private valueChange = new EventEmitter();
private nextOrder = this.defaultOrder;
constructor(private utils:UtilsService) {
}
@Input()
private set value(value: SortOrder) {
this._value = value;
this.nextOrder = this.computeNextOrder();
}
public ngOnInit() {
}
private computeNextOrder() {
if (this._value.sort != this.sortValue) {
return this.defaultOrder;
}
else {
return this.utils.toggleOrder(this._value.order);
}
}
clicked() {
let nextValue = {
sort: this.sortValue,
order: this.nextOrder
}
this._value = nextValue;
this.valueChange.emit(nextValue);
}
}
|
JavaScript
|
UTF-8
| 1,855 | 2.75 | 3 |
[] |
no_license
|
function causeTraverser(obj) {
if (obj.isRoot) {
return obj.stack
}
if (obj.causedBy) {
return causeTraverser(obj.causedBy)
}
return obj.stack
}
/**
* A sublcass of Error that is used to semantically communicate how an error
* should impact error tracking and messages to the client (UI messages)
*
* BasicError#clientMessage should be set to whatever message you would like
* to show to the client in the UI
*
* BasicError#causedBy allows for error-wrapping. This allows us to return a more
* semantic error (BasicError), while holding on-to the actual error for inspection
* later on (perhaps by sending the cause to Sentry, or any other error-tracking
* facility)
*
* BasicError should not be used directly, rather it should be extended from a
* concrete implementation.
*/
export class BasicError extends Error {
constructor(msg) {
super(msg)
this.causedBy = null
this.name = this.constructor.name
this.scope = 'developer'
this.clientMessage = 'Oops, it looks like something went wrong. We have been notified and will look into what caused this. In the meantime, please try again later.'
}
setClientMessage(msg) {
this.clientMessage = msg
return this
}
setCausedBy(error) {
this.causedBy = error
return this
}
useCausedByStack() {
if (this.causedBy) {
this.stack = causeTraverser(this)
}
return this
}
/**
* This method causes the error-stack traverser to stop at this level. This means that,
* in the future, stack traces will be equal to the trace that led-up to this
* error being thrown.
*
* Order matters! This method needs to be called before using the useCausedByStack
* method, which is typically used by the concrete implementations of this class.
*/
setAsRoot() {
this.isRoot = true
return this
}
}
|
C#
|
UTF-8
| 752 | 3.46875 | 3 |
[] |
no_license
|
using System.Collections;
/// <summary>
/// Applies an exponential smoothing filter determined by the
/// timeLag of the smoothed result.
/// </summary>
/// <remarks>
/// The behavior of the filter is independent of the frame rate.
/// Lower frame rates will have less filtering applied.
/// </remarks>
public class Smoother
{
public float state;
public float timeLag;
public Smoother (float init, float set_timeLag = 0f)
{
state = init;
timeLag = set_timeLag;
}
// Update is called once per frame
public void Update (float next, float deltaTime)
{
float nextWeight = 1f;
if (timeLag > 0f)
nextWeight = deltaTime / (deltaTime + timeLag);
state *= (1f - nextWeight);
state += nextWeight * next;
}
}
|
C#
|
UTF-8
| 2,467 | 3.734375 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Declare the variable as private
//Then declare its public method with get and set accessors
//Notice the "value" keyword
//Auto implementaion - whenever we do not have any restriction on a field, e.g its value can be anything , we do not need sech big blocks of get and set
//Look in the case of email id here
//You even dont need to declare that private variable
//just declare a public property and inclue get and set accessors without any condition
//the compiler will itself create a private variable of the same name which you can use later also (see S1.emailId")
namespace HowTousePropertiesInCsharp
{
public class Student
{
private string _name;
private int _id;
private int _passingMarks = 40;
public string emailID
{
get;
set;
}
public int ID
{
set
{
if (value <= 0) //value keyword takes the value what we set to the variable, like S1.Id = 101, so value = 101
{
throw new Exception("ID cannot be 0 or negative");
}
this._id = value;
}
get //while printing , get accessor is invoked
{
return this._id;
}
}
public string name
{
set
{
if (string.IsNullOrEmpty(value))
{
throw new Exception("Name cannot be null or blank");
}
this._name = value;
}
get
{
return this._name;
}
}
public int passinMarks
{
get
{
return this._passingMarks;
}
}
}
class Program
{
static void Main(string[] args)
{
Student S1 = new Student();
S1.ID = 100; //Just acting as a property , this calls the set accessor whwenver executed
S1.name = "Ujjwal";
Console.WriteLine("ID is {0}", S1.ID);
Console.WriteLine("Welcome {0}", S1.name);
Console.WriteLine("Passing marks = {0}", S1.passinMarks);
S1.emailID = "ujjwalvaish@outlook.com";
Console.WriteLine("email Id is {0}", S1.emailID);
Console.ReadKey();
}
}
}
|
Java
|
UTF-8
| 3,108 | 2.171875 | 2 |
[] |
no_license
|
package org.harper.otms.calendar.service;
import org.harper.otms.calendar.service.dto.CancelLessonDto;
import org.harper.otms.calendar.service.dto.ChangeLessonStatusDto;
import org.harper.otms.calendar.service.dto.ChangeLessonStatusResponseDto;
import org.harper.otms.calendar.service.dto.ConfirmCancelDto;
import org.harper.otms.calendar.service.dto.GetLessonDto;
import org.harper.otms.calendar.service.dto.GetLessonHistoryDto;
import org.harper.otms.calendar.service.dto.GetLessonHistoryResponseDto;
import org.harper.otms.calendar.service.dto.GetLessonItemDto;
import org.harper.otms.calendar.service.dto.GetLessonItemResponseDto;
import org.harper.otms.calendar.service.dto.GetLessonResponseDto;
import org.harper.otms.calendar.service.dto.GetOngoingLessonDto;
import org.harper.otms.calendar.service.dto.GetOngoingLessonResponseDto;
import org.harper.otms.calendar.service.dto.GetRequestedLessonDto;
import org.harper.otms.calendar.service.dto.GetRequestedLessonResponseDto;
import org.harper.otms.calendar.service.dto.MakeLessonItemDto;
import org.harper.otms.calendar.service.dto.MakeLessonItemResponseDto;
import org.harper.otms.calendar.service.dto.SetupLessonDto;
import org.harper.otms.calendar.service.dto.SetupLessonResponseDto;
import org.harper.otms.calendar.service.dto.TriggerLessonDto;
import org.harper.otms.calendar.service.dto.TriggerLessonResponseDto;
public interface LessonService {
/**
* Retrieve a lesson
*
* @param request
* @return
*/
GetLessonResponseDto getLesson(GetLessonDto request);
/**
* Retrieve lesson item
*
* @param request
* @return
*/
GetLessonItemResponseDto getLessonItem(GetLessonItemDto request);
/**
* Make a lesson item from its lesson
*
* @param request
* @return
*/
MakeLessonItemResponseDto makeLessonItem(MakeLessonItemDto request);
/**
* Client setup meeting with tutor
*
* @param request
*/
SetupLessonResponseDto setupLesson(SetupLessonDto request);
/**
*
* @param request
* @return
*/
GetRequestedLessonResponseDto getRequestedLessons(
GetRequestedLessonDto request);
/**
*
* @param request
* @return
*/
GetOngoingLessonResponseDto getOngoingLessons(GetOngoingLessonDto request);
/**
*
* @param request
* @return
*/
GetLessonHistoryResponseDto getLessonHistory(GetLessonHistoryDto request);
/**
*
* @param request
* @return
*/
ChangeLessonStatusResponseDto changeLessonStatus(
ChangeLessonStatusDto request);
/**
* Both client and tutor can propose the cancellation of a meeting. Client
* can directly cancel a meeting Tutor always need to get approval from
* client to cancel a meeting
*
* @param request
*/
void cancelLesson(CancelLessonDto request);
/**
* Client confirm tutor's request of canceling a meeting or a item
*
* @param request
*/
void confirmCancel(ConfirmCancelDto request);
/**
* Trigger a given lesson at specific time. This is generally achieved via a
* scheduler service and is not intended to be invoked by user
*/
TriggerLessonResponseDto triggerLesson(TriggerLessonDto request);
}
|
Markdown
|
UTF-8
| 702 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
# Serverless Chaos Monkey
A lambda function that randomly chooses a running EC2 server and terminates it.
## Getting started
1. Generate the package
```bash
npm install
npm run package
```
2. upload the package `chaos-monkey.zip` to AWS Lambda.
3. Add and edit `EC2_AWS_REGION` as an env. variable for your function
4. Apply permissions found in `iam-policy.json` (edit it with the correct aws region)
5. Add EventBridge (CloudWatch Events) as a trigger, sending events to the function every 5 minutes.
6. Check the logs `/aws/lambda/chaos-monkey` and the state of your EC2 instances.
## Chaos engineering
[Some reading about this discipline](https://en.wikipedia.org/wiki/Chaos_engineering)
|
Java
|
UTF-8
| 292 | 2.71875 | 3 |
[] |
no_license
|
public class SunDemo {
public static void main(String[] args) {
Sun sun1 = Sun.getInstance();
Sun sun2 = Sun.getInstance();
System.out.println(sun1==sun2);
Car car1 = new Car();
Car car2 = new Car();
System.out.println(car1==car2);
}
}
|
Markdown
|
UTF-8
| 1,137 | 2.765625 | 3 |
[
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] |
permissive
|
The following steps must be taken for the example script to work.
0. Create wallet
0. Create account for gstio.token
0. Create account for scott
0. Create account for exchange
0. Set token contract on gstio.token
0. Create GST token
0. Issue initial tokens to scott
**Note**:
Deleting the `transactions.txt` file will prevent replay from working.
### Create wallet
`clgst wallet create`
### Create account steps
`clgst create key`
`clgst create key`
`clgst wallet import --private-key <private key from step 1>`
`clgst wallet import --private-key <private key from step 2>`
`clgst create account gstio <account_name> <public key from step 1> <public key from step 2>`
### Set contract steps
`clgst set contract gstio.token /contracts/gstio.token -p gstio.token@active`
### Create GST token steps
`clgst push action gstio.token create '{"issuer": "gstio.token", "maximum_supply": "100000.0000 GST", "can_freeze": 1, "can_recall": 1, "can_whitelist": 1}' -p gstio.token@active`
### Issue token steps
`clgst push action gstio.token issue '{"to": "scott", "quantity": "900.0000 GST", "memo": "testing"}' -p gstio.token@active`
|
Python
|
UTF-8
| 1,012 | 3.75 | 4 |
[] |
no_license
|
import pytest
from roman import RomanNumber
def test_zero():
with pytest.raises(ValueError):
RomanNumber.from_arabic(0)
def test_negative():
with pytest.raises(ValueError):
RomanNumber.from_arabic(-1)
def test_overflow():
with pytest.raises(ValueError):
RomanNumber.from_arabic(4000)
arabic = (1, 5, 10, 50, 100, 500, 1000)
roman = ('I', 'V', 'X', 'L', 'C', 'D', 'M')
@pytest.mark.parametrize('arabic,roman', zip(arabic, roman))
def test_basic_literal(arabic, roman):
assert RomanNumber.from_arabic(arabic) == roman
def test_roman_addition():
assert RomanNumber.from_arabic(3) == 'III'
def test_roman_subtraction():
assert RomanNumber.from_arabic(4) == 'IV'
def test_roman_examples():
assert RomanNumber.from_arabic(2417) == 'MMCDXVII'
assert RomanNumber.from_arabic(999) == 'CMXCIX'
assert RomanNumber.from_arabic(290) == 'CCXC'
assert RomanNumber.from_arabic(1742) == 'MDCCXLII'
assert RomanNumber.from_arabic(3974) == 'MMMCMLXXIV'
|
C++
|
UTF-8
| 1,798 | 2.59375 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
bool check[100][100][100] = { false, };
int tom[100][100][100];
int day[100][100][100] = { 0, };
struct bfs
{
int x;
int y;
int z;
};
int main()
{
bool nt = false;
int m, n, h, count=0,d, max=0;
cin >> m >> n >> h;
bfs t, cn;
queue<bfs> s;
int dx[6] = { 1, -1, 0, 0, 0, 0 };
int dy[6] = { 0, 0, 1, -1, 0, 0 };
int dz[6] = { 0, 0, 0, 0, 1, -1 };
for (int i = 0; i < h; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++)
{
cin >> tom[k][j][i];
}
}
}
for (int i = 0; i < h; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++)
{
if (tom[k][j][i] == 1 && check[k][j][i] == false)
{
t.x = k;
t.y = j;
t.z = i;
check[k][j][i] = true;
s.push(t);
}
}
}
}
while (!s.empty())
{
cn = s.front();
s.pop();
for (int l = 0; l < 6; l++)
{
d = day[cn.x][cn.y][cn.z];
bfs next;
next.x = cn.x + dx[l];
next.y = cn.y + dy[l];
next.z = cn.z + dz[l];
if (next.x >= 0 && next.x < m && next.y >= 0 && next.y < n && next.z >= 0 && next.z < h && check[next.x][next.y][next.z] == false && tom[next.x][next.y][next.z] != -1)
{
tom[next.x][next.y][next.z] = 1;
s.push(next);
check[next.x][next.y][next.z] = true;
day[next.x][next.y][next.z] = d + 1;
}
}
}
for (int i = 0; i < h; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++)
{
if (max < day[k][j][i])
{
max = day[k][j][i];
}
}
}
}
for (int i = 0; i < h; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < m; k++)
{
if (tom[k][j][i] == 0)
{
nt = true;
}
}
}
}
if (nt)
{
cout << -1;
}
else
{
cout << max;
}
return 0;
}
|
PHP
|
UTF-8
| 1,449 | 2.5625 | 3 |
[] |
no_license
|
<?php
namespace app\controllers;
use vendor\core\Auth;
use vendor\core\Session;
use vendor\core\Request;
use vendor\core\View;
use app\models\Users;
class AuthController extends Auth
{
protected $view;
protected $request;
/*
* p - alxalxalx7
* l - g0l0va
* */
public function __construct()
{
$this->view = new View();
$this->request = new Request();
$this->view->layout = 'auth';
}
public function loginAction()
{
if(isset($_COOKIE['goods_mem']) && $currentUser = Users::findByColumn("secret", $_COOKIE['goods_mem'])){
Auth::successAuth($currentUser->login, 1);
header("Location: /admin");
}
$login = $this->request->post('login', false);
$password = $this->request->post('password', false);
$remember = $this->request->post('remember', 0);
if($login && $password){
if(Auth::checkAuth($login, $password))
{
Auth::successAuth($login, $remember);
header("Location: /admin");
}
else{
Session::sessionInit('error', 'Ошибка авторизации - Не верный логин или пароль');
}
}
$this->view->display("auth/login");
}
public function logoutAction()
{
Session::sessionRemove('AdminAuth');
header('Location: /');
}
}
|
Java
|
UTF-8
| 849 | 3.328125 | 3 |
[] |
no_license
|
import java.util.*;
public class LC271 {
public String encode(List<String> strs) {
if (strs.size() == 0) return "empty";
StringBuilder sb = new StringBuilder();
sb.append("startbab");
for (String str:strs) {
str.replaceAll("a", "aa");
sb.append(str);
sb.append("bab");
}
sb.append("end");
return sb.toString();
}
// Decodes a single string to a list of strings.
public List<String> decode(String s) {
LinkedList<String> res = new LinkedList<>();
if (s.equals("empty")) return res;
String[] arr = s.split("bab");
for (String str : arr) {
str.replaceAll("aa", "a");
res.add(str);
}
res.removeFirst();
res.removeLast();
return res;
}
}
|
Python
|
UTF-8
| 304 | 3.96875 | 4 |
[] |
no_license
|
from tkinter import *
def say_something1(thing):
print(thing)
def say_something2(a, b, c):
print(a, b, c)
window = Tk()
window.title("Window After")
window.config(padx=100, pady=50)
window.after(1000, say_something1, "Hello")
window.after(2000, say_something2, 3, 5, 8)
window.mainloop()
|
Swift
|
UTF-8
| 1,330 | 2.703125 | 3 |
[] |
no_license
|
//
// HTTPClient.swift
// structureCoversionDemo
//
// Created by Mobikasa on 09/10/17.
// Copyright © 2017 mobikasa. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import SwiftyJSON
class HTTPClient : NSObject{
static let shared = HTTPClient()
let CompletionHandler: (Data?, URLResponse?, Error?) -> Void = {
(data, response, error) in
// this is where the completion handler code goes
if let response = response {
print(response)
}
if let error = error {
print(error)
}
}
func getRequest(baseUrl:String, params:Dictionary<String, Any>?, completionBlock:@escaping (([String:Any]?, Bool, String?) -> Void) ) {
Alamofire.request(baseUrl).responseJSON { (responseData) in
switch (responseData.result){
case .success(_):
if let response = responseData.result.value{
completionBlock(response as? [String : Any] ,true, nil)
}
break
case .failure(_):
completionBlock(nil,false, responseData.result.error!.localizedDescription)
break
}
}
}
}
|
C++
|
UTF-8
| 1,217 | 2.796875 | 3 |
[] |
no_license
|
#pragma once
#include <vector>
#include "Car.h"
#include <algorithm>
#include <map>
using std::vector;
using std::ostream;
using std::map;
using std::unique_ptr;
class RepoException {
string msg;
public:
RepoException(string msg): msg{msg}{}
string getMessage() {
return msg;
}
};
class CarRepo
{
private:
vector <Car> cars;
//map<string, Car> cars;
public:
CarRepo() = default;
CarRepo(const CarRepo& ot) = delete;
~CarRepo() = default;
virtual void storeCar(const Car& car);
const vector<Car>& getAll()const noexcept {
return cars;
}
/*const map<string,Car>& getAll()const noexcept {
return cars;
}*/
virtual void sterge(const Car& c);
virtual void update(const Car& cNou);
const Car& find(string nrInmatriculare);
};
class CarRepoFile : public CarRepo {
private:
string fileName;
public:
CarRepoFile(string fileName) :CarRepo(), fileName{ fileName }{
loadFromFile();
}
CarRepoFile(const CarRepo& ot) = delete;
void loadFromFile();
void storeToFile();
void storeCar(const Car&car) override;
void update(const Car&cNou)override;
void sterge(const Car& c)override;
};
void RepoTests();
|
Java
|
UTF-8
| 170 | 2.34375 | 2 |
[] |
no_license
|
package plactice6;
public class CalcLogic {
public static int tasu(int a , int b) {
return(a + b);
}
public static int hiku(int a , int b){
return(a - b);
}
}
|
Ruby
|
UTF-8
| 4,351 | 2.84375 | 3 |
[
"MIT"
] |
permissive
|
# Module for lame quotes... or not
module Bronze
def self.quote
quotes = [
'El fútbol es como el ajedrez pero sin dados. *-Lukas Podolski*',
'Recibí un golpe en mi tobillo izquierdo. Pero algo me dijo que era mi derecho. *-Lee Hendrie*',
'Bueno, del país no puedo contarles nada... solo puedo adelantarle que se trata de un equipo brasileño... *-Murci Rojas*',
'...y bueno, sin duda es difícil jugar a 3.000 kilómetros de altura. *-Manuel López*',
'Sí, mi pierna está bien, en la casa, cuidando a mis hijos, y le quisiera mandar un saludo, que la quiero mucho y que me espere con algo rico... *-Francisco Huaiquipán*',
'No me importaría perder todos los partidos, siempre y cuando ganemos la Liga. *-Mark Viduka*',
'Jamás he consumido cocaína. *-Nicolás Peric*, _después de anotar un gol de arco a arco en Bolivia y salir positivo en un examen antidoping._',
'Perdimos porque no ganamos. *-Ronaldo*',
'Cuando un equipo anda bien, no anda mal y viceversa. *-Mariano Puyol*',
'Me gustaría jugar en un equipo italiano. Como el Barcelona. *-Mark Draper*',
'No pude acostumbrarme a vivir en Italia. Era como estar en un país extranjero. *-Ian Rush*',
'Primero que nada un saludo a todos los señores televisores... *-Juan Carlos Letelier*',
'Siempre me pongo primero mi bota derecha. Y luego, obviamente, mi calcetín izquierdo. *-Barry Venison*',
'Mis padres han estado conmigo apoyándome. Incluso desde que tenía 7 años. *-David Beckham*',
'Los brasileños son de Sudamérica. Los ucranianos serán más europeos. *-Phil Neville*',
'A veces, en el fútbol, tienes que marcar goles. *-Thierry Henry*',
'No hay nada entre medio. O eres bueno, o eres malo. Nosotros estuvimos entre medio. *-Gary Lineker*',
'Tuve que tomar vino porque comí mucho cerdo. *-Pedro “Heidi” González*',
'¿Cuántos pulmones tengo? Bueno... Uno, como toda la gente, ¿no?. *-Héctor Puebla*',
'Estoy muy emocionado porque no todos los días se viaja a Europa. *-Frank Lobos*, _en declaraciones de la sub 20 chilena llegando a Estados Unidos._',
'Contento por mi debut, lo hice bien y por suerte pude lesionar a Francescoli. *-Luis Chavarría*',
'Lo bonito del fútbol es que se juega con los pies, se apoya en los pies y se piensa con la cabeza. *-Xavier Azkargorta*',
'No tengo por qué estar de acuerdo con lo que pienso. *-Carlos Caszely*',
'Dios me bendició. *-Eduardo “Pollito” Arancibia*',
'Vimos unas luces rojas, creíamos que pasaba algo malo y por eso entramos. *-Jaime “Pajarito” Valdés*, _sub 20 chileno, tras ser sorprendido dentro de un “sauna” que visitó para escapar de una concentración._',
'Ya sé que formo parte del best seller chileno... *-Francisco “Murci” Rojas*',
'Saludos a mi señora que está embarazada de mi. *-“Murci” Rojas*',
'Yo cacho que fue el desayuno... el que me cayó mal, comí... un puré picante con longaniza y leche. *-Francisco Huiquipán*',
'Recibí un golpe en mi tobillo izquierdo. Pero algo me dijo que era mi derecho. *-Lee Hendrie*',
'Ganar no es lo importante, siempre y cuando ganes. *-Vinnie Jones*',
'Vi al golero estético y se la tiré por arriba, fue un gol de odontología. *-Nelson Pedetti*',
'Como todo equipo africano, Jamaica es difícil por su velocidad y su fuerza. *-Edinson Cavani*',
'El equipo juega igual conmigo o sinmigo. *-Francisco “Murci” Rojas*',
'Los periodistas siempre inventan cosas que nunca son mentiras. *-Francisco “Murci” Rojas*',
'La fama es emífera, ¿no?. *-Iván Zamorano*',
'Lo que pasa es que los periodistas están sobacando el fútbol. *-Reinaldo Sánchez*',
'Tal vez habría que organizar un sextangular. *-Reinaldo Sánchez*',
'Voy a fichar en un equipo que va en el sextimo lugar. *-Eros Pérez*',
'Para que se produzca el gol, la pelota debe ingresar más de un ciento por ciento sobre la línea. *-Milton Millas*',
'Ni lo uno ni lo otro, sino todo lo contrario. *-Claudio Borghi*',
'¡Qué jugada! Si la pelota entraba, era gol. *-Héctor Vega Onesime*',
'Ojalá que en griega pueda hacer lo mismo. *-Alejandro Carrasco*',
'La gente me criticó mucho a mí. La gente tiraba la piedra y después la escondía, así que la mano quedaba por ahí hablando sola. *-Murci Rojas*',
'Me fui a la cresta cuando inventaron el Fair Play. *-Ricardo “Manteca” González*'
]
<<-HEREDOC
> #{quotes.sample}
HEREDOC
end
end
|
PHP
|
UTF-8
| 855 | 2.8125 | 3 |
[] |
no_license
|
<?php
define('DBHOST', 'localhost');
define('DBUSERNAME', 'learnphpuser');
define('DBPASSWORD', 'supersecret');
define('DBTABLE', 'myblog');
$dbc = FALSE;
function connectToDB() {
// Connect and select:
global $dbc;
if ( $dbc = @mysql_connect(DBHOST, DBUSERNAME, DBPASSWORD) ) {
return $dbc;
}
else { // Connection failure.
print '<p style="color: red;">Could not connect to MySQL:<br />' . mysql_error() . '.</p>';
return FALSE;
}
}
function selectDBTable() {
global $dbc;
if ( @mysql_select_db(DBTABLE, $dbc) ) {
return TRUE;
}
else {
// Handle the error if the database couldn't be selected:
print '<p style="color: red;">Could not select the database because:<br />' . mysql_error($dbc) . '.</p>';
mysql_close($dbc);
return FALSE;
}
}
?>
|
JavaScript
|
UTF-8
| 2,112 | 3.90625 | 4 |
[] |
no_license
|
const BinarySearchTree = require('../../data-structures-algorithms/DSA-BTS/bst');
// linear search
function indexOf(array, value) {
for (let i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
};
// binary search
function binarySearch(array, value, start, end) {
var start = start === undefined ? 0 : start;
var end = end === undefined ? array.length : end;
if (start > end) {
return -1;
}
const index = Math.floor((start + end) / 2);
const item = array[index];
console.log(start, end);
if (item == value) {
return index;
}
else if (item < value) {
return binarySearch(array, value, index + 1, end);
}
else if (item > value) {
return binarySearch(array, value, start, index - 1);
}
};
//DFS
function dfs(values=[]) {
if (this.left) {
values = this.left.dfs(values);
}
values.push(this.value);
if (this.right) {
values = this.right.dfs(values);
}
return values;
}
//BFS
function bfs(tree, values = []) {
const queue = new Queue(); // Assuming a Queue is implemented (refer to previous lesson on Queue)
const node = tree.root;
queue.enqueue(node);
while (queue.length) {
const node = queue.dequeue(); //remove from the queue
values.push(node.value); // add that value from the queue to an array
if (node.left) {
queue.enqueue(node.left); //add left child to the queue
}
if (node.right) {
queue.enqueue(node.right); // add right child to the queue
}
}
return values;
}
const main = () => {
const arr =[25, 15, 50, 10, 24, 35, 70, 4, 12, 18, 31, 44, 66, 90, 22];
const BST = new BinarySearchTree();
arr.map(n => BST.insert(n,n))
}
console.log(main())
/*
3. I would approach this with a BTS as this will allow each book to be assigned a number and will cut back on search times regardless of teh size of the library.
4. 1. 25, 15, 14, 19, 27, 89, 79, 91, 90, 35
4. 2. 8, 5, 7, 6, 9, 11, 10, 8
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.