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
4,471
3.078125
3
[]
no_license
package marvelydc.ui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.Border; import marvelydc.mapeado.GenAleatorios; import marvelydc.mapeado.Mapa; /** * Clase encargada de administrar cada sala en la interfaz gráfica * @version 10/01/2018 * @author Jose Juan Pena Gomez & Francisco Nunez Sierra * Desarrollo de Programas<br/> * <b>Grupo: JJyFarn </b><br> * <b>Entrega: EC_Final </b><br> * Curso: 2017/2018 */ @SuppressWarnings("serial") public class Square extends JPanel{ /** * Layout para almacenar las etiquetas */ private BorderLayout layout = new BorderLayout(); /** * Etiqueta con la id de la sala */ private JLabel idSquareLabel = new JLabel(" ",JLabel.LEFT); /** * Etiqueta con el dato de los pj */ private JLabel charactersLabel = new JLabel(" ",JLabel.CENTER); /** * Array con las paredes para poder poner los bordes correctamente */ private int walls[] = {1,1,1,1}; // N, W, S, E /** * Numero de la sala */ private int nsala; /** * Puntero a la imagen que debe usar para el fondo */ ImageIcon imagenFondo=null; /** * Puntero a la imagen que debe usar para los pj */ ImageIcon imagenPj=null; /** * Constructor del cuadrado que gestiona su id, le crea 4 paredes y le mete * un edificio de fondo aleatorio o no con una probabilidad de 1/3 * @param id * El id de la sala */ public Square(int id){ nsala=id; this.setLayout(layout); this.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black)); setBackground(Color.LIGHT_GRAY); if(id==Mapa.getInstancia().getDailyPlanet()) { if(Mapa.getInstancia().checkPortal()) imagenFondo=Resources.dpOpen; else imagenFondo=Resources.dpClosed; }else { if(GenAleatorios.generarNumero(3)==1) { int nEdificio=GenAleatorios.generarNumero(Resources.edificios.length); imagenFondo=Resources.edificios[nEdificio]; } } //Configuramos la etiqueta del identificador de sala idSquareLabel.setForeground(Color.BLUE); Font font = new Font("Helvetica", Font.ITALIC, 10); idSquareLabel.setFont(font); idSquareLabel.setText(Integer.toString(id)); this.add(idSquareLabel, BorderLayout.NORTH); //Configuramos la etiqueta del robot que hay en cada sala charactersLabel.setForeground(Color.BLACK); font = new Font("Helvetica", Font.BOLD, 14); charactersLabel.setFont(font); this.add(charactersLabel, BorderLayout.CENTER); } /** * Se le mete un texto y un icono de pj a el cuadrado * @param text Texto de personajes * @param icon Icono de los personajes */ public void setTextAndIcon(String text,ImageIcon icon){ imagenPj=icon; charactersLabel.setText(text); } /** * Se limpia el texto y el icono del cuadrado */ public void clearTextAndIcon() { imagenPj=null; charactersLabel.setText(" "); } /** * Pone las paredes a un array determinado * @param walls * Array de paredes donde un 1 es que hay y un 0 que no */ public void setWalls(int walls[]){ this.walls=walls; } /** * Pinta las paredes poniendo los bordes a las paredes que han sido establecidas con setwalls */ public void paintWalls(){ Border border; border = BorderFactory.createMatteBorder(walls[0], walls[1], walls[2], walls[3], Color.black); this.setBorder(border); } @Override /** * Sobreescritura del metodo paint que permite en las propias graficas del componente que * pintemos los iconos de pj y de los edificios del fondo */ public void paintComponent(Graphics g) { super.paintComponent(g); if(imagenFondo==Resources.dpClosed) if(Mapa.getInstancia().checkPortal()) imagenFondo=Resources.dpOpen; if(imagenFondo!=null) { g.setColor(Color.DARK_GRAY); g.fillOval(this.getWidth()/8, this.getHeight()/2, this.getWidth()*3/4, this.getHeight()/2); g.drawImage(imagenFondo.getImage(), this.getWidth()/4, this.getHeight()/4, this.getWidth()/2, this.getHeight()*5/8, null); } if(!Mapa.getInstancia().getSala(nsala).noQuedanArmas()) { g.drawImage(Resources.salaArma.getImage(), this.getWidth()*3/4, this.getHeight()/16, this.getWidth()/4, this.getHeight()*1/4, null); } if(imagenPj!=null) g.drawImage(imagenPj.getImage(), this.getWidth()/4,this.getHeight()*1/4, this.getWidth()/2, this.getHeight()*3/4, null); } }
Python
UTF-8
2,577
3.09375
3
[]
no_license
import gym import numpy as np import matplotlib.pyplot as plt def convertObservation(observation): curRow = int(observation/4) curCol = observation%4 return (curRow,curCol) def determineAction(observation, state): """ Returns 0 (go left) or 1 (go right) depending on whether the weighted sum of weights * observations > 0 """ #make sure previous observation gets set even if function returns early c = convertObservation(observation) p = convertObservation(state["prevStep"][0]) cs = np.cumsum(state[c,:]) v = np.random.uniform(0, cs[cs.shape[0]-1]) #random value from 0 to sum of all action weights for a given row and column for i in range(cs.shape[0]): if v < cs[i]: state["prevStep"] = (observation,i) return i def updateQ(observation,reward,done): discount = 0.99 learningRate = 0.1 c = convertObservation(observation) p = convertObservation(state["prevStep"][0]) oldQ = state["q"][p,state["prevStep"][1]] maxQ = np.max(state["q"][c,:]) if done: state["q"][p,state["prevStep"][1]] = oldQ * (1 - learningRate) + learningRate * reward return state["q"][p,state["prevStep"][1]] = oldQ * (1 - learningRate) + learningRate * (reward + discount * maxQ) def initEpisode(observation): state["prevStep"][0] = observation def initState(state): state["q"] = np.ones((4,4,4))*0.1 state["prevStep"] = "" def runEpisode(env, state): """ This function runs one episode with a given set of state and returns the total reward with those weights """ observation = env.reset() initialization(observation) for step in range(200): environment.render() action = determineAction(observation, state) observation, reward, done, info = env.step(action) updateQ(observation,reward,done) if done: break def runEpisode(env, state): """ This function runs one episode with a given set of state and returns the total reward with those weights """ observation = env.reset() initialization(observation) for step in range(200): action = determineAction(observation, state) observation, reward, done, info = env.step(action) updateQ(observation,reward,done) if done: break def main(): state = {} initState(state) env = gym.make('FrozenLake-v0') env.reset() for i in range(200): runEpisode(env,state) render_episode() if __name__ == '__main__': main()
Python
UTF-8
1,312
2.640625
3
[]
no_license
import numpy as np from scipy import stats from specsens import util def pfa(noise_power, thr, n, dB=True): if dB: noise_power = util.dB_to_factor_power(noise_power) return 1. - stats.chi2.cdf(2. * thr / noise_power, 2. * n) def pd(noise_power, signal_power, thr, n, dB=True, num_bands=1): if dB: noise_power = util.dB_to_factor_power(noise_power) signal_power = util.dB_to_factor_power(signal_power) # noise energy is distributed over all bands, but signal is not # therefore increase SNR by number of bands signal_power *= num_bands return 1. - stats.chi2.cdf(2. * thr / (noise_power + signal_power), 2. * n) def thr(noise_power, pfa, n, dB=True): if dB: noise_power = util.dB_to_factor_power(noise_power) return stats.chi2.ppf(1. - pfa, 2. * n) * noise_power / 2. def roc(noise_power, signal_power, pfa, n, dB=True, num_bands=1): if dB: noise_power = util.dB_to_factor_power(noise_power) signal_power = util.dB_to_factor_power(signal_power) # noise energy is distributed over all bands, but signal is not # therefore increase SNR by number of bands signal_power *= num_bands return 1. - stats.chi2.cdf( stats.chi2.ppf(1. - pfa, 2. * n) / (1 + signal_power / noise_power), 2. * n)
Ruby
UTF-8
632
2.828125
3
[]
no_license
class ServiceResponse def initialize(success: false, message: nil, payload: nil) @success = success @message = message @wrapped_object = payload end def success? @success end def message @message end def unwrap @wrapped_object end def self.success ServiceResponse.new(success: true) end def self.success_with_payload(payload) ServiceResponse.new(success: true, message: nil, payload: payload) end def self.error ServiceResponse.new(success: false) end def self.error_with_message(message) ServiceResponse.new(success: false, message: message) end end
SQL
UTF-8
511
2.734375
3
[]
no_license
/*------------------------------------------------------------ * Script SQLSERVER ------------------------------------------------------------*/ /*------------------------------------------------------------ -- Table: stock ------------------------------------------------------------*/ CREATE TABLE stock( id INT IDENTITY (1,1) NOT NULL , preservation INT NOT NULL , capacity INT NOT NULL , name VARCHAR (50) NOT NULL , CONSTRAINT stock_PK PRIMARY KEY (id) );
Markdown
UTF-8
3,826
2.578125
3
[]
no_license
### 彭斯:川普对炸弹邮包事件没有责任 ------------------------ <p> 【大纪元2018年10月27日讯】(大纪元记者洪梅编译报导)美国中期选举将至的关键时期,针对连日来在美国政界掀起巨大波澜的炸弹邮包事件,美国副总统 <a href="http://www.epochtimes.com/gb/tag/%E5%BD%AD%E6%96%AF.html"> 彭斯 </a> (Mike Pence)周五(10月26日)说,总统 <a href="http://www.epochtimes.com/gb/tag/%E5%B7%9D%E6%99%AE.html"> 川普 </a> 对此没有任何责任。 </p> <p> 周五,美国司法部宣布,在佛罗里达州拘捕了炸弹邮包事件嫌犯——56岁的赛亚(Cesar Altieri Sayoc)。赛亚涉嫌近日将13个含相似爆炸装置的包裹邮寄给美国民主党多位政要及其相关知名人士,包括奥巴马、希拉里、拜登(Joe Biden)等政要,大金主索罗斯(George Soros),明星支持者罗伯特‧德尼罗(Robert Di Nero)以及有线电视新闻网(CNN)。 </p> <p> 赛亚是是一名注册的共和党选民。 </p> <p> 执法部门记录显示,赛亚共有多次因违法行为被捕,涉及盗窃、殴打、欺诈、持有毒品等行为。 </p> <p> 针对此事件, <a href="http://www.epochtimes.com/gb/tag/%E5%BD%AD%E6%96%AF.html"> 彭斯 </a> 周五(10月26日)在新墨西哥州罗斯威尔的一次竞选活动中接受美国ABC新闻采访时,回答记者“是否 <a href="http://www.epochtimes.com/gb/tag/%E5%B7%9D%E6%99%AE.html"> 川普 </a> 总统要在此事件中承担一些责任”的提问时,说,“不,完全不。” </p> <p> 他随后举了一个例子,解释说,“民主党议员桑德斯(Bernie Sanders)的热情支持者在棒球场枪击共和党议员史卡利塞(Steve Scalise)时,桑德斯没有承担责任。” </p> <p> 去年6月14日在美国弗吉尼亚州亚历山德里亚的一座国会棒球训练场,一些共和党议员在进行训练时遭遇一起枪击案,造成5人受伤,包括共和党议员史卡利塞。 </p> <p> 美国媒体此前报导说,枪击者霍奇金森曾是民主党总统候选人桑德斯的热情支持者,对川普等共和党人一直持敌视态度,他在作案前曾询问是民主党人还是共和党人在棒球场内进行训练。 </p> <p> 赛亚被捕后,川普随后表示,“我们绝不能让政治暴力在美国扎根。不能让它发生。我承诺,将尽我作为总统的所有力量阻止它。” </p> <p> 他还呼吁美国人民要团结。“最重要的是,美国人必须团结。我们必须向世界表明,作为美国人,我们是以和平、爱与谐和为前提团结在一起。没有像我们国家这样的国家,每天我们都在向世界展示我们是伟大的。” </p> <p> 彭斯稍早针对此事发推文说:“我们谴责企图攻击前总统奥巴马、克林顿夫妇、CNN,以及其他人的暴力行为。此等懦弱行动是卑鄙的,在我们这个国家没有立足之地。感谢特勤局、FBI,以及地方执法部门的快速反应,要将嫌犯绳之以法。” </p> <p> 川普转发彭斯的推文,并说:“充分赞成。” </p> <p> 责任编辑:林妍 </p> <p> </p> 原文链接:http://www.epochtimes.com/gb/18/10/27/n10812391.htm ------------------------ #### [禁闻聚合首页](https://github.com/gfw-breaker/banned-news/blob/master/README.md) &nbsp;|&nbsp; [Web代理](https://github.com/gfw-breaker/open-proxy/blob/master/README.md) &nbsp;|&nbsp; [一键翻墙软件](https://github.com/gfw-breaker/nogfw/blob/master/README.md) &nbsp;|&nbsp; [《九评共产党》](https://github.com/gfw-breaker/9ping.md/blob/master/README.md#九评之一评共产党是什么) &nbsp;|&nbsp; [《解体党文化》](https://github.com/gfw-breaker/jtdwh.md/blob/master/README.md#绪论)
Java
UTF-8
1,903
2.265625
2
[]
no_license
package com.github.skp81.tkigui; import com.github.skp81.tkigui.listener.BlockClickHandler; import com.github.skp81.tkigui.listener.CommandHandler; import com.github.skp81.tkigui.listener.InventoryEventHandler; import com.github.skp81.tkigui.listener.ItemBreakHandler; import com.github.skp81.tkigui.manager.DataManager; import com.github.skp81.tkigui.manager.GUIManager; import org.bukkit.Bukkit; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; public class TkiguiPlugin extends JavaPlugin { private static TkiguiPlugin instance; private GUIManager guiManager; private DataManager dataManager; public static TkiguiPlugin getInstance(){ return instance; } public GUIManager getGUIManager(){ return guiManager; } public DataManager getDataManager(){ return dataManager; } @Override public void onEnable() { instance = this; File file = new File(getDataFolder(),"config.yml"); File dir = getDataFolder(); if(!dir.exists()) dir.mkdir(); if(!file.exists()){ saveResource("config.yml",true); }else{ reloadConfig(); } try { dataManager = new DataManager(); guiManager = new GUIManager(); dataManager.loadFile(); } catch (IOException | InvalidConfigurationException e) { e.printStackTrace(); } Bukkit.getPluginManager().registerEvents(new BlockClickHandler(),this); Bukkit.getPluginManager().registerEvents(new InventoryEventHandler(),this); Bukkit.getPluginManager().registerEvents(new ItemBreakHandler(),this); this.getCommand("tki").setExecutor(new CommandHandler()); } @Override public void onDisable() { } }
C++
UTF-8
1,446
3.453125
3
[]
no_license
// 290. Word Pattern (https://leetcode.com/problems/word-pattern/) // Author: Hritik Gupta class Solution { public: vector<string> split(string str){ vector<string> words; string curr = ""; for(int i=0; i<str.size(); i++){ if(str[i] == ' '){ words.push_back(curr); curr = ""; } else curr += str[i]; } words.push_back(curr); return words; } bool wordPattern(string pattern, string str) { vector<string> words = split(str); if(words.size() != pattern.size()) return false; unordered_map<char, string> f_hash; unordered_map<string, char> b_hash; for(int i=0; i<pattern.size(); i++){ if(f_hash.find(pattern[i]) != f_hash.end()){ if(f_hash[pattern[i]] != words[i]) return false; } f_hash[pattern[i]] = words[i]; } for(int i=0; i<words.size(); i++){ if(b_hash.find(words[i]) != b_hash.end()){ if(b_hash[words[i]] != pattern[i]) return false; } b_hash[words[i]] = pattern[i]; } return true; } }; /* Approach Similar to 205. Isomorphic Strings M = number of words in str N = number of chars in pattern Time: O(M+N) Space: O(2*M+N) */
Java
UTF-8
11,750
2.15625
2
[]
no_license
package com.jacky8399.portablebeacons.events; import com.jacky8399.portablebeacons.BeaconEffects; import com.jacky8399.portablebeacons.Config; import com.jacky8399.portablebeacons.PortableBeacons; import com.jacky8399.portablebeacons.recipes.BeaconRecipe; import com.jacky8399.portablebeacons.recipes.RecipeManager; import com.jacky8399.portablebeacons.utils.ItemUtils; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.chat.TranslatableComponent; import net.md_5.bungee.chat.ComponentSerializer; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.PrepareAnvilEvent; import org.bukkit.event.inventory.PrepareSmithingEvent; import org.bukkit.inventory.*; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; public class RecipeEvents implements Listener { private static ItemStack showError(String error) { ItemStack stack = new ItemStack(Material.BARRIER); ItemMeta meta = stack.getItemMeta(); meta.setDisplayName(ChatColor.RED + error); stack.setItemMeta(meta); return stack; } private static ItemStack showLocalizedError(String error) { ItemStack stack = new ItemStack(Material.BARRIER); ItemMeta meta = stack.getItemMeta(); var translatable = new TranslatableComponent(error); translatable.setColor(ChatColor.RED); translatable.setItalic(false); ItemUtils.setDisplayName(meta, translatable); stack.setItemMeta(meta); return stack; } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) public void onGrindstoneItem(InventoryClickEvent e) { if (e.getClickedInventory() instanceof GrindstoneInventory || (e.getInventory() instanceof GrindstoneInventory && (e.getClick().isShiftClick() || e.getClick().isKeyboardClick()))) { if (ItemUtils.isPortableBeacon(e.getCurrentItem()) || ItemUtils.isPortableBeacon(e.getCursor())) { e.setResult(Event.Result.DENY); } } } @EventHandler public void onAnvil(PrepareAnvilEvent e) { handleRecipe(e.getView(), true, e::setResult); } @EventHandler public void onSmithing(PrepareSmithingEvent e) { handleRecipe(e.getView(), true, e::setResult); } private boolean handleRecipe(InventoryView view, boolean preview, Consumer<ItemStack> resultSetter) { Player player = (Player) view.getPlayer(); Inventory inv = view.getTopInventory(); ItemStack beacon = inv.getItem(0), right = inv.getItem(1); if (beacon == null || beacon.getAmount() != 1 || right == null || right.getType().isAir()) return false; BeaconEffects beaconEffects = ItemUtils.getEffects(beacon); if (beaconEffects == null) return false; if (Config.enchSoulboundOwnerUsageOnly && beaconEffects.soulboundOwner != null && !beaconEffects.soulboundOwner.equals(player.getUniqueId())) { resultSetter.accept(null); return false; // owner only } BeaconRecipe recipe = RecipeManager.findRecipeFor(view.getType(), beacon, right); if (recipe == null) { resultSetter.accept(null); return false; // no recipe } int cost = recipe.expCost().getCost(beacon, right); if (cost < 0) { // disallowed if (preview) { // Too expensive! if (inv instanceof AnvilInventory anvilInventory) { Bukkit.getScheduler().runTask(PortableBeacons.INSTANCE, () -> anvilInventory.setRepairCost(40)); } else { resultSetter.accept(showLocalizedError("container.repair.expensive")); return false; } } resultSetter.accept(null); return false; } var recipeOutput = preview ? recipe.getPreviewOutput(player, beacon, right) : recipe.getOutput(player, beacon, right); if (Config.debug) PortableBeacons.INSTANCE.logger.info("handleRecipe (preview: %b) for %s in %s: recipe %s, cost %d".formatted( preview, player.getName(), view.getType(), recipe.id(), cost )); if (recipeOutput == null) { resultSetter.accept(null); return false; } int level = player.getLevel(); boolean canAfford = player.getGameMode() == GameMode.CREATIVE || level >= cost; if (preview) { var result = recipeOutput.output().clone(); ItemMeta meta = result.getItemMeta(); List<String> lore = meta.hasLore() ? new ArrayList<>(ItemUtils.getRawLore(meta)) : new ArrayList<>(); int oldSize = lore.size(); if (cost > 0) { if (inv instanceof AnvilInventory anvilInventory && (cost < anvilInventory.getMaximumRepairCost() || player.getGameMode() == GameMode.CREATIVE)) { Bukkit.getScheduler().runTask(PortableBeacons.INSTANCE, () -> anvilInventory.setRepairCost(cost)); } else { var translatable = new TranslatableComponent("container.repair.cost", Integer.toString(cost)); translatable.setColor(canAfford ? ChatColor.GREEN : ChatColor.RED); translatable.setItalic(false); translatable.setBold(true); lore.add(ComponentSerializer.toString(new TextComponent())); lore.add(ComponentSerializer.toString(translatable)); } } if (Config.debug) { var recipeComponent = new ComponentBuilder("Recipe: " + recipe.id()) .color(ChatColor.GRAY).italic(false).create(); lore.add(ComponentSerializer.toString(recipeComponent)); } if (lore.size() != oldSize) { ItemUtils.setRawLore(meta, lore); result.setItemMeta(meta); } resultSetter.accept(result); } else { if (!canAfford) { // not enough experience return false; } // subtract levels if (player.getGameMode() != GameMode.CREATIVE) { player.setLevel(level - cost); } // update input items inv.setItem(0, null); inv.setItem(1, recipeOutput.right()); inv.setItem(2, null); resultSetter.accept(recipeOutput.output()); } return true; } @EventHandler(ignoreCancelled = true, priority = EventPriority.LOW) public void onAnvilClick(InventoryClickEvent e) { Inventory inv = e.getClickedInventory(); if (!(inv instanceof AnvilInventory || inv instanceof SmithingInventory) || e.getSlot() != 2) return; Player player = (Player) e.getWhoClicked(); ItemStack beacon = inv.getItem(0), right = inv.getItem(1); if (!ItemUtils.isPortableBeacon(beacon)) return; if ((right == null || right.getType().isAir()) && inv instanceof AnvilInventory anvilInventory && anvilInventory.getRenameText() != null && !anvilInventory.getRenameText().isEmpty()) return; // renaming, don't care // handle the event ourselves if (Config.debug) PortableBeacons.INSTANCE.logger.info("InventoryClick for %s in %s, click type: %s, action: %s".formatted( player.getName(), e.getClickedInventory().getType(), e.getClick(), e.getAction() )); e.setResult(Event.Result.DENY); if (!isValidClick(e)) // disallow unhandled clicks return; handleRecipe(e.getView(), false, result -> handleClick(e, result)); } private static boolean isValidClick(InventoryClickEvent e) { return true; // return switch (e.getAction()) { // case PICKUP_ALL, PICKUP_SOME, PICKUP_HALF, // PICKUP_ONE, DROP_ALL_SLOT, DROP_ONE_SLOT, // MOVE_TO_OTHER_INVENTORY, HOTBAR_MOVE_AND_READD, CLONE_STACK -> true; // default -> false; // }; } // replicate vanilla behavior private static void handleClick(InventoryClickEvent e, ItemStack result) { if (result == null) return; Inventory craftingInventory = e.getInventory(); Sound sound = switch (craftingInventory.getType()) { case ANVIL -> Sound.BLOCK_ANVIL_USE; case SMITHING -> Sound.BLOCK_SMITHING_TABLE_USE; default -> throw new IllegalStateException("Invalid inventory type" + craftingInventory.getType()); }; Player player = (Player) e.getWhoClicked(); PlayerInventory inventory = player.getInventory(); // play crafting station sound player.getWorld().playSound(player, sound, SoundCategory.BLOCKS, 1, 1); ItemStack cursor = e.getCursor(); switch (e.getClick()) { case LEFT, RIGHT -> { if (cursor == null) { player.setItemOnCursor(result); } else if (!cursor.isSimilar(result)) { player.setItemOnCursor(result); dropItemAs(player, cursor); } else { cursor.setAmount(cursor.getAmount() + result.getAmount()); player.setItemOnCursor(cursor); } } // DROP, CONTROL_DROP, default default -> dropItemAs(player, result); case SHIFT_LEFT, SHIFT_RIGHT -> { var leftOver = inventory.addItem(result); leftOver.forEach((ignored, stack) -> dropItemAs(player, stack)); } case SWAP_OFFHAND, NUMBER_KEY -> { int slot = e.getHotbarButton(); Map<Integer, ItemStack> leftOver = Map.of(); if (slot == -1) { // offhand swap leftOver = inventory.addItem(inventory.getItemInOffHand()); inventory.setItemInOffHand(result); } else { var original = inventory.getItem(slot); if (original != null) leftOver = inventory.addItem(original); inventory.setItem(slot, result); } leftOver.forEach((ignored, stack) -> dropItemAs(player, stack)); } case MIDDLE, CREATIVE -> { if (player.getGameMode() == GameMode.CREATIVE) { var clone = result.clone(); clone.setAmount(clone.getMaxStackSize()); player.setItemOnCursor(clone); } else { dropItemAs(player, result); } } } } private static void dropItemAs(Player player, ItemStack stack) { Location location = player.getEyeLocation(); player.getWorld().dropItem(location, stack, item -> { item.setThrower(player.getUniqueId()); item.setOwner(player.getUniqueId()); item.setVelocity(location.getDirection()); }); } }
Java
UTF-8
987
2.515625
3
[]
no_license
package edu.uned.missi.tfm.appiumlib.conditional.impl; import java.util.HashMap; import edu.uned.missi.tfm.appiumlib.statement.Conditional; import io.appium.java_client.MobileElement; /** * Allows to evaluate if a RadioButton/CheckBox was selected * @author Paul Pasquel * */ public class Checked extends Conditional { public Checked(Boolean denied, HashMap<String, Object> attributes) { super(denied, attributes); } @Override public boolean check() { logger.info(toString()); MobileElement e = this.element.getMElement(); if (e == null) { return false; } // if(e.getAttribute("className").contains("RadioButton")) { String value = e.getAttribute("checked"); if (denied) { return !"true".equals(value); } return "true".equals(value); } @Override public String toString() { String condition = (String)get("id") + " is checked"; if (denied) { return "But " + condition; } return condition; } }
Python
UTF-8
1,145
3.625
4
[]
no_license
'''check out https://leetcode.com/problems/zigzag-conversion/description/''' class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ self.numRows = numRows allRows = [''] * numRows down = True rowCount = 0 for charac in s: allRows[rowCount] += charac # terminal conditions if (rowCount == numRows - 1 and down): # hit the bot row down = not down rowCount = self.legitRowCount(rowCount - 1) elif (rowCount == 0 and not down): # hit the top row down = not down rowCount = self.legitRowCount(rowCount + 1) else: rowCount = self.legitRowCount(rowCount + 1) if down else self.legitRowCount(rowCount - 1) finalStr = '' for row in allRows: finalStr += row return finalStr def legitRowCount(self, rowCount): if rowCount < 0: return 0 if rowCount > self.numRows - 1: return self.numRows - 1 return rowCount
TypeScript
UTF-8
163
2.5625
3
[]
no_license
var printColors = function(...colors: string[]) { console.log(colors); } printColors("red"); printColors("red","blue"); printColors("red","green", "purple");
Shell
UTF-8
176
2.953125
3
[]
no_license
#!/usr/bin/env zsh # app related config APP="${BASH_IT}/app/*.zsh" for _bash_it_config_file in $~APP; do # shellcheck disable=SC1090 source "$_bash_it_config_file"; done
Python
UTF-8
210
3.328125
3
[]
no_license
import numpy as np t = np.array([0.,1.,2.,3.,4.,5.,6.]) print(t) print(t.ndim) print(t.shape) print(t[0],t[1],t[2]) print(t[2:5], t[-1]) # 2 : 2열 앞까지 , 3: 3열 부터 끝까지 print(t[:2], t[3:])
Python
UTF-8
441
3.15625
3
[]
no_license
import numpy as np # print(num_list.shape) def counter(num): num_list = np.zeros(num*100) for i in range(1,100): num_list[(i+1)*num-1]=1 for i in range(num-1): for j in range(1,100): num_list[(i+1)*(j+1)-1] = 0 count = 0 for i in num_list: if i:count+=1 return count print(counter(1)) print(counter(2)) print(counter(3)) print(counter(4)) print(counter(5)) print(counter(6))
Java
UTF-8
365
3.203125
3
[]
no_license
package src.chapter4; public class Exercise24 { public static void main(String[] args) { Integer i = new Integer(3); System.out.println(i); System.out.println(whichType(i)); } public static String whichType(Integer i) { return "Integer"; } public static String whichType(int i) { return "int"; } }
Python
UTF-8
4,737
3.03125
3
[]
no_license
#MACHINE LEARNING ALGORITHM(Linear Regression) import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.formula.api as sm from sklearn.model_selection import train_test_split from sklearn import metrics House_Data=pd.read_csv("House_Data.csv",parse_dates=["date"]) House_Data["date"]=House_Data["date"].astype("category") House_Data["sqft_living"].value_counts() mean=House_Data["sqft_living"].mean() sd=House_Data["sqft_living"].std() def last_list(a): if (a>mean-2*sd)&(a<mean+2*sd): return a df=House_Data["sqft_living"].apply(last_list) df.value_counts() mask=House_Data["sqft_living"]<=df.max() mask1=House_Data["sqft_living"]>=df.min() df=House_Data[mask & mask1] House_Data=df House_Data=House_Data.drop(["id","date","sqft_lot","sqft_above","sqft_basement","sqft_lot15"],axis=1) Train, Test=train_test_split(House_Data,test_size=0.35, random_state=0) model5=sm.ols('price~bedrooms+bathrooms+sqft_living+condition+floors+waterfront+view+grade+yr_built+yr_renovated+zipcode+lat+long+sqft_living15',data=Train).fit() model5.summary() prediction=model5.predict(Test) #GUI using TKINTER from tkinter import * master = Tk() master.configure(background='light green') master.title("Home Price Prediction") Label(master, text="BEDROOMS",bg='black',fg='white').grid(row=0,sticky='ew',padx=15) Label(master, text="BATHROOMS",bg='black',fg='white').grid(row=1,padx=15,sticky='ew') Label(master, text="SQFT_LIVING",bg='black',fg='white').grid(row=2,padx=15,sticky='ew') Label(master, text="CONDITION",bg='black',fg='white').grid(row=3,padx=15,sticky='ew') Label(master, text="FLOOR",bg='black',fg='white').grid(row=4,padx=15,sticky='ew') Label(master, text="WATERFRONT",bg='black',fg='white').grid(row=5,padx=15,sticky='ew') Label(master, text="VIEW",bg='black',fg='white').grid(row=6,padx=15,sticky='ew') Label(master, text="GRADE",bg='black',fg='white').grid(row=7,padx=15,sticky='ew') Label(master, text="YR_BUILT",bg='black',fg='white').grid(row=8,padx=15,sticky='ew') Label(master, text="YR_RENOVATED",bg='black',fg='white').grid(row=9,padx=15,sticky='ew') Label(master, text="ZIPCODE",bg='black',fg='white').grid(row=10,padx=15,sticky='ew') Label(master, text="LATITUDE",bg='black',fg='white').grid(row=11,padx=15,sticky='ew') Label(master, text="LONGITUDE",bg='black',fg='white').grid(row=12,padx=15,sticky='ew') Label(master, text="SQFT_LIVING15",bg='black',fg='white').grid(row=13,padx=15,sticky='ew') Label(master, text="Predicted House Value",bg='black',fg='white').grid(row=14,padx=15,sticky='ew') v1=DoubleVar() v2=DoubleVar() v3=DoubleVar() v4=DoubleVar() v5=DoubleVar() v6=DoubleVar() v7=DoubleVar() v8=DoubleVar() v9=DoubleVar() v10=DoubleVar() v11=DoubleVar() v12=DoubleVar() v13=DoubleVar() v14=DoubleVar() v15=DoubleVar() e1 = Entry(master,textvariable=v1) e2 = Entry(master,textvariable=v2) e3 = Entry(master,textvariable=v3) e4 = Entry(master,textvariable=v4) e5 = Entry(master,textvariable=v5) e6 = Entry(master,textvariable=v6) e7 = Entry(master,textvariable=v7) e8 = Entry(master,textvariable=v8) e9 = Entry(master,textvariable=v9) e10= Entry(master,textvariable=v10) e11= Entry(master,textvariable=v11) e12= Entry(master,textvariable=v12) e13= Entry(master,textvariable=v13) e14= Entry(master,textvariable=v14) e15= Entry(master,textvariable=v15) def findout(): a=v1.get() b=v2.get() c=v3.get() d=v4.get() e=v5.get() f=v6.get() g=v7.get() h=v8.get() i=v9.get() j=v10.get() k=v11.get() l=v12.get() m=v13.get() n=v14.get() entry=pd.DataFrame([[a,b,c,d,e,f,g,h,i,j,k,l,m,n]]) y_predict =model5.predict(entry) v15.set(y_predict) e1.grid(row=0, column=2,padx=20,pady=10) e2.grid(row=1, column=2,padx=20,pady=10) e3.grid(row=2, column=2,padx=20,pady=10) e4.grid(row=3, column=2,padx=20,pady=10) e5.grid(row=4, column=2,padx=20,pady= 10) e6.grid(row=5, column=2,padx=20,pady=10) e7.grid(row=6, column=2,padx=20,pady=10) e8.grid(row=7, column=2,padx=20,pady=10) e9.grid(row=8, column=2,padx=20,pady=10) e10.grid(row=9, column=2,padx=20,pady=10) e11.grid(row=10, column=2,padx=20,pady=10) e12.grid(row=11, column=2,padx=20,pady=10) e13.grid(row=12, column=2,padx=20,pady=10) e14.grid(row=13, column=2,padx=20,pady=10) e15.grid(row=14, column=2,padx=20,pady=10) b=Button(master,text="Predict",command=findout,fg='white',bg='green',bd=3,highlightthickness=4) b.grid(row=15,column=2) b2=Button(master,text="Quit",command=master.destroy,fg='white',bg='green',bd=3,highlightthickness=4) b2.grid(row=16,column=2) master.mainloop( )
C#
UTF-8
844
3.421875
3
[ "MIT" ]
permissive
#region Usings using System; using System.Linq; using JetBrains.Annotations; #endregion namespace Extend { public static partial class StringEx { /// <summary> /// Extracts all letters of the input string. /// </summary> /// <exception cref="ArgumentNullException">The string can not be null.</exception> /// <param name="str">The string to extract the letters from.</param> /// <returns>The extracted letters.</returns> [Pure] [NotNull] [PublicAPI] public static String ExtractLetters( [NotNull] this String str ) { str.ThrowIfNull( nameof(str) ); return new String( str.ToCharArray() .Where( x => x.IsLetter() ) .ToArray() ); } } }
Shell
UTF-8
647
2.578125
3
[]
no_license
# Maintainer: Simone Baratta -- Conte91 <at> gmail <dot> com pkgname=eigen-cmake-git pkgver=r2.d334930 pkgrel=1 pkgdesc="Eigen configuration files for CMake" arch=('any') license=('custom:"Beerware"') _reponame='eigen-cmake' url="http://github.com/Conte91/$_reponame" source=("git+https://github.com/Conte91/$_reponame.git") pkgver() { cd "$srcdir/$_reponame" echo "r`git rev-list --count HEAD`.`git rev-parse --short HEAD`" } package() { cd $srcdir/$_reponame install -Dm644 FindEigen.cmake $pkgdir/usr/share/cmake-3.1/Modules/FindEigen.cmake install -D -m644 LICENSE.txt "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE" } md5sums=('SKIP')
Markdown
UTF-8
674
2.65625
3
[]
no_license
# benfeitoria/notification-php-sdk Este SDK deve ser utilizado para se comunicar com o [benfeitoria/notification](https://github.com/benfeitoria/notification). ## Instalação Para registrar o SDK como dependência utilize o comando: ``` compoer require benfeitoria/notification-php-sdk ``` ## Utilização Registre o **\Benfeitoria\Notification\Services\NotificationService** em sua aplicação. Após o registro basta referenciar a classe de notificação que deseja disparar a partir do método **send()**: ```php <?php app(\Benfeitoria\Notification\Services\NotificationService::class)->send( new Benfeitoria\Notification\Notifications\Email10($data) ); ```
Python
UTF-8
1,351
3.078125
3
[]
no_license
#!/usr/bin/env python # -*- coding: utf-8 -*- ' a test module ' __author__ = 'FrancisD' import time class Funnel(object): def __init__(self, capacity, leaking_rate): self.capacity = capacity # max space self.leaking_rate = leaking_rate # quota/s self.left_quota = capacity # left space self.leaking_ts = time.time() # lastest leaking time def make_space(self): now_ts = time.time() delta_ts = now_ts - self.leaking_ts # water leaked in delta_ts time delta_quota = delta_ts * self.leaking_rate if delta_quota < 1: return self.left_quota += delta_quota self.leaking_ts = now_ts if self.left_quota > self.capacity: self.left_quota = self.capacity def watering(self, quota): self.make_space() if self.left_quota >= quota: self.left_quota -= quota return True return False funnels = {} def is_allowed(user_id, action_key, capacity, leaking_rate): key = f'{user_id}:{action_key}' funnel = funnels.get(key) if not funnel: funnel = Funnel(capacity, leaking_rate) funnels[key] = funnel print(funnels) return funnel.watering(1) for i in range(20): time.sleep(1) print(is_allowed('test','reply', 5, 0.5))
JavaScript
UTF-8
838
2.59375
3
[]
no_license
//Add //When the user click add player dispatch the action using player id const API_BASE_URL = 'http://localhost:8080'; export const addPlayer = (playerId) => dispatch => { // dispatch(authRequest()); //loading return ( fetch(`${API_BASE_URL}/team`, { method: 'PATCH',//post or patch headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ playerId }) }) // .then(res => normalizeResponseErrors(res)) .then(res => res.json()) // .then((res) => dispatch(addPlayerSuccess(res))) // .then(({authToken}) => storeAuthInfo(authToken, dispatch)) .catch(err => { // return dispatch(addPlayerError(err)); }) ); };
Shell
UTF-8
129
2.578125
3
[]
no_license
#!/usr/bin/env bash whom_variable="word" printf "HEllo, %s\n" "$whom_variable" printf "this is my arg %s %s %s\n" "$1" "$2" "$3"
Java
UTF-8
7,904
2.015625
2
[]
no_license
package org.nuxeo.nike; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.runtime.datasource.ConnectionHelper; public class AggregateValues { public static final String kLABEL_SEASONS = "Seasons"; public static final String kLABEL_EVENTS = "Events"; public static final String kLABEL_CATEGORIES = "Categories"; public static final String kLABEL_KEYWORDS = "Nike-Keywords"; public static final String kLABEL_WIDHTS = "Width Ranges"; public static final String kLABEL_HEIGHTS = "Height Ranges"; public static final String kLABEL_ALL = "All"; public static final Log log = LogFactory.getLog(AggregateValues.class); protected static final String kSQL_FOR_SEASONS = "SELECT season AS label, COUNT(season) AS count" + " FROM appcommon ac" + " LEFT JOIN proxies p ON p.targetid = ac.id" + " JOIN hierarchy h ON h.id = ac.id" + " WHERE p.targetid IS NULL " + " AND h.isversion IS NULL" + " AND season IS NOT NULL AND season <> ''" + " GROUP BY season ORDER BY season"; protected static final String kSQL_FOR_EVENTS = "SELECT event AS label, COUNT(event) AS count" + " FROM appcommon ac" + " LEFT JOIN proxies p ON p.targetid = ac.id" + " JOIN hierarchy h ON h.id = ac.id" + " WHERE p.targetid IS NULL " + " AND h.isversion IS NULL" + " AND event IS NOT NULL AND event <> ''" + " GROUP BY event ORDER BY event"; protected static final String kSQL_FOR_CATEGORIES = "SELECT category AS label, COUNT(category) AS count" + " FROM appcommon ac" + " LEFT JOIN proxies p ON p.targetid = ac.id" + " JOIN hierarchy h ON h.id = ac.id" + " WHERE p.targetid IS NULL " + " AND h.isversion IS NULL" + " AND category IS NOT NULL AND category <> ''" + " GROUP BY category ORDER BY category"; protected static final String kSQL_FOR_KEYWORDS = "SELECT item AS label, count(item) AS count" + " FROM ac_keywords as ack" + " LEFT JOIN proxies p ON p.targetid = ack.id" + " JOIN hierarchy h ON h.id = ack.id" + " WHERE p.targetid IS NULL " + " AND h.isversion IS NULL" + " AND item IS NOT NULL AND item <> ''" + " GROUP BY item ORDER BY item"; protected static final String kSQL_FOR_WIDTH_RANGE = "SELECT width_range AS label, COUNT(width_range) AS count" + " FROM appcommon ac" + " LEFT JOIN proxies p ON p.targetid = ac.id" + " JOIN hierarchy h ON h.id = ac.id" + " WHERE p.targetid IS NULL " + " AND h.isversion IS NULL" + " AND width_range IS NOT NULL" + " GROUP BY width_range ORDER BY width_range"; protected static final String kSQL_FOR_HEIGHT_RANGE = "SELECT height_range AS label, COUNT(height_range) AS count" + " FROM appcommon ac" + " LEFT JOIN proxies p ON p.targetid = ac.id" + " JOIN hierarchy h ON h.id = ac.id" + " WHERE p.targetid IS NULL " + " AND h.isversion IS NULL" + " AND width_range IS NOT NULL" + " GROUP BY height_range ORDER BY height_range"; public String run(String inStatsOnWhat, CoreSession inSession) throws SQLException { String jsonResult = ""; boolean doAll = inStatsOnWhat.equals( AggregateValues.kLABEL_ALL ); jsonResult = "{"; if(doAll || inStatsOnWhat.equals( AggregateValues.kLABEL_SEASONS )) { jsonResult += "\"seasons\":" + doTheSQLQuery(kSQL_FOR_SEASONS) + ","; } if(doAll || inStatsOnWhat.equals( AggregateValues.kLABEL_EVENTS )) { jsonResult += "\"events\":" + doTheSQLQuery(kSQL_FOR_EVENTS) + ","; } if(doAll || inStatsOnWhat.equals( AggregateValues.kLABEL_CATEGORIES )) { jsonResult += "\"categories\":" + doTheSQLQuery(kSQL_FOR_CATEGORIES) + ","; } if(doAll || inStatsOnWhat.equals( AggregateValues.kLABEL_KEYWORDS )) { jsonResult += "\"keywords\":" + doTheSQLQuery(kSQL_FOR_KEYWORDS) + ","; } if(doAll || inStatsOnWhat.equals( AggregateValues.kLABEL_WIDHTS )) { jsonResult += "\"widthRange\":" + doTheSQLQuery(kSQL_FOR_WIDTH_RANGE) + ","; } if(doAll || inStatsOnWhat.equals( AggregateValues.kLABEL_HEIGHTS )) { jsonResult += "\"heightRange\":" + doTheSQLQuery(kSQL_FOR_HEIGHT_RANGE) + ","; } jsonResult = jsonResult.substring(0, jsonResult.length() - 1); jsonResult += "}"; return jsonResult; } protected String doTheSQLQuery(String inQueryStr) throws SQLException { String jsonResult = "["; Connection co = ConnectionHelper.getConnection(null); if(co != null) { try { Statement st = co.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs = st.executeQuery(inQueryStr); while(rs.next()) { jsonResult += "{\"label\":\"" + rs.getString("label") + "\", \"count\":" + rs.getInt("count") + "},"; } rs.close(); // Remove last comma. // If there was nothing, then reduce to empty if(jsonResult.equals("[")) { jsonResult = "[]"; } else { jsonResult = jsonResult.substring(0, jsonResult.length() - 1) + "]"; } } catch (SQLException e) { // . . . throw e; } finally { co.close(); } } return jsonResult; } }
Java
UTF-8
4,105
3.015625
3
[]
no_license
package training.chessington.model.pieces; import training.chessington.model.Board; import training.chessington.model.Coordinates; import training.chessington.model.Move; import training.chessington.model.PlayerColour; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Pawn extends AbstractPiece { public Pawn(PlayerColour colour) { super(Piece.PieceType.PAWN, colour); } @Override public List<Move> getAllowedMoves(Coordinates from, Board board) { ArrayList<Move> allowedMoves = new ArrayList<>(); HashMap<String,Move> moveSet = this.setMoves(from, board); createForwardMoves(from,allowedMoves,moveSet); checkBlockedMoves(board,allowedMoves); Move moveDL = moveSet.get("Diagonal left one step"); Move moveDR = moveSet.get("Diagonal right one step"); if(checkIfMovesIsOnBoard(moveDL,7) && checkIfMovesIsOnBoard(moveDR,7)){ if(checkIfCoordinateIsOccupied(board,moveDL.getTo()) && !checkIfSameColour(this, board.get(moveDL.getTo()))){ allowedMoves.add(moveDL); } if(checkIfCoordinateIsOccupied(board,moveDR.getTo()) && !checkIfSameColour(this, board.get(moveDR.getTo()))){ allowedMoves.add(moveDR); } } return allowedMoves; } public void checkBlockedMoves(Board board, ArrayList<Move> allowedMoves){ boolean clearFMoves = false; for(Move i: allowedMoves){ if(board.get(i.getTo()) != null){ if(allowedMoves.indexOf(i) == 0){ clearFMoves = true; } else{ allowedMoves.remove(i); } } } if(clearFMoves){ allowedMoves.clear(); } } public void createForwardMoves(Coordinates from, ArrayList<Move> allowedMoves, HashMap<String, Move> moveSet){ if(from.getRow() == 6 | from.getRow() == 1){ if(checkIfMovesIsOnBoard(moveSet.get("Forward one step"), 7)){ allowedMoves.add(moveSet.get("Forward one step")); } if(checkIfMovesIsOnBoard(moveSet.get("Forward two steps"), 7)){ allowedMoves.add(moveSet.get("Forward two steps")); } } else if (from.getRow() != 0 | from.getRow() != 7){ if(checkIfMovesIsOnBoard(moveSet.get("Forward one step"), 7)){ allowedMoves.add(moveSet.get("Forward one step")); } } } public boolean checkIfMovesIsOnBoard(Move move, int max){ boolean onBoard = false; if(move.getTo().getCol() <= max && move.getTo().getCol() >= 0){ if(move.getTo().getRow() <= max && move.getTo().getRow() >= 0){ onBoard = true; } } return onBoard; } public boolean checkIfCoordinateIsOccupied(Board board, Coordinates coord){ boolean isOccupied = false; if(board.get(coord) != null){ isOccupied = true; } return isOccupied; } public boolean checkIfSameColour(Piece x, Piece y){ boolean isSameColour = true; if(x.getColour() != y.getColour()){ isSameColour = false; } return isSameColour; } public HashMap<String,Move> setMoves(Coordinates from, Board board){ HashMap<String,Move> moveSet = new HashMap<>(); int rowMultiplier = 1; if(this.colour == PlayerColour.WHITE){ rowMultiplier = -1; } moveSet.put("Forward one step", new Move(from,from.plus(rowMultiplier,0))); moveSet.put("Forward two steps", new Move(from,from.plus(2*rowMultiplier,0))); moveSet.put("Diagonal left one step", new Move(from, from.plus(rowMultiplier,-1))); moveSet.put("Diagonal right one step", new Move(from, from.plus(rowMultiplier,+1))); return moveSet; } }
Java
GB18030
941
2.453125
2
[]
no_license
package cn.kgc.dao.impl; import cn.kgc.dao.intf.PrescriptionMedicineDao; import cn.kgc.model.PrescriptionMedicine; public class PrescriptionMedicineDaoImpl extends BaseDaoImpl implements PrescriptionMedicineDao { public PrescriptionMedicineDaoImpl() { super("PrescriptionMedicineDao"); } /** * ѯҩƷϵݿСδʹõidţַĸֵ * @return * @throws Exception */ @Override public String queryMinEmptyId() throws Exception { return queryMinEmptyId(sqlMap.get("QUERY_MIN_EMPTY_ID_SQL1"),sqlMap.get("QUERY_MIN_EMPTY_ID_SQL2"),"minid"); } /** * ĴҩƷϵݿ⣬Ӱ * @param prescriptionMedicine * @return * @throws Exception */ @Override public int insert(PrescriptionMedicine prescriptionMedicine) throws Exception { return insert(sqlMap.get("INSERT_SQL"), prescriptionMedicine, 0, 3); } }
C++
UTF-8
2,654
2.546875
3
[]
no_license
#pragma once #ifndef scribble_master_h__ #define scribble_master_h__ #include <assert.h> #include <vector> #include <memory> #include <opencv2/opencv.hpp> #include "predefined_mask_manager.h" #include "scribble_types.h" #include "autofill_scribble.h" class ScribbleMaster { public: ScribbleMaster(): isReady_(false) {} // Initialize to new scribble set. // init() will automatically reset() the session. bool init(cv::Size const& imgSize); // Load predefined masks bool loadPredefinedMasks(cv::Mat const img); bool loadPredefinedMasks(std::string const& imgFileName) { return loadPredefinedMasks(cv::imread(imgFileName)); } bool setImageForAutoFill(cv::Mat const img); bool setImageForAutoFill(std::string const& imgFileName) { return setImageForAutoFill(cv::imread(imgFileName)); } // Add new positive or negative scribble. // Specify thickness and whether the scribble rendering should be anti-aliased. bool addScribble(Scribble const& scribble, ScribbleType scribbleType, ScribbleGroup scribbleGroup, int thickness, bool antialias); // Undo last scribble // This operation is slower than addScribble() since it has to rebuild the entire scribble process up-to // one step before. This trades time for memory. bool undo(); // Are there any remaning operations to undo()? bool gotAnythingToUndo() { return 0 < scribbles_.size(); } // Redo last scribble // This operation is available only when: // - A successful undo() was called // - addScribble() was not called after the undo() bool redo(); // Are there any operations to redo()? bool gotAnythingToRedo() { return 0 < redoScribbles_.size(); } // return the current number of scribbles size_t count() { return scribbles_.size(); } cv::Mat const& getPaintMask() { return paintMask_; } // Check the state of the object. // Will be false before init() and after reset() bool isReady(); // release resources and forget all scribbles. void reset(); private: bool fullRedraw(); bool incrementalDraw(); void updateAutoFillMask(cv::Mat& mask); private: bool isReady_; cv::Size imgSize_; cv::Mat autoFillInputImage_, paintMask_, unusedFillOrderMask_; typedef std::shared_ptr<ScribbleInfo> ScribbleInfoHandle; std::vector<ScribbleInfoHandle> scribbles_; std::vector<ScribbleInfoHandle> redoScribbles_; PredefinedMaskManager predefinedMaskManager_; cv::Mat currentScribbleBunchImage_, incrementalMask_, autoFillBaseMask_; cv::Mat cachedUndoMask_; bool cachedUndoMaskGood_; int firstBunchScribble_; }; #endif // scribble_master_h__
TypeScript
UTF-8
1,830
2.984375
3
[]
no_license
import {Injectable} from '@angular/core'; import {Member, TalkState} from './Member'; @Injectable({ providedIn: 'root' }) export class MemberShufflerService { constructor() { } initializeMembers(): Member[] { // todo later make the names and count variable return [ {name: 'Jo', talkState: TalkState.Waiting, id: 1}, {name: 'No', talkState: TalkState.Waiting, id: 2}, {name: 'Se', talkState: TalkState.Waiting, id: 3}, {name: 'Ol', talkState: TalkState.Waiting, id: 4}, {name: 'Ma', talkState: TalkState.Waiting, id: 5}, ]; } getRandomNumber(x: number): number { // use this when first determine random next member // let random = members[Math.floor(Math.random() * members.length)]; return Math.floor(Math.random() * x); } getNextRound(members: Member[], nextActiveMember: number): Member[] { // set previous talking to has talked const indexCurrentlySpeaking = members.findIndex(value => value.talkState === TalkState.Talking); members[indexCurrentlySpeaking].talkState = TalkState.HasTalked; // see if everyone has already talked if (members.every(value => value.talkState === TalkState.HasTalked)) { // reset ever member to waiting members.map(value => value.talkState = TalkState.Waiting); } // just take the next member which state is Waiting if (members[nextActiveMember].talkState !== TalkState.Waiting) { const nextTalkingMember = members.find(value => value.talkState === TalkState.Waiting); members.map(value => { if (value === nextTalkingMember) { value.talkState = TalkState.Talking; return value; } }); return members; } // next member is waiting members[nextActiveMember].talkState = TalkState.Talking; return members; } }
Python
UTF-8
1,189
3.453125
3
[]
no_license
#Q- To explore supervised Machine learning #importing libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd #importing dataset dataset = pd.read_csv('http://bit.ly/w-data') X = dataset.iloc[:,:-1].values Y= dataset.iloc[:,1].values #Y is dependant vector. #splitting into training & testing from sklearn.model_selection import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,Y, test_size=1/3, random_state=0) #fitting simple linear regression to the training set from sklearn.linear_model import LinearRegression regressor= LinearRegression() regressor.fit(X_train , Y_train) #predicting test set result Y_pred= regressor.predict(X_test) #Visualizing training set result plt.scatter(X_train , Y_train , color='red') plt.plot(X_train , regressor.predict(X_train), color='blue') plt.title('hours vs score (training set)') plt.xlabel('hours') plt.ylabel('score') plt.show() #Visualizing test set result plt.scatter(X_test , Y_test , color='red') plt.plot(X_train , regressor.predict(X_train), color='blue') plt.title('hours vs score (test set)') plt.xlabel('hours') plt.ylabel('score') plt.show()
C++
UTF-8
1,125
2.828125
3
[]
no_license
#include "pch.h" #include "CppUnitTest.h" #include "D:\vs项目文件\最大子段和\最大子段和\最大子段和.cpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; extern void Return_Max(int& Max, int* arr, int count); namespace UnitTest1 { TEST_CLASS(UnitTest1) { public: TEST_METHOD(TestMethod1) { int true_value = 20; int arr[] = { -2,11,-4,13,-5,-2 }; int test_value; Return_Max(test_value, arr, 6); Assert::AreEqual(true_value, test_value); } TEST_METHOD(TestMethod2) { int true_value = 0; int arr[] = { -1,-2,-3,-4,-5 }; int test_value; Return_Max(test_value, arr, 5); Assert::AreEqual(true_value, test_value); } TEST_METHOD(TestMethod3) { int true_value = 55; int arr[] = { 20,25,-10,20,-100 }; int test_value; Return_Max(test_value, arr, 5); Assert::AreEqual(true_value, test_value); } TEST_METHOD(TestMethod4) { int true_value = 10; int arr[] = { 10,-5 }; int test_value; Return_Max(test_value, arr, 2); Assert::AreEqual(true_value, test_value); } }; }
Shell
UTF-8
2,534
3.171875
3
[]
no_license
#!/bin/bash # Installation des paquets necessaires sur le serveur de deploiement # Parametrage de Cobbler # Deploiement des conf Ansible de base HYPERVISEUR_USER="pse32" # supprime flag rm -f prerequis.flag 2>/dev/null # Cree et deploie la cle SSH sur l'hyperviseur # si elle n'existe pas deja if [[ ! -e ${HOME}/.ssh/id_rsa ]]; then ssh-keygen -t rsa -f ${HOME}/.ssh/id_rsa -P "" -q echo "############# Veuillez rentrer le mot de passe pour l'hyperviseur ######################" ssh-copy-id ${HYPERVISEUR_USER}@192.168.122.1 echo "################ Merci ########################################" fi # YUM unset http_proxy unset https_proxy yum -y install cobbler cobbler-web dhcp debmirror yum -y install python2-pip gcc python-dev libxml2-dev libxslt-dev gnome-python2-devel yum -y install libvirt-python libffi libffi-devel python-devel openssl-devel # PIP export http_proxy="http://proxy.infra.dgfip:3128" export https_proxy="http://proxy.infra.dgfip:3128" pip install --upgrade pip pip install ssh-paramiko pip install pyyaml #pip install libvirt-python # Parametrage de Cobbler cp ./templates/tftpd.template /etc/cobbler cp ./templates/dhcp.template /etc/cobbler sed -i s/"manage_dhcp: 0"/"manage_dhcp: 1"/g /etc/cobbler/settings sed -i s/"pxe_just_once: 0"/"pxe_just_once: 1"/g /etc/cobbler/settings COBBLER_IP=$(ip a | grep 192.168 | awk -P '{print $2}' | awk -F'/' '{print $1}') sed -i s/"next_server: 127.0.0.1"/"next_server: ${COBBLER_IP}"/g /etc/cobbler/settings sed -i s/"server: 127.0.0.1"/"server: ${COBBLER_IP}"/g /etc/cobbler/settings cobbler sync >/dev/null 2>&1 # Lancement des services systemctl enable cobblerd systemctl enable rsyncd systemctl enable httpd systemctl enable xinetd systemctl enable tftp systemctl start cobblerd systemctl start rsyncd systemctl start httpd systemctl start xinetd systemctl start tftp # Donnees Cobbler cp ./templates/sample_perso.seed /var/lib/cobbler/kickstarts/ umount /media mount -o loop /var/tmp/ubuntu-16.04.2-server-amd64.iso /media if [[ $(cobbler distro list | grep ubuntu_server-x86_64 | wc -l) -eq 0 ]]; then cobbler import --path=/media/ --name=ubuntu_server-x86_64 fi if [[ $(cobbler profile list | grep ubuntu_server-x86_64 | wc -l) -eq 0 ]]; then cobbler profile add --name=ubuntu_server-x86_64 --distro=ubuntu_server-x86_64 --kickstart=/var/lib/cobbler/kickstarts/sample_perso.seed fi cobbler sync # Creer flag touch prerequis.flag # reboot # Installation des roles Ansible # URL cobbler web echo "https://${COBBLER_IP}/cobbler_web"
JavaScript
UTF-8
3,477
2.90625
3
[]
no_license
function Auto (marca, año, tipo, nombre, apellido, mail){ this.marca = marca; this.año = año; this.tipo = tipo; this.nombre = nombre; this.apellido = apellido; this.mail = mail; } function getPrecioPorMarca(marca){ if(marca === 'europeo'){ return 5000; } if(marca === 'americano'){ return 3500; } if(marca === 'asiatico'){ return 2000; } } function getPrecioPorAño(año){ return parseInt(año) * 0.5; } function getPrecioPorTipo(tipo){ return tipo === 'basico' ? 1000 : 2500; } function procesarDatosDelForm(){ const nombre = document.getElementById("nombre").value; const apellido = document.getElementById("apellido").value; const mail = document.getElementById("mail").value; const marca = document.getElementById("marca").value; const año = document.getElementById("año").value; const tipo = document.getElementById("radioBasico").checked ? 'basico' : 'completo'; //define si es o no "tipo basico" const auto = new Auto(marca, año, tipo, nombre, apellido, mail) //me crea un JSON const autoAGuardar = JSON.stringify(auto); //me crea string de JSON como parametro localStorage.setItem('auto1', autoAGuardar) //guarda en localStorange const cotizacion = getPrecioPorAño(año) + getPrecioPorMarca(marca) + getPrecioPorTipo(tipo); //formula de cotizacion document.getElementById('cotizacion').innerHTML = 'Tu cotizacion es de $ ' + cotizacion; } $ ('#scriptBox').mouseover (function(){ $('#scriptBox').css("color","black") $('#scriptBox').css("background","#EB8F2A") $('#scriptBox').css("font-family","verdana") }); $('#scriptBox').mouseout (function(){ $('#scriptBox').css("color","black") $('#scriptBox').css("background","white") $('#scriptBox').css("font-family","arial") }); $('#scriptBox').one("click", function(){ alert("Aguarde mientras valoramos su seguro") }); /*function enter (e) { if (event.which == 13 || event.keyCode == 13) { alert("Calculando valor de seguro"); } } function validarCampos (event){ var valor = event.target.value; if (valor ==""){ event.target.className = "form-control is-invalied" } else { event.target.className = "form-control" } validarTodosLosCampos() } function validarTodosLosCampos (){ var valormarcaCapturar = marcaCapturar.value; var valorañoCapturar = añoCapturar.value; var valortipoCapturar = tipoCapturar.value; document.getElementByClassName("button-primary").disable = !(valormarcaCapturar !=="" && valormarcaCapturar !=="" && valormarcaCapturar !=="" ) } $ (document).ready(function(){ $("save").clic(function(){ let nombre = $("#nombre").val(); let apellido = $("#apellido").val(); let mail = $("#mail").val(); let año = $("#año").val(); let marca = $("#marca").val(); let radioBasico = $("#radioBasico").val(); let radioCompleto = $("#radioCompleto").val(); let auto = { 'nombre':nombre, 'apellido':apellido, 'mail':mail, 'año':año, 'marca':marca, 'radioBasico':radioBasico, 'radioCompleto':radioCompleto } localStorage.setItem('nombre', nombre); sessionStorage.setItem('mail', mail); $('#list').append('') $('#form')[0].reset(); }); }); $ (document).ready(function(){ $.getJSON('getUser.txt',function(response){ console.log (JSON.stringify(response) ); }); });*/
Python
UTF-8
1,781
3.015625
3
[]
no_license
import tfidf import os def cleansourcecode( document ): """Replace all Non Alpha Numeric and Non space chars with a space""" # Also setting words to lower here... is this bad? return ''.join( e.lower() if e.isalnum() or e.isspace() else ' ' for e in document ) path = '/home/fox/hg/pyrapad/pyrapad/lib/gist/' documentList = os.listdir( path ) # choose a subject from the documentList and read it into subject subject = open( path + documentList[29], 'r' ).read() print subject # read in EVERY file into the documentList, also run clean code on each documentList = [ cleansourcecode( open( path + document, 'r' ).read() ) for document in documentList ] subject = cleansourcecode( subject ) documentList.append( subject ) subjectwords = subject.split() scores = {} # At this point I'm not taking into account # multiple occurances of the same word. # multiple occurances should weigh more # maybe score += score * count / 10 # # score of .20 with a word count of 3 would be # score = .20 + .20 * 3 / 10 # >>> score = 0.26 # # score of .20 with a word count of 9 would be # score = .20 + .20 * 9 / 10 # >>> score = 0.38 for word in subjectwords: #print tfidf.tfidf( word, document2, documentList ) scores[word] = tfidf.tfidf( word, subject, documentList ) # reverse sort dict by word scores # creates a list out of the dict scorelist = sorted( scores.items(), key=lambda x: x[1], reverse=True ) # from operator import itemgetter # scorelist = sorted( scores.items(), key=itemgetter(1), reverse=True ) # top keywords for subject document topsix = scorelist[0:6] # print sorted scores to the screen for score in scorelist: print score # create the url string for subject document slug = '-'.join( word[0] for word in topsix ) print slug
Java
UTF-8
1,246
2.46875
2
[]
no_license
package com.vdab.rdcar.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.io.Serializable; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; @Data @Entity public class LeasedCar implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String brand; private String model; private Long mileage; @Enumerated(EnumType.STRING) private Colour colour; @Transient private Long ageOfCar; @DateTimeFormat(pattern = "yyyy-MM-dd") private LocalDate registrationDate; public Long getAgeOfLeasedCar(){ if (registrationDate != null) { LocalDate today = LocalDate.now(); this.ageOfCar = ChronoUnit.YEARS.between(this.registrationDate, today); return ageOfCar; }else{ return ageOfCar; } } @ManyToOne private Employee employee; @OneToMany(fetch = FetchType.EAGER) private List<CarChoice> carChoices; }
Rust
UTF-8
249
3.1875
3
[]
no_license
#[derive(Debug)] struct X { a: i32 } impl Copy for X { } impl Clone for X { fn clone(&self) -> Self { *self } } fn main() { let x = X { a: 3 }; let y = x; println!("x and y value: {:?} {:?}", x, y); }
C++
UTF-8
11,300
3.1875
3
[]
no_license
#include <cmath> #include <utility> #include <cstdio> // #include "debug.h" #include "../common/cycleTimer.h" #define debug 0 void print_matrix(double **M, int r, int c) { /* for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { printf("%lf ", M[i][j]); } printf("\n"); } */ } void print_vector(double *M, int n) { for (int i = 0; i < n; i++) { printf("%lf\n", M[i]); } } void vector_matrix_multiply(double *vector, double **matrix, int n, double *out_vector) { double sum; for (int k = 0; k < n; k++) { sum = 0.0; for (int i = 0; i < n; i++) { sum += vector[i] * matrix[i][k]; } out_vector[k] = sum; } } void matrix_vector_multiply(double **matrix, double *vector, int n, double *output) { double sum; for (int row = 0; row < n; row++) { sum = 0.0; for(int col = 0; col < n; col++) { sum += vector[col] * matrix[row][col]; } output[row] = sum; } } double vector_vector_multiply(double *vector1, double *vector2, int n) { double ret = 0.0; for (int i = 0; i < n; i++) ret += vector1[i] * vector2[i]; return ret; } void matrix_transpose(double **input, double **output, int n) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) output[j][i] = input[i][j]; } // For computing Cholesky decomposition of a matrix A = LL' // - we first decompose input as L * L' // - output = L void get_cholesky(double **input, double **output, int dim) { for (int i = 0; i < dim; i++) for (int j = 0; j < dim; j++) output[i][j] = input[i][j]; for (int col = 0; col < dim; col++) { //printf("Begin new iteration: col: %d\n", col); output[col][col] = std::sqrt(output[col][col]); //printf("output[%d][%d] = sqrt(output[%d][%d])\n", col, col, col, col); //printf("Divide all elements below the diagonal element by diagonal element\n"); for (int row = col + 1; row < dim; row++) { //printf("output[%d][%d] = output[%d][%d] / output[%d][%d]\n", row, col, row, col, col, col); output[row][col] = output[row][col] / output[col][col]; } for (int col2 = col + 1; col2 < dim; col2++) { // printf("Begin new internal iteration: col2: %d\n", col2); for (int row2 = col2; row2 < dim; row2++) { output[row2][col2] = output[row2][col2] - output[row2][col] * output[col2][col]; //printf("output[%d][%d] = output[%d][%d] - output[%d][%d] * output[%d][%d]\n", row2, col2, row2, col2, row2, col, col2, col); } } //printf("Done with this iteration!\n"); } for (int row = 0; row < dim; row++) { for (int col = row + 1; col < dim; col++) { output[row][col] = 0.0; //printf("output[%d][%d] = 0\n", row, col); } } } // It computes 2 things: // - y'*inv(K)*y // - det(inv(k)) std::pair<double, double> multiply_and_get_logdeterminant(double *yt, double **X, double *y, int n) { double **L, **U; double product = 0.0; double det = 0.0; L = new double*[n]; U = new double*[n]; for (int i = 0; i < n; i++) { L[i] = new double[n]; U[i] = new double[n]; } double startime = CycleTimer::currentSeconds(); get_cholesky(X, L, n); double endtime = CycleTimer::currentSeconds(); printf("time taken by cholesky = %lf\n\n", endtime - startime); for (int i = 0; i < n; i++) { det += log(L[i][i]); } det = 2 * det; matrix_transpose(L, U, n); //MAYBE WE CAN AVOID TRANSPOSE - BY USING L[j][i] INSTEAD OF U[i][j] // Ax = b -> LUx = b. Then y is defined to be Ux double *x = new double[n]; double *temp = new double[n]; // Forward solve Ly = b for (int i = 0; i < n; i++) { temp[i] = y[i]; for (int j = 0; j < i; j++) { temp[i] -= L[i][j] * temp[j]; } temp[i] /= L[i][i]; } // Backward solve Ux = y for (int i = n - 1; i >= 0; i--) { x[i] = temp[i]; for (int j = i + 1; j < n; j++) { x[i] -= U[i][j] * x[j]; } x[i] /= U[i][i]; } // now x has the product of X^-1 * y for (int i = 0; i < n; i++) product += yt[i] * x[i]; std::pair<double, double> ret; ret = std::make_pair (product, det); for (int i = 0; i < n; i++) { delete U[i]; delete L[i]; } delete x; delete temp; delete []U; delete []L; return ret; } /* Calls to the matrix library: - subtract_vec(a, b, c, DIM) -> c = a - b (all 3 are vectors of size DIM x 1) for subtracting 2 vectors: takes 3 args - 2 inputs (both 1D double array) and fills the third input array (1D double array) - dotproduct_vec(a, b, DIM) -> return a' * b return: transpose(vector1) * vector2 [both vectors have size DIM x 1] computes the dotproduct of 2 vectors : takes 2 args - 2 inputs (both 1D double array) and outputs a double - compute_chol_and_det(K, y, n); -> returns a pair (note n is for size, as K: n x n and y: n x 1) pair.first = transpose(y) * inverse(K) * inverse(y) pair.second = determinant(K) - subtract_matrices(A, B, C, n1, n2); -> C = A - B // all 3 matrices are of size n1 x n2 ( subtraction is elementwise ) - get_outer_product(a, b, M, n); -> M = a * transpose(b) //n is telling the size basically it is vector1 * vector2.transpose() a: n x 1, b = n x 1, transpose(b): 1 x n => M will be n x n - compute_K_inverse(K, outputK, n); -> outputK = inverse(K) // so can't use cholesky, K is n x n square matrix - vector_using_cholesky(K, y, ans, n); -> ans = inverse(K) * y //can very well use cholesky K: n x n, y: n x 1, ans: n x 1 */ // For computing c = a - b (element wise vector subtraction) void subtract_vec(double *a, double *b, double *c, int DIM) { for (int i = 0; i < DIM; i++) { c[i] = a[i] - b[i]; } } // For computing ans = a' * b; double dotproduct_vec(double *a, double *b, int DIM) { double ans = 0.0; for (int i = 0; i < DIM; i++) { ans += a[i] * b[i]; } return ans; } std::pair<double, double> compute_chol_and_det(double **K, double *y, int n) { return multiply_and_get_logdeterminant(y, K, y, n); } // For computing: C = A - B (element wise matrix difference) void subtract_matrices(double **A, double **B, double **C, int n1, int n2) { for (int i = 0; i < n1; i++) { for(int j = 0; j < n2; j++) { C[i][j] = A[i][j] - B[i][j]; } } if (debug) printf("inside matrix subtraction\n"); if (debug) print_matrix(C, n1, n2); } // For computing: void get_outer_product(double *a, double *b, double **M, int n) { for (int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { M[i][j] = a[i] * b[j]; } } if (debug) printf("Inside outer_product\n"); if (debug) print_matrix(M, n, n); } // For computing: ans = inv(K) * y // Much of it is taken from the above multiply_and_determinant code void vector_Kinvy_using_cholesky(double **K, double *y, double *ans, int n){ double **L, **U; L = new double*[n]; U = new double*[n]; for (int i = 0; i < n; i++) { L[i] = new double[n]; U[i] = new double[n]; } get_cholesky(K, L, n); matrix_transpose(L, U, n); //MAYBE WE CAN AVOID TRANSPOSE - BY USING L[j][i] INSTEAD OF U[i][j] double *temp = new double[n]; // Forward solve Ly = b for (int i = 0; i < n; i++) { temp[i] = y[i]; for (int j = 0; j < i; j++) { temp[i] -= L[i][j] * temp[j]; } temp[i] /= L[i][i]; } // Backward solve Ux = y for (int i = n - 1; i >= 0; i--) { ans[i] = temp[i]; for (int j = i + 1; j < n; j++) { ans[i] -= U[i][j] * ans[j]; } ans[i] /= U[i][i]; } for (int i = 0 ; i < n ; i++) { delete L[i]; delete U[i]; } delete L; delete U; delete temp; if (debug) printf("kinvy using chol ho gaya, now see the output\n"); if (debug) print_vector(ans, n); } // For making M = I (identity matrix) void make_identity(double **M, int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) M[i][j] = 1.0; else M[i][j] = 0.0; } } } // Computes output for satisfying A * output = B, using forward substitution (columnwise, for each column of B) // INVARIANT for correct result: A is lower triangular void matrix_forward_substitution(double **A, double **B, double **output, int DIM) { for (int k = 0; k < DIM; k++) { // this is looping over columns of B matrix for (int i = 0 ; i < DIM; i++) { output[i][k] = B[i][k]; for(int j = 0; j < i; j++) { output[i][k] = output[i][k] - A[i][j] * output[j][k]; } output[i][k] = output[i][k] / A[i][i]; } } } // Computes output for satisfying A * output = B, using forward substitution (columnwise, for each column of B) // INVARIANT for correct result: A is lower triangular // This is for the case where B and output and are not square matrix. But, A has to be symmetric! void matrix_forward_substitution_rectangular(double **A, double **B, double **output, int dim1, int dim2) { //printf("In matrix forward substitution rectangular, dim1: %d, dim2: %d\n", dim1, dim2); for (int k = 0; k < dim2; k++) { // this is looping over columns of B matrix for (int i = 0; i < dim1; i++) { output[i][k] = B[i][k]; for (int j = 0; j < i; j++) { output[i][k] = output[i][k] - A[i][j] * output[j][k]; } output[i][k] = output[i][k] / A[i][i]; } } } // Computes output for satisfying A * output = B, using backward substitution (columnwise, for each column of B) // INVARIANT for correct result: A is upper triangular void matrix_backward_substitution(double **A, double **B, double **output, int DIM){ for (int k = 0; k < DIM; k++) { for (int i = DIM - 1; i >= 0 ; i--) { output[i][k] = B[i][k]; for (int j = i + 1; j < DIM; j++) { output[i][k] = output[i][k] - A[i][j] * output[j][k]; } output[i][k] = output[i][k] / A[i][i]; } } } //We need inverse(K), K = LL' => inv(K) = inv(LL') = inv(L') * inv(L) equivalent to inv(L') * (inv(L) * I) // - Now, first we have to solve inv(L) * I // - we can use Matrix_forward_substitution (MFS) // => let T = inv(L) * I <=> L * T = I (identity) // So we employ MFS with L and I to get T // // - our subsequent task is to solve: inv(L') * T // => let S = inv(L') * T <=> L' * S = T // So we employ MBS with L' and T to get S void compute_K_inverse(double **K, double **outputK, int n) { double **temp1, **T, **I, **L; temp1 = new double*[n]; T = new double*[n]; I = new double*[n]; L = new double*[n]; for (int i = 0; i < n; i++) { temp1[i] = new double[n]; T[i] = new double[n]; I[i] = new double[n]; L[i] = new double[n]; } // 1. Solving inv(L) * I using MFS // - Need identity matrix make_identity(I, n); // - Need the lower triangular matrix of K (by cholesky); result stored in L get_cholesky(K, L, n); // - Now MFS matrix_forward_substitution(L, I, T, n); // should make L * T = I // 2. Solving inv(L') * T // - Need L.transpose() matrix_transpose(L, temp1, n); // temp1 = L' // - Now MBS matrix_backward_substitution(temp1, T, outputK, n); // should make L' * outputK = T if (debug) printf("Now seeing the inv(K) matrix only\n"); if (debug) print_matrix(outputK, n, n); for (int i = 0; i < n; i++) { delete temp1[i]; delete T[i]; delete I[i]; delete L[i]; } delete []T; delete []I; delete []L; delete []temp1; } void elementwise_matrixmultiply(double ** inp1, double ** inp2, double ** output, int n1, int n2) { for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { output[i][j] = inp1[i][j] * inp2[i][j]; } } if (debug) printf("Now printing the output matrix from EEM\n"); if (debug) print_matrix(output, n1, n2); }
PHP
UTF-8
1,025
2.828125
3
[]
no_license
<?php namespace App\Auth; use Illuminate\Auth\EloquentUserProvider; use Illuminate\Contracts\Auth\UserProvider as UserProviderContract; class EmailOrNicknameUserProvider extends EloquentUserProvider implements UserProviderContract { /** * Retrieve a user by the given credentials. * * @param array $credentials * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByCredentials(array $credentials) { if (empty($credentials)) { return; } $query = $this->createModel()->newQuery(); $emailOrNickname = $credentials['email'] ?? $credentials['nickname'] ?? null; if (!$emailOrNickname) { throw new \InvalidArgumentException("Email or nickname is required and not provided."); } $query->where(function ($q) use ($emailOrNickname) { $q->where('email', $emailOrNickname)->orWhere('nickname', $emailOrNickname); }); return $query->first(); } }
Java
UTF-8
1,692
2.75
3
[]
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 Database; import businesslogic.User; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Vector; /** * * @author fauzianordlund */ public class PresentListDB { private static String createStatement() { return "select * from user"; } public static Vector createOrder(Connection con){ Statement stmt = null; ResultSet rs = null; // List<User> the_users = new ArrayList<>(); // Hashtable the_users = new Hastable; Vector vector = new Vector(); // Hashtable<Integer,User> hm=new Hashtable<Integer,User>(); try{ stmt = con.createStatement(); rs = stmt.executeQuery(createStatement()); while(rs.next()){ int id = rs.getInt("id"); String username = rs.getString("username"); String password = rs.getString("password"); String fn = rs.getString("firstName"); String ln = rs.getString("lastName"); String email = rs.getString("email"); User temp = new User(id,username,password,fn,ln,email); // hm.put(id, temp); vector.add(temp); } return vector; }catch (SQLException ex) { System.out.println(ex); return null; } } }
Java
UTF-8
1,018
2.34375
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 com.gpms.pojo; /** * * @author Developer */ public class EventModel { private int eventid; private String eventdescription; public EventModel() { } public EventModel(int eventid, String eventdescription) { this.eventid = eventid; this.eventdescription = eventdescription; } public int getEventid() { return eventid; } public void setEventid(int eventid) { this.eventid = eventid; } public String getEventdescription() { return eventdescription; } public void setEventdescription(String eventdescription) { this.eventdescription = eventdescription; } @Override public String toString() { return "EventModel{" + "eventid=" + eventid + ", eventdescription=" + eventdescription + '}'; } }
JavaScript
UTF-8
1,916
2.828125
3
[]
no_license
document.addEventListener("DOMContentLoaded", event => { const app=firebase.app(); console.log(app); const db=firebase.firestore(); const postsList=document.querySelector('#posts-list'); const postForm=document.querySelector("#makePostsForm"); function renderPost(doc) { let li=document.createElement('li'); let title=document.createElement('span'); let to=document.createElement('span'); let cross=document.createElement('div'); li.setAttribute('data-id',doc.id); title.textContent=doc.data().title; to.textContent=doc.data().to; cross.textContent='x'; li.appendChild(title); li.appendChild(to); li.appendChild(cross); postsList.appendChild(li); cross.addEventListener('click',(e) => { e.stopPropagation(); let id=e.target.parentElement.getAttribute('data-id'); db.collection('posts').doc('id').delete(); }) } db.collection('posts').get().then( (snapshot)=>{ //console.log(snapshot); snapshot.docs.forEach(doc =>{ console.log(doc.data()); renderPost(doc); }) }); function googleLogin() { const provider= new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider) .then(result =>{ const user=result.user; document.write('<h1> Hello '+result.user.displayName+" </h1>"); console.log(user); }) .catch(console.log); return; } postForm.addEventListener('submit', (e) => { e.preventDefault(); db.collection('posts').add({ title:postForm.title.value, to:postForm.to.value }) postForm.title.value=''; postForm.to.value=''; }) })
Rust
UTF-8
2,728
3.078125
3
[]
no_license
#!/usr/bin/env rust-script //! ```cargo //! [package] //! edition = "2021" //! //! [dependencies] //! pathfinding = "4.2" //! ``` use std::{collections::HashSet, hash::Hash}; use pathfinding::prelude::astar; fn parse_input(input: &str) -> i32 { input.trim().parse().unwrap() } fn is_wall(seed: i32, pos: (i32, i32)) -> bool { let (x, y) = pos; let num = x * x + 3 * x + 2 * x * y + y + y * y + seed; num.count_ones() % 2 == 1 } fn get_adjacent(seed: i32, pos: (i32, i32)) -> Vec<(i32, i32)> { let (x, y) = pos; let mut adjacent = Vec::with_capacity(4); if x > 0 && !is_wall(seed, (x - 1, y)) { adjacent.push((x - 1, y)); } if !is_wall(seed, (x + 1, y)) { adjacent.push((x + 1, y)); } if y > 0 && !is_wall(seed, (x, y - 1)) { adjacent.push((x, y - 1)); } if !is_wall(seed, (x, y + 1)) { adjacent.push((x, y + 1)); } adjacent } fn manhattan_distance(from: (i32, i32), to: (i32, i32)) -> i32 { (from.0 - to.0).abs() + (from.1 - to.1).abs() } fn star1(input: &i32) -> i32 { let seed = *input; let goal = (31, 39); let (_path, length) = astar( &(1, 1), |&pos| get_adjacent(seed, pos).into_iter().map(|x| (x, 1)), |&pos| manhattan_distance(pos, goal), |&pos| pos == goal, ) .expect("no path found"); length } // Annoyingly the pathfinding library doesn't have an algorithm implemented for // (nodes reachable within n steps of a bfs), so I'll just implement it myself fn bfs_reachable<T, IT>(initial_state: &T, expand: impl Fn(&T) -> IT, steps: u32) -> usize where T: Eq + Hash + Clone, IT: IntoIterator<Item = T>, { let mut seen = HashSet::new(); let mut curr_queue = vec![initial_state.clone()]; let mut next_queue = Vec::new(); seen.insert(initial_state.clone()); for _ in 0..steps { for state in curr_queue.drain(..) { for next_state in expand(&state) { if seen.insert(next_state.clone()) { next_queue.push(next_state); } } } std::mem::swap(&mut curr_queue, &mut next_queue); } seen.len() } fn star2(input: &i32) -> usize { let seed = *input; bfs_reachable(&(1, 1), |&pos| get_adjacent(seed, pos), 50) } fn main() { let args: Vec<_> = std::env::args().collect(); let filename = args.get(1).map(|s| &s[..]).unwrap_or("input.txt"); let input = std::fs::read_to_string(filename).unwrap(); let input = parse_input(&input); println!("{}", star1(&input)); println!("{}", star2(&input)); }
C++
UTF-8
1,167
2.953125
3
[ "BSL-1.0" ]
permissive
#pragma once class RobotConfiguration { private: float speed; float health; float robotRotation; float turretRotation; int minFireCountdown; bool canNotShootAndMove; public: RobotConfiguration(): RobotConfiguration(0, 0, 0, 0, 0, true) {} RobotConfiguration(float speed, float health, float robotRotation, float turretRotation, int minFireCountdown, bool canNotShootAndMove): speed(speed), health(health), robotRotation(robotRotation), turretRotation(turretRotation), minFireCountdown(minFireCountdown), canNotShootAndMove(canNotShootAndMove) {} float getSpeed() { return speed; } float getHealth() { return health; } float getRobotRotation() { return robotRotation; } float getTurretRotation() { return turretRotation; } int getMinFireCountdown() { return minFireCountdown; } bool canShootAndMove() { return !canNotShootAndMove; } };
Java
UTF-8
260
2.9375
3
[]
no_license
package ru.progwards.java1.lessons.bigints; public class IntInteger extends AbsInteger { String base; public IntInteger(int value){ base = Integer.toString(value); } @Override public String toString(){ return base; } }
Markdown
UTF-8
304
2.78125
3
[ "MIT" ]
permissive
# Calculator This is calculator with simple interface and supporting only basic math operations, written on JavaScript. The main idea here is the backend logic. It is entirely my concept and it works well. Adding new type of operations is easy, but this is not a goal for me. <br> <img src="a.png">
C#
UTF-8
3,941
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TB_QuestGame { /// <summary> /// static class to hold key/value pairs for menu options /// </summary> public static class ActionMenu { public enum CurrentMenu { MissionIntro, InitializeMission, MainMenu, AdminMenu, ManageInventory, ProspectorInfo, NpcMenu } public static CurrentMenu currentMenu = CurrentMenu.MainMenu; public static Menu GameIntro = new Menu() { MenuName = "GameIntro", MenuTitle = "", MenuChoices = new Dictionary<char, ProspectorAction>() { { ' ', ProspectorAction.None } } }; public static Menu InitializeMission = new Menu() { MenuName = "InitializeAdventure", MenuTitle = "Initialize Mission", MenuChoices = new Dictionary<char, ProspectorAction>() { { '1', ProspectorAction.Exit } } }; public static Menu MainMenu = new Menu() { MenuName = "MainMenu", MenuTitle = "Main Menu", MenuChoices = new Dictionary<char, ProspectorAction>() { {'1', ProspectorAction.PlayerInfoMenu}, {'2', ProspectorAction.LookAround}, {'3', ProspectorAction.Travel}, {'4', ProspectorAction.PickUpItem}, {'5', ProspectorAction.ManageInventory}, {'6', ProspectorAction.Shop}, {'7', ProspectorAction.Interact}, {'8', ProspectorAction.AdminMenu}, {'0', ProspectorAction.Exit} } }; public static Menu AdminMenu = new Menu() { MenuName = "AdminMenu", MenuTitle = "Admin Menu", MenuChoices = new Dictionary<char, ProspectorAction>() { { '1', ProspectorAction.ListDestinations }, { '2', ProspectorAction.ListItems}, { '3', ProspectorAction.ListNonPlayableCharacters}, { '0', ProspectorAction.ReturnToMainMenu } } }; public static Menu useItem = new Menu() { MenuName = "ManageInventory", MenuTitle = "Manage Inventory", MenuChoices = new Dictionary<char, ProspectorAction>() { { '1', ProspectorAction.PutDownItem }, { '2', ProspectorAction.ConsumeItem}, { '3', ProspectorAction.WieldItem}, { '0', ProspectorAction.ReturnToMainMenu } } }; public static Menu ProspectorInfo = new Menu() { MenuName = "ProspectorInfo", MenuTitle = "Player Info", MenuChoices = new Dictionary<char, ProspectorAction>() { { '1', ProspectorAction.ProspectorInfo }, { '2', ProspectorAction.EditAccount}, { '3', ProspectorAction.ProspectorLocationsVisited}, { '0', ProspectorAction.ReturnToMainMenu } } }; public static Menu NpcMenu = new Menu() { MenuName = "NpcMenu", MenuTitle = "NPC Menu", MenuChoices = new Dictionary<char, ProspectorAction>() { { '1', ProspectorAction.TalkTo }, { '2', ProspectorAction.SellTo }, { '3', ProspectorAction.LookAt }, { '0', ProspectorAction.ReturnToMainMenu } } }; } }
C#
UTF-8
723
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; namespace SonosWp8 { public class ServiceFactory { private static readonly IDictionary<Type, Func<object>> Registrations = new Dictionary<Type, Func<object>>(); public static void Register<T, TR>(Func<TR> creator) where TR : class, T { Registrations[typeof (T)] = creator; } public static T Get<T>() { Func<object> creator; if (Registrations.TryGetValue(typeof (T), out creator)) return (T) creator(); Debug.WriteLine("ServiceFactory: No Type defined for: " + typeof (T)); return default(T); } } }
TypeScript
UTF-8
1,322
2.53125
3
[]
no_license
import { sign } from 'jsonwebtoken' import { IResponseUserModel } from '@modules/users/infra/schemas/user' import AppError from '@shared/errors/app-error' import IUserRepository from '@modules/users/infra/repositories/protocols/i-user-repository' import IBcryptAdapter from '@shared/infra/adapters/protocols/i-bcrypt-adapter' interface IResponse { user: IResponseUserModel token: string } export class AuthenticationService { constructor ( private readonly usersRepository: IUserRepository, private readonly bcryptAdapter: IBcryptAdapter) {} async execute (body: any): Promise<IResponse> { const requiredFields = ['email', 'password'] for (const field of requiredFields) { if (!body[field]) { throw new AppError(`Missing param: ${field}`) } } const user = await this.usersRepository.findByEmail(body.email) if (!user) { throw new AppError('Invalid credentials', 401) } const passwordIsValid = await this.bcryptAdapter.compare(body.password, user.password) if (!passwordIsValid) { throw new AppError('Invalid credentials', 401) } const userId = user._id.toString() const token = sign({ uid: userId }, 'd2efc1f9e9409e902919b3dbe6ccbeaa', { subject: userId, expiresIn: '30d' }) return { user, token } } }
Java
UTF-8
697
1.953125
2
[]
no_license
package com.turbid.basicapi.entity.shop.commodity; import com.turbid.basicapi.tools.CodeLib; import lombok.Data; /** * 商品类 */ @Data public class Commodity { private static final String TABLE_CODE= "commodity"; //商品编号 private String code; public String getCode() { if (null==code) { return CodeLib.getCode(TABLE_CODE); } return code; } //分类编号 private String cc_code; //商品名称 private String name; //商品标题 private String title; //商品价格 private Double price; //商品图片 private String image; //商品图片组 private String fg_code; }
Python
UTF-8
430
3.046875
3
[]
no_license
#!/usr/bin/env python #coding=utf-8 from __future__ import print_function import random def apple(): print("您選擇了蘋果") def orange(): print("您選擇了橘子") def banana(): print("您選擇了香蕉") def default(): print("沒有您選擇的") case = "apple" switch = { 'apple' : apple, 'orange' : orange, 'banana' : banana, } switch.get(case, default)() switch.get("coffee", default)()
C#
UTF-8
592
2.515625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Text; namespace FriendlyRAT.Core.Windows { using System.ComponentModel; using System.Drawing; internal static class CursorManager { public static Point GetCursor() { if (Native.GetCursorPos(out var pos)) return new Point(pos.X, pos.Y); throw new Win32Exception(); } public static void SetCursor(Point point) { if (!Native.SetCursorPos(point.X, point.Y)) throw new Win32Exception(); } } }
Markdown
UTF-8
8,099
3.015625
3
[ "BSD-3-Clause" ]
permissive
<a id="tags_8c"></a> # File tags.c ![][C++] **Location**: `examples/tags.c` Advanced example of PicoTest test filter, implements a primitive tagging feature for test filtering. ```cpp #include <stdio.h> #include <picotest.h> /* Custom test filter function declaration. */ PicoTestFilterProc matchTag; #undef PICOTEST_FILTER #define PICOTEST_FILTER matchTag /* Tags for test filtering */ typedef struct TestTags { PicoTestProc *test; const char *tags[10]; } TestTags; TestTags taggedTests[]; /* * Test filter function. **cond** is a tag name, optionally prefixed by '!' for * negation. * * Positive tagging, e.g. "tagname": * - Test suites tagged "tagname" will run with all their subtests * (PICOTEST_FILTER_PASS). * - Test suites not tagged "tagname" won't run but will propagate the filter to * their subtests (PICOTEST_FILTER_SKIP_PROPAGATE). * * Negative tagging, e.g. "!tagname": * - Test suites tagged "tagname" won't run but will propagate the filter * to their subtests (PICOTEST_FILTER_SKIP_PROPAGATE). * - Test suites not tagged "tagname" will run and will propagate the filter to * their subtests (PICOTEST_FILTER_PASS_PROPAGATE). */ PicoTestFilterResult matchTag(PicoTestProc *test, const char *testName, const char *cond) { TestTags *taggedTest; const char **tag; int negate = (cond[0] == '!'); if (negate) cond++; /* First find test in tagged tests. */ for (taggedTest = taggedTests; taggedTest->test; taggedTest++) { if (taggedTest->test != test) continue; /* Then find **cond** in tag list. */ for (tag = taggedTest->tags; *tag; tag++) { if (strcmp(*tag, cond) == 0) { /* Found. */ return (negate ? PICOTEST_FILTER_SKIP_PROPAGATE : PICOTEST_FILTER_PASS); } } break; } /* Not found. */ return (negate ? PICOTEST_FILTER_PASS_PROPAGATE : PICOTEST_FILTER_SKIP_PROPAGATE); } /* Hooks */ PicoTestCaseEnterProc logCaseEnter; PicoTestCaseLeaveProc logCaseLeave; PicoTestSuiteEnterProc logSuiteEnter; PicoTestSuiteLeaveProc logSuiteLeave; #undef PICOTEST_CASE_ENTER #undef PICOTEST_CASE_LEAVE #undef PICOTEST_SUITE_ENTER #undef PICOTEST_SUITE_LEAVE #define PICOTEST_CASE_ENTER logCaseEnter #define PICOTEST_CASE_LEAVE logCaseLeave #define PICOTEST_SUITE_ENTER logSuiteEnter #define PICOTEST_SUITE_LEAVE logSuiteLeave int level = 0; void indent(int level) { while (level--) printf(" "); } void logCaseEnter(const char *name) { indent(level++); printf("running test case %s\n", name); } void logCaseLeave(const char *name, int fail) { level--; } void logSuiteEnter(const char *name, int nb) { indent(level++); printf("running test suite %s\n", name); } void logSuiteLeave(const char *name, int nb, int fail) { level--; } /* Main test suite */ #include "mainSuite.inc" /* Tagged tests */ TestTags taggedTests[] = { {testCase1, {"tag1", "tag4", NULL}}, {testCase2, {"tag2", NULL}}, {subSuite, {"tag3", NULL}}, {testCase4, {"tag4", NULL}}, {NULL} }; void main() { /* * Run all tests in order: * * running test suite mainSuite * running test case testCase1 * running test case testCase2 * running test suite subSuite * running test case testCase4 * running test case testCase5 * running test case testCase3 */ printf("Run all tests:\n"); mainSuite(NULL); printf("\n"); /* * Run tests tagged "tag3": * * running test suite subSuite * running test case testCase4 * running test case testCase5 */ printf("Run tests tagged \"tag3\":\n"); mainSuite("tag3"); printf("\n"); /* * Run tests not tagged "tag4": * running test suite mainSuite * running test case testCase2 * running test suite subSuite * running test case testCase5 * running test case testCase3 */ printf("Run tests not tagged \"tag4\":\n"); mainSuite("!tag4"); printf("\n"); } ``` ## Source ```cpp #include <stdio.h> #include <picotest.h> /* Custom test filter function declaration. */ PicoTestFilterProc matchTag; #undef PICOTEST_FILTER #define PICOTEST_FILTER matchTag /* Tags for test filtering */ typedef struct TestTags { PicoTestProc *test; const char *tags[10]; } TestTags; TestTags taggedTests[]; /* * Test filter function. **cond** is a tag name, optionally prefixed by '!' for * negation. * * Positive tagging, e.g. "tagname": * - Test suites tagged "tagname" will run with all their subtests * (PICOTEST_FILTER_PASS). * - Test suites not tagged "tagname" won't run but will propagate the filter to * their subtests (PICOTEST_FILTER_SKIP_PROPAGATE). * * Negative tagging, e.g. "!tagname": * - Test suites tagged "tagname" won't run but will propagate the filter * to their subtests (PICOTEST_FILTER_SKIP_PROPAGATE). * - Test suites not tagged "tagname" will run and will propagate the filter to * their subtests (PICOTEST_FILTER_PASS_PROPAGATE). */ PicoTestFilterResult matchTag(PicoTestProc *test, const char *testName, const char *cond) { TestTags *taggedTest; const char **tag; int negate = (cond[0] == '!'); if (negate) cond++; /* First find test in tagged tests. */ for (taggedTest = taggedTests; taggedTest->test; taggedTest++) { if (taggedTest->test != test) continue; /* Then find **cond** in tag list. */ for (tag = taggedTest->tags; *tag; tag++) { if (strcmp(*tag, cond) == 0) { /* Found. */ return (negate ? PICOTEST_FILTER_SKIP_PROPAGATE : PICOTEST_FILTER_PASS); } } break; } /* Not found. */ return (negate ? PICOTEST_FILTER_PASS_PROPAGATE : PICOTEST_FILTER_SKIP_PROPAGATE); } /* Hooks */ PicoTestCaseEnterProc logCaseEnter; PicoTestCaseLeaveProc logCaseLeave; PicoTestSuiteEnterProc logSuiteEnter; PicoTestSuiteLeaveProc logSuiteLeave; #undef PICOTEST_CASE_ENTER #undef PICOTEST_CASE_LEAVE #undef PICOTEST_SUITE_ENTER #undef PICOTEST_SUITE_LEAVE #define PICOTEST_CASE_ENTER logCaseEnter #define PICOTEST_CASE_LEAVE logCaseLeave #define PICOTEST_SUITE_ENTER logSuiteEnter #define PICOTEST_SUITE_LEAVE logSuiteLeave int level = 0; void indent(int level) { while (level--) printf(" "); } void logCaseEnter(const char *name) { indent(level++); printf("running test case %s\n", name); } void logCaseLeave(const char *name, int fail) { level--; } void logSuiteEnter(const char *name, int nb) { indent(level++); printf("running test suite %s\n", name); } void logSuiteLeave(const char *name, int nb, int fail) { level--; } /* Main test suite */ #include "mainSuite.inc" /* Tagged tests */ TestTags taggedTests[] = { {testCase1, {"tag1", "tag4", NULL}}, {testCase2, {"tag2", NULL}}, {subSuite, {"tag3", NULL}}, {testCase4, {"tag4", NULL}}, {NULL} }; void main() { /* * Run all tests in order: * * running test suite mainSuite * running test case testCase1 * running test case testCase2 * running test suite subSuite * running test case testCase4 * running test case testCase5 * running test case testCase3 */ printf("Run all tests:\n"); mainSuite(NULL); printf("\n"); /* * Run tests tagged "tag3": * * running test suite subSuite * running test case testCase4 * running test case testCase5 */ printf("Run tests tagged \"tag3\":\n"); mainSuite("tag3"); printf("\n"); /* * Run tests not tagged "tag4": * running test suite mainSuite * running test case testCase2 * running test suite subSuite * running test case testCase5 * running test case testCase3 */ printf("Run tests not tagged \"tag4\":\n"); mainSuite("!tag4"); printf("\n"); } ``` [C++]: https://img.shields.io/badge/language-C%2B%2B-blue (C++) [public]: https://img.shields.io/badge/-public-brightgreen (public)
Java
UTF-8
854
3.296875
3
[]
no_license
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; int sum = 0; ListNode dummyHead = new ListNode(0); ListNode current = dummyHead; while(l1 != null || l2 != null) { int val1 = (l1 == null) ? 0 : l1.val; int val2 = (l2 == null) ? 0 : l2.val; sum = val1 + val2 + carry; carry = sum / 10; current.next = new ListNode(sum % 10); current = current.next; if(l1 != null)l1 = l1.next; if(l2 != null)l2 = l2.next; } if(carry != 0)current.next = new ListNode(1); return dummyHead.next; } }
C++
GB18030
576
3.625
4
[]
no_license
//עָ÷while÷ֱҵΪֹ //չҲɰǷΪżж϶չΪκ void ReorderOddEven(int *pData, unsigned int length) { if(pData == NULL || length <= 0) return; int *pBegin = pData; int *pEnd = pData + length - 1; while(pBegin < pEnd) { while(pBegin < pEnd && (*pBegin & 0x1) != 0) pBegin++; while(pBegin < pEnd && (*pEnd & 0x1) == 0) pEnd--; if(pBegin < pEnd) { int tmp = *pBegin; *pBegin = *pEnd; *pEnd = tmp; } } }
Markdown
UTF-8
357
2.609375
3
[ "MIT" ]
permissive
# One Page Portfolio Site A single web page portfolio site. Created as part of Udacity's FEND nanodegree. Completely responsive. Flexbox based layout. Live version via custom domain: [www.sunnymui.com](http://www.sunnymui.com) Original GitHub Pages link: [https://sunnymui.github.io/one-page-portfolio/](https://sunnymui.github.io/one-page-portfolio/)
Python
UTF-8
663
3.359375
3
[]
no_license
def choose_one(so_far, nums, squares): #print(so_far, nums) if not nums: return so_far else: for n in nums: if not so_far or so_far[-1] + n in squares: n2 = nums[::] n2.remove(n) ans = choose_one(so_far + [n], n2, squares) if ans: return ans def square_sum(rmin=1, rmax=300): squares, i = set(), 1 while i*i < rmax**2: squares.add(i*i) i += 1 return choose_one([], list(range(rmin, rmax+1)), squares) if __name__ == '__main__': print(square_sum()) # [8, 1, 15, 10, 6, 3, 13, 12, 4, 5, 11, 14, 2, 7, 9]
C#
UTF-8
4,441
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; using System.Collections.ObjectModel; using Newtonsoft.Json; using System.Net.Http; using ItemType; using favType; namespace Viasat_App { public partial class ResultsPage : ContentPage { public ObservableCollection<Parameter> parametersList = new ObservableCollection<Parameter>(); public string requestString; public string responseString; public ResultsPage(ObservableCollection<ItemModel> itemList, string title) { InitializeComponent(); ResultsListView.ItemsSource = itemList; Title = title; } //START: BUTTONS EVENTS ####################################################### private async void itemEntry_Tapped(object sender, ItemTappedEventArgs e) { //Creating an object of type ItemModel ItemModel item = (ItemModel)((ListView)sender).SelectedItem; ((ListView)sender).SelectedItem = null; string itemId = item.id; ItemModel tempItem = new ItemModel(); tempItem.id = itemId; //item serialized to be sent as the request to the API //handles parameters not entered by the user, that way they are not included in the json string so the API doesn't have to parse and check for nulls. var jsonString = JsonConvert.SerializeObject(tempItem, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); requestString = jsonString; //Creating the http client which will provide us with the network capabilities using (var httpClient = new HttpClient()) { //request string to be sent to the API var httpContent = new StringContent(requestString, Encoding.UTF8, "application/json"); //sending the previously created request to the api and waiting for a response that will be saved in the httpResponse var // NOTE: if the api's base url changes this has to be modified. var httpResponse = await httpClient.PostAsync("http://52.13.18.254:3000/searchbyid", httpContent); //to visualize the json sent over the network comment the previous line, uncomment the next one and go to the link. //var httpResponse = await httpClient.PostAsync("https://putsreq.com/qmumqAwIq9s5RBEfbNfh", httpContent); //verifying that response is not empty if (httpResponse.Content != null) { //response into a usable var var responseContent = await httpResponse.Content.ReadAsStringAsync(); //debugging Console.WriteLine("JSON: " + requestString); Console.WriteLine("POST: " + httpContent.ToString()); Console.WriteLine("GET: " + responseContent); responseString = responseContent; } } var itemsList = JsonConvert.DeserializeObject<ObservableCollection<ItemModel>>(responseString); var itemReceived = itemsList[0]; FavModel itemViewed = new FavModel(); itemViewed.id = globals.Globals.TheUser._id; itemViewed.item_id = itemId; jsonString = JsonConvert.SerializeObject(itemViewed, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); requestString = jsonString; using (var httpClient = new HttpClient()) { var httpContent = new StringContent(requestString, Encoding.UTF8, "application/json"); var httpResponse = await httpClient.PostAsync("http://52.13.18.254:3000/itemviewed", httpContent); } globals.Globals.TheUser.recently_viewed.Add(itemReceived.id); //calling the ItemPage into the stack and passing the selected item by the user await Navigation.PushAsync(new ItemPage(itemReceived)); } } }
Python
UTF-8
4,148
3.328125
3
[]
no_license
# https://raw.githubusercontent.com/wessilfie/BasicBGMBot/master/app.py import random from flask import Flask, request from pymessenger.bot import Bot import os from web_scraper import get_restaurant_menu, get_restaurant_entree RESTAURANT_ORDER = {"CAFE_3": 0, "CLARK_KERR_CAMPUS": 1, "CROSSROADS": 2, "FOOTHILL": 3, } app = Flask(__name__) ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] VERIFY_TOKEN = os.environ['VERIFY_TOKEN'] bot = Bot (ACCESS_TOKEN) #We will receive messages that Facebook sends our bot at this endpoint @app.route("/", methods=['GET', 'POST']) def receive_message(): if request.method == 'GET': """Before allowing people to message your bot, Facebook has implemented a verify token that confirms all requests that your bot receives came from Facebook.""" token_sent = request.args.get("hub.verify_token") return verify_fb_token(token_sent) #if the request was not get, it must be POST and we can just proceed with sending a message back to user else: # get whatever message a user sent the bot output = request.get_json() for event in output['entry']: messaging = event['messaging'] for message in messaging: if message.get('message'): #Facebook Messenger ID for user so we know where to send response back to recipient_id = message['sender']['id'] if message['message'].get('text'): response_sent_text = get_message(message['message'].get('text')) send_message(recipient_id, response_sent_text) #if user sends us a GIF, photo,video, or any other non-text item if message['message'].get('attachments'): response_sent_nontext = get_message() send_message(recipient_id, response_sent_nontext) return "Message Processed" def verify_fb_token(token_sent): #take token sent by facebook and verify it matches the verify token you sent #if they match, allow the request, else return an error if token_sent == VERIFY_TOKEN: return request.args.get("hub.challenge") return 'Invalid verification token' #chooses a random message to send to the user def get_message(command): # Finds and executes the given command, filling in response default_response = "Not sure what you mean. Try *{}*.".format("help") response = None # This is where you start to implement more commands! command_parts = command.split(" ") print(command_parts) if len(command_parts) == 1: command = command_parts[0].lower() if command == "help": response = """\ Hello! Welcome to the Cal Dining Bot! Ask me about the food being served at any Berkeley Dining hall. Here are the available dining halls: - Crossroads - Clark_Kerr_campus - Foothill - Cafe_3 Here are the available meals: - Breakfast - Lunch - Dinner Here's a sample command: *crossroads dinner*\ """ if len(command_parts) == 2: restaurant, meal = command_parts restaurant = command_parts[0].upper() meal = command_parts[1][0].upper() + command_parts[1][1:].lower() if restaurant in RESTAURANT_ORDER: response = get_restaurant_menu(restaurant, meal) or "Sorry, that meal wasn't available." elif len(command_parts) == 3: restaurant, meal, entree = command_parts restaurant = command_parts[0].upper() entree = entree.upper() meal = command_parts[1][0].upper() + command_parts[1][1:].lower() if restaurant in RESTAURANT_ORDER: response = get_restaurant_entree(restaurant, meal, entree) or "Sorry, that entree wasn't available." return response or default_response #uses PyMessenger to send response to user def send_message(recipient_id, response): #sends user the text message provided via input response parameter bot.send_text_message(recipient_id, response) return "success" if __name__ == "__main__": app.run()
PHP
UTF-8
862
2.625
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Hello World</title> <link rel="stylesheet" href=""> </head> <body> <?php $conn = mysqli_connect('localhost','root',''); if (!$conn) { die ('ket noi that bai'. mysqli_connect_error()); } mysqli_select_db($conn, 'freetuts'); $sql = 'CREATE TABLE test ( id INT(6) unsigned auto_increment primary key, title VARCHAR(30) not null, content text, add_date TIMESTAMP )'; if (mysqli_query($conn, $sql)) { echo "create table completed"; $sql = 'insert into news (title, content) values (?,?)'; $stmt = $conn->prepare($sql); $stmt->bind_param('ss',$title, $content); $stmt->execute(); } else { echo "create table not completed" .mysqli_connect_error(); } mysqli_close($conn); ?> </body> </html>
Python
UTF-8
793
2.765625
3
[]
no_license
#!/usr/bin/env python3 import requests import getpass class Login: def __init__(self,user='',password=''): self.session=requests.session() self.login=dict() self.url='https://www.newbiecontest.org/forums/index.php?action=login2' self.connection(user,password) def connection(self,user='',password=''): if user == '': user=input("User : ") if password == '': password=getpass.getpass("Password : ") self.login=dict(user=user,passwrd=password) self.session.post(self.url,data=self.login) def getSession(self): return self.session def getContent(self,addr): return str(self.session.get(addr).content) def getOriginalContent(self,addr): return self.session.get(addr).content def sendAnswer(self,addr): return str(self.session.post(addr).content)
PHP
UTF-8
1,721
3.09375
3
[ "MIT" ]
permissive
<?php namespace Wookieb\ZorroDataSchema\SchemaOutline\TypeOutline; /** * @author Łukasz Kużyński "wookieb" <[email protected]> */ class ClassOutline extends AbstractTypeOutline { /** * @var ClassOutline */ private $parentClass; private $properties = array(); public function __construct($name, array $properties = array(), ClassOutline $parentClass = null) { parent::__construct($name); foreach ($properties as $property) { $this->addProperty($property); } if ($parentClass) { $this->setParentClass($parentClass); } } /** * @param PropertyOutline $property * @return self */ public function addProperty(PropertyOutline $property) { $this->properties[$property->getName()] = $property; return $this; } /** * @return array */ public function getProperties() { return $this->properties; } /** * Set type outline of parent class * * @param ClassOutline $class * @return self */ private function setParentClass(ClassOutline $class) { $this->parentClass = $class; return $this; } /** * Returns type outline of parent class * * @return ClassOutline */ public function getParentClass() { return $this->parentClass; } /** * Checks whether current class outline is a subclass of class outline with given name * * @param string $name * @return boolean */ public function isSubclassOf($name) { return $this->parentClass && ($this->parentClass->getName() === $name || $this->parentClass->isSubclassOf($name)); } }
Markdown
UTF-8
1,025
3.21875
3
[]
no_license
<html> <h1>Project: JavaScript Web Scrapping</h1> <p><strong>In this project we will understand how to manipulate JSON data, how to use the request module and how to fetch URLs, for last how to read and write a file using the fs module.</strong></p> <body> <li>Task 0: Write a script that reads and prints the content of a file.</li> <li>Task 1: Write a script that writes a string to a file.</li> <li>Task 2: Write a script that display the status code of a GET request.</li> <li>Task 3: Write a script that prints the title of a Star Wars movie where the episode number matches a given integer.</li> <li>Task 4: Write a script that prints the number of movies where the character “Wedge Antilles” is present.</li> <li>Task 5: Write a script that gets the contents of a webpage and stores it in a file.</li> <li>Task 6: Write a script that computes the number of tasks completed by user id.</li> </body> <br> <br> <footer>Made by: <strong><a href="https://github.com/DanielBaquero28">Daniel Baquero</a></strong></footer> </html>
PHP
UTF-8
236
2.625
3
[]
no_license
<?php namespace Core; class DependencyContainer { private static $instances = array(); public function __construct() { } public function getCar() { } public function getMotocycle() { } }
Java
UTF-8
264
2.203125
2
[]
no_license
package businesslogic; import auxilary.models.User; /** * Created by Anastacia on 21.03.2018. */ public interface AccountManagerInterface { public boolean signUp(User user); public boolean login(User user); public User getCurrentAccountUser(); }
C#
UTF-8
490
2.546875
3
[ "MIT" ]
permissive
using Pharmacy.BusinessLayer.Models; namespace Pharmacy.PresentationLayer.Models { public class UserViewModel { public UserViewModel(int id, string username, string pharmacyName) { Id = id; Username = username; PharmacyName = pharmacyName; } public UserViewModel(User user) : this(user.Id, user.Username, user.Pharmacy?.Name) { } public int Id { get; } public string Username { get; } public string PharmacyName { get; } } }
Markdown
UTF-8
4,381
2.78125
3
[]
no_license
## 郭文贵2021年3月11日盖特 20210311_1尊敬的战友们好!GTV可能被骇客的紧急通知! [轉載自GNews](https://gnews.org/ThreadView/53480350) 3月11号,尊敬的战友们好啊! 首先我今天,先给大家聊聊就是咱们这个G-TV的紧急事件。从昨天晚上,(G-TV)遭受了大量共匪的所谓的网络黑客攻击。最重要的事情是刚刚的几个小时前,就所有G-TV的直播有两个功能。咱们这个直播当中啊,用的是声网(平台)直播的。大概再过一两个月,咱们就可以不用声网了,就(可以)完全独立了。现在用的是声网这个平台,主要是两个功能,一个就是直播功能,一个就是信息通知功能。 昨天晚上12点前就有国内的啊,这个那个……(非常重要)的战友告诉我们,说因为最近G-TV啊,国内翻墙看G-TV的人实在太多了。而且关键他们也不知道怎么回事,就在有些城市各省啊,就轻易就能上G-TV了。网络电脑版(很容易上),手机不行,在电脑上一打G-TV,夸~就上去了,然后就能看了。这对他们来讲比较恐惧,就是制止不住啦,都要跨过墙去,要去看一看这个G-TV,了解了解郭骗子,是吧?郭3秒在干啥呢?爆料革命在干啥?新中国联邦在干啥?想想挺可怜的,14亿人,想跨过一个墙去看一个郭骗子,看我们的新中国联邦,所以他们有点恐惧、害怕。 最后听说有领导下令:不惜一切代价,共产党啊要不惜一切代价拿下,就是坚决的要制止。没办了,法估计啊,我是瞎蒙的啊,就把声网的这个信息通知系统给毁了,给黑客掉了,那什么现象了呢?就你直播的时候显示(观众)是零。你别再显示200万、10万了,什么我是英雄,什么(其它的节目)你拉一边儿倒去吧,你甭说10万、20万、100万了,什么《(我是)英雄》啊,弄得他们天天烦死了,是吧?还有几个牛节目一播就100多万,200万,像秘密翻译组简直成了他们噩梦了。他们对我们即时翻译,秘密翻译组,恐惧至极,包括班农的节目啊,还有我们路波切的节目,把他们烦死了,所以说才能显示零。这是一个! 第二个呢,在没有修复前,我们已经跟声网在联系了,没有修复前你在直播中的节目可能就录不上了,就丢了,找不着了。除非你自己你先录下来,到时候再往上传,所以说这是紧急事件。(其实)我挺开心的,我一个没有责备咱工程师,这说明了我们的价值。共产党如果不黑咱,不理咱,那说明咱这个爆料革命的利器不管用,啊斩魔刀,唰【做拔刀动作】~不管用啊。咱这斩魔刀一亮,就抽这一点儿,共产党:耶~受不了啦。你越受不了(害怕),我们越要拔开(出刀)。 所以说兄弟姐妹们啊,这就是咱们这个G-TV的力量。什么能让共匪这个样子?什么能让共匪这个样子?再一个,昨天这个G-TV公布以后,我得天呐,我的天呐,我的天呐! 我先告诉大家,SEC叫美国证监会,它没有任何资格给人定罪,没有任何资格给人判刑,千万别上当,啊。跟它之间是行政的问题,SEC到目前,跟我们合作非常愉快,我们也希望跟它合作愉快。但是从昨天调查完以后,所有的这些调查部门对我们刮目相看。觉得我们是充分考虑投资者的意见和投资者的利益和投资者的特殊情形。 五大国家,离岸国,五大离岸国没有一家不找我们联系的。大家知道哪个五大离岸国吗?大家数一数。五大离岸国,没不找我们联系的,欢迎我们去。特别是听了看了我这个直播以后,他们觉得世界上没有这么负责任的人。这么大方的人,general的人,但(其实)是(因为)他不知道咱们新中国联邦的战友情。我再告诉战友们,绝对是史无前例的,而且我们要赶在一个最最伟大的时刻,最最关键的时刻,要让它发生。大家知道是什么吗?且听下回分解。现在这个视频Getter就是关于紧急通知G-TV被黑客的事儿,下一个我给你们讲解讲解什么叫伟大的时刻! 耶,咋的咧?~
Java
UTF-8
937
3.296875
3
[]
no_license
package com.technical.google; public class MatrixFind { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int[][] matrix = {{1}}; boolean x = searchMatrix(matrix,-1); if(x==true) { System.out.println("True"); } else { System.out.println("False"); } } public static boolean searchMatrix(int[][] matrix, int target) { int row = matrix.length-1; int col = matrix[0].length-1; int cur_row = 0; int cur_col = col; while(cur_row<=row && cur_col>=0) { if(matrix[cur_row][cur_col] == target) { return true; } if( matrix[cur_row][cur_col] < target) { cur_row++; } else { cur_col--; } } return false; } }
Java
UTF-8
2,177
2.078125
2
[ "BSD-3-Clause" ]
permissive
package com.ociweb.behaviors.inprogress; import com.ociweb.gl.api.PubSubFixedTopicService; import com.ociweb.gl.api.PubSubMethodListener; import com.ociweb.gl.api.StartupListener; import com.ociweb.iot.grove.oled.oled2.OLED96x96Transducer; import com.ociweb.iot.maker.FogCommandChannel; import com.ociweb.iot.maker.FogRuntime; import com.ociweb.iot.maker.image.FogBitmap; import com.ociweb.pronghorn.pipe.ChannelReader; import static com.ociweb.iot.grove.oled.OLEDTwig.OLED_96x96_2; public class ImageBillboardBehavior implements PubSubMethodListener, StartupListener { private final PubSubFixedTopicService allFeedbackService; private final PubSubFixedTopicService imageService; private final OLED96x96Transducer display; private final FogBitmap bmp; public ImageBillboardBehavior(FogRuntime runtime, String publishTopic) { FogCommandChannel bufferChannel = runtime.newCommandChannel(); FogCommandChannel displayChannel = runtime.newCommandChannel(); display = OLED_96x96_2.newTransducer(displayChannel); this.bmp = display.newEmptyBmp(); this.allFeedbackService = bufferChannel.newPubSubService(publishTopic, 5, bmp.messageSize()); this.imageService = bufferChannel.newPubSubService("billboard/image/control", 5, bmp.messageSize()); double scale = (double) bmp.getWidth() * bmp.getHeight(); for (int x = 0; x < bmp.getWidth(); x++) { for (int y = 0; y < bmp.getHeight(); y++) { bmp.setValue(x, y, 0, ((double)(x * y) / scale)); } } } @Override public void startup() { sendTestImage(); } public boolean onAllFeedback(CharSequence charSequence, ChannelReader messageReader) { return allFeedbackService.publishTopic(writer-> writer.write(display.newBmpLayout())); } private void sendTestImage() { imageService.publishTopic( writer-> writer.write(bmp)); } public boolean onImage(CharSequence charSequence, ChannelReader ChannelReader) { ChannelReader.readInto(bmp); //display.display(display.newPreferredBmpScanner(bmp)); return true; } }
Markdown
UTF-8
6,391
3.25
3
[]
no_license
# 0217 ## NextJS - 리액트에서 SSR을 위한 도구 가장 큰 이유 : SSR을 위해서! Vue에는 NuxtJS가 있다. 그리고 Angular에는 Angular Universal 이번 자란다 2.0을 위해서 유니버셜을 공부해놔야한다. --- GraphQL : SQL처럼 data query language이다. 요청받은 구조로 데이터를 반환하는 특징이 있다. 다음과 같은 데이터가 있다면, ``` Users = [ { firstName '준우', lastName: '박' }, { firstName '여울', lastName: '박' } ] ``` 그리고 GraphQL 스키마를 다음과 같이 선언한다. ``` type User { firstName: String! lastName: String! } ``` 그리고 firstName 필드의 데이터만 사용하고 싶으면, 다음과 같은 데이터를 제공받을 필드의 이름을 HTTP Request 본문으로 보낸다. ``` { query user { firstName } } ``` 그러면, 이제 다음과같은 데이터만 받을 수 있다. ``` { "data": { "user": [ { "firstName": "준우" }, { "firstName": "여울" } ] } } ``` 이러한 GraphQL기반의 플랫폼 중에 `Apollo` 가 있다. --- Sass와 SCSS Sass의 3버전에서 등장한 것이 SCSS이다. 기존 CSS구문과 완전히 호환되도록, 새로운 구문을 도입해서 Sass의 모든 기능까지 넣은 것이 SCSS이다. 즉, CSS의 수퍼셋이다. 마치 타입스크립트와 자바스크립트같은. Sass나 SCSS는 웹에서 직접 동작할 수 없다. 즉 이러한 전처리기(Preprocessor)로 작성 후, CSS로 컴파일해야한다. --- # 0219 너무 앵귤러를 사용하기위한 타입스크립트를 사용하고 있는 건 아니었나 하는 생각을 하게되었다. `addEventListener` 콜백으로 받는 이벤트 핸들러의 타입을 어떻게 지정해줘야 할까? ``` button.addEventListener('click', ((e: MouseEvent) => { //do something }) as EventListener); ``` # 타입 단언 Type Assertions 프로그래머가 타입스크립트보다 타입에 대해 더 잘 이해하고 있는 상황을 의미한다. "타입스크립트야. 내가 타입을 알고있어. 나를 믿어봐!" ```typescript function generateStr(value: string | number, isBoolean: boolean): string { if(isBoolean) { return value.toFixed(2); // Property 'toFixed' does not exist on type 'string'.(2339) } return 'hmm... value is string'; } ``` isBoolean이 참일 경우, value는 number이고, Number.toFixed() 메소드를 상황하려는 상황이다. 하지만 타입스크립트는 `isBoolean` 이 참인지, 거짓인지를 컴파일 단계에서는 판단할 수 없기 때문에, `value` 타입이 string인지 number인지 추론할 수 없어서 에러를 반환한다. ```typescript function generateStr(value: string | number, isBoolean: boolean): string { if(isBoolean) { return (value as number).toFixed(2); } return 'hmm... value is string'; } ``` 따라서, `isBoolean` 이 참인 경우, `value` 타입이 number라고 **단언** 해야 한다. 다음과 같이 사용할 수도 있다. ```typescript function generateStr(value: string | number, isBoolean: boolean): string { if(isBoolean) { return (<number>value).toFixed(2); } return 'hmm... value is string'; } ``` --- # 자바스크립트 최적화 `<script>` 태그를 만나면, 자바스크립트가 실행되며 그 전까지 생성된 DOM에만 접근할 수 있다. 그리고 스크립트가 종료될 때 까지, DOM트리 생성이 중단된다. ( -> 그래서 HTML문서 최하단에 배치한다.) 이 때, `<head>` 태그 아래에 포함되어 있거나, HTML 내부에 `<script>` 태그가 포함되어 있더라도, `defer` 나 `async` 속성을 명시하면 HTML 파싱을 멈추지 않게 할 수 있다. ### Ref : https://ui.toast.com/fe-guide/ko_PERFORMANCE/ --- # setTimeout() 두번째 파라미터로 지정된 밀리초만큼 기다렸다가, 첫번째 파라미터로 받는 콜백을 실행하게된다. 이 때. 첫번째 시간값은 "보장된 시간"이 아니라, "최소 시간"을 의미한다. 시간 값은, `메시지가 큐에 푸시된 후의 지연시간` 을 의미한다. 즉, 대기열에 다른 메시지가 없으면 해당 지연시간 직후 메시지가 처리된다. 그러나 메시지가 있는 경우, 다른 메시지가 처리될 때까지 기다려야한다. - Task Queue - Task란, 브라우저나 그 외 구동환경(node) 에서 순차적으로 실행되어야하는 작업을 뜻한다. - ex) setTimeout 콜백, UI 이벤트 발생으로 인한 콜백 등 - Microtask Queue - Microtask란, 현재 실행되고 있는 작업 바로 다음으로 실행되어야 할 비동기 작업을 뜻한다.(higher priority) - ex) Promise 즉, Microtask Queue에 담겨있는 태스크가 먼저 콜스택으로 옮겨져서 실행되고, 그 이후에 Task Queue에 담겨있는 태스크가 콜스택으로 옮겨져서 실행된다. 그렇다면 만약 Microtask Queue의 태스크가 매우 고비용작업이라면, 뒤에서 실행되길 기다리던 Task Queue의 태스크는 하염없이 기다려야 하겠구나. Task Queue에는 클릭이나 렌더링과 같은 UI/ 사용자경험에 직결되는 콜백들이 담겨있으므로, 사용자경험을 해칠 수 있겠구나. --- # Destructuring을 자주 사용하자. ``` const turtle = { name: 'bob', legs: 4, shell: true, meal: 10, diet: 'berries' }; # BAD function showItem(item) { return `${item.name} has ${item.legs} and has shell is ${item.shell}!`; } showItem(turtle); # GOOD function showItem2( {name, legs, shell} ) { return `${name} has ${legs} and has shell is ${shell}`; } # ANOTHER function showItem3(item) { const {name, legs, shell} = item; return `${name} has ${legs} and has shell is ${shell}`; } showItem2(turtle); ``` ``` const obj = {firstName: 'junwoo', lastName: 'park'}; const {firstName, lastName} = obj; //firstName -> 'junwoo' / lastName -> 'park' const {firstName: a1, lastName:a2} = obj; //a1 -> 'junwoo' / a2 -> 'park' const {firstName: b1, lastName: b2, middleName: b3 = 'hahaha'} = obj; //b1 -> 'junwoo' / b2 -> 'park' / b3 -> 'hahaha' ``` --- # Run-to-completion 하나의 메시지 처리가 시작되면, 이 메시지 처리가 끝날 때 까지는 다른 어떤 작업도 중간에 끼어들지 못한다는 의미이다.
Java
UTF-8
750
2.75
3
[]
no_license
package com.books.notebasecore.util; import java.util.List; public class ArrayUtil { /** * 是否存在下标 * * @param arr * @param index * @return */ public static boolean isArrayIndex(String[] arr, int index) { try { String str = arr[index]; } catch (Exception e) { return false; } return true; } /** * 是否存在下标 * * @param list * @param index * @return */ public static boolean isArrayIndex(List<?> list, int index) { try { list.get(index); } catch (Exception e) { return false; } return true; } }
Java
UTF-8
794
3.390625
3
[]
no_license
@SuppressWarnings("all") public class JDKAnnotation { /* * JDK中预定义的一些注解 * @Override :检测被该注解标注的方法是否是继承自父类(接口)的 * @Deprecated:该注解标注的内容,表示已过时 * @SuppressWarnings:压制警告 * 一般传递参数all @SuppressWarnings("all") */ @Override //检测被该注解标注的方法是否是继承自父类(接口)的 public String toString() { return super.toString(); } @Deprecated //表示过时的方法,不推荐使用,但是也死可以使用的,不是强制的 public void show1(){ //过时的方法 } public void show2(){ //替代之后的方法 } public void Demov1(){ show1(); } }
JavaScript
UTF-8
1,938
2.859375
3
[]
no_license
async function perform_fetch() { var requesturl = window.location.protocol + "//" + window.location.host + "/tickets/json"; response = await fetch(requesturl); response = await response.json(); return response; } async function search_tickets() { response = await perform_fetch(); var userElement = document.getElementById("search-ticket-list"); userElement.innerHTML = ""; for(var productName in response) { // productName == Nazov produktu z ktoreho sa idu pozriet tickety var tickets = response[productName]; for(var listMember in tickets) { for(var ticketName in tickets[listMember]) { // ticketName == Nazov ticketu ktory je priradeny ku produktu ticketId = tickets[listMember][ticketName] // ticketId == Idčko ticketu z db console.log(ticketName); console.log(ticketId); userElement.innerHTML = userElement.innerHTML + "<p id=\"search-list-item\" onclick=\"select_ticket(" + ticketId + ")\">" + ticketName + "</p>\n"; } } } if (userElement.innerHTML == "") { userElement.innerHTML = userElement.innerHTML + "<p>There are no tickets related to you</p>"; } } function select_ticket(selectedTicket) { developerId = document.getElementById("ticket"); developerId.value = selectedTicket; document.getElementById("search-ticket-wrapper").style.display = "none"; } function hideSearchTicket() { var ticket = document.getElementById("search-ticket-wrapper"); var assignee = document.getElementById("search-assignee-wrapper"); if (ticket.style.display === "none") { if (assignee.style.display !== "none") { assignee.style.display = "none"; } search_tickets() ticket.style.display = "initial"; } else { ticket.style.display = "none"; } }
Java
UTF-8
5,416
1.976563
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 com.fillingstationproject.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fillingstationproject.util.RegexPattern; import java.io.Serializable; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Maneesha */ @Entity @Table(name = "payment") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Payment.findAll", query = "SELECT p FROM Payment p")}) public class Payment implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Column(name = "payno") private String payno; @Column(name = "date") private LocalDate date; // @Max(value=?) @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation @Column(name = "nettotal") @RegexPattern(regexp = "^([1-9]{1,6}.[0-9]{2})$",message = "Invalid Total Price") private BigDecimal nettotal; @Column(name = "paidtotal") @RegexPattern(regexp = "^([1-9]{1,6}.[0-9]{2})$",message = "Invalid Paid Price") private BigDecimal paidtotal; @Column(name = "totalbalance") @RegexPattern(regexp = "^([1-9]{1,6}.[0-9]{2})$",message = "Invalid Total Balance") private BigDecimal totalbalance; @Column(name = "discount") private BigDecimal discount; @Column(name = "discountprice") private BigDecimal discountprice; @JoinColumn(name = "paymenttype_id", referencedColumnName = "id") @ManyToOne(optional = false, fetch = FetchType.EAGER) private Paymenttype paymenttypeId; @JoinColumn(name = "employee_id", referencedColumnName = "id") @ManyToOne(optional = false, fetch = FetchType.EAGER) private Employee employeeId; @JoinColumn(name = "grnnote_id", referencedColumnName = "id") @ManyToOne(optional = false, fetch = FetchType.EAGER) private Grnnote grnnoteId; @OneToMany(cascade = CascadeType.ALL, mappedBy = "paymentId", fetch = FetchType.LAZY) @JsonIgnore private List<Chequepayment> chequepaymentList; public Payment() { } public Payment(Integer id) { this.id = id; } public Payment(Integer id,String payno) { this.id = id; this.payno = payno; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } public BigDecimal getNettotal() { return nettotal; } public void setNettotal(BigDecimal nettotal) { this.nettotal = nettotal; } public BigDecimal getPaidtotal() { return paidtotal; } public void setPaidtotal(BigDecimal paidtotal) { this.paidtotal = paidtotal; } public BigDecimal getTotalbalance() { return totalbalance; } public void setTotalbalance(BigDecimal totalbalance) { this.totalbalance = totalbalance; } public Paymenttype getPaymenttypeId() { return paymenttypeId; } public void setPaymenttypeId(Paymenttype paymenttypeId) { this.paymenttypeId = paymenttypeId; } public Employee getEmployeeId() { return employeeId; } public void setEmployeeId(Employee employeeId) { this.employeeId = employeeId; } public Grnnote getGrnnoteId() { return grnnoteId; } public void setGrnnoteId(Grnnote grnnoteId) { this.grnnoteId = grnnoteId; } public String getPayno() { return payno; } public void setPayno(String payno) { this.payno = payno; } @XmlTransient public List<Chequepayment> getChequepaymentList() { return chequepaymentList; } public void setChequepaymentList(List<Chequepayment> chequepaymentList) { this.chequepaymentList = chequepaymentList; } public BigDecimal getDiscount() { return discount; } public void setDiscount(BigDecimal discount) { this.discount = discount; } public BigDecimal getDiscountprice() { return discountprice; } public void setDiscountprice(BigDecimal discountprice) { this.discountprice = discountprice; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Payment)) { return false; } Payment other = (Payment) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "com.fillingstationproject.entity.Payment[ id=" + id + " ]"; } }
Java
ISO-8859-1
3,984
3.328125
3
[]
no_license
package agenda; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.Scanner; public class Agenda { ArrayList<Contacto> contactos; public Agenda() { this.contactos = new ArrayList<Contacto>(); } public boolean AddContacto(String nombre, String apellidos, String dni, String telefono) { // Letras y espacios MAX 20 carcteres Pattern pNombre = Pattern.compile("^[A-Z ?]{0,20}$", 2); // Letras y espacios MAX 30 carcteres Pattern pApellidos = Pattern.compile("^[A-Z ?]{0,30}$", 2); // 8 nmeros y 1 letra Pattern pDni = Pattern.compile("^[0-9]{8}[A-Z]{1}$", 2); // Empieza con 6 7 seguido de 8 nmeros del 0-9 Pattern pTelefono = Pattern.compile("^[67][0-9]{8}$"); final char [] letras = {'T','R','W','A','G','M','Y','F','P','D','X','B','N','J','Z','S','Q','V','H','L','C','K','E'}; boolean valido = false; // Comprobar si cumplen los filtros if (pNombre.matcher(nombre).matches() && pApellidos.matcher(apellidos).matches() && pDni.matcher(dni).matches() && pTelefono.matcher(telefono).matches()) { // Comprobar letra, DNI nmero % 23 = indice del 0-22 el cual corresponde a la letra del array de letras int indiceDni = Integer.parseInt(dni.substring(0, 8)) % 23; if ( Character.compare(letras[indiceDni], dni.charAt(8)) == 0 ) { valido = true; this.contactos.add(new Contacto(nombre, apellidos, dni, telefono)); } else System.out.println("Letra del DNI invlida"); } return valido; } public void mostrarAgenda() { System.out.println("\r*******************************************************************************"); System.out.println("* Contactos de la Agenda *"); System.out.println("*******************************************************************************"); System.out.println("* N * Nombre * Apellidos * D.N.I. * Telfono *"); System.out.println("*******************************************************************************"); this.contactos.forEach( contacto -> { String linea = "* " + (contactos.indexOf(contacto) + 1) + " * "; linea += contacto.getNombre() + " * "; linea += contacto.getApellidos() + " * "; linea += contacto.getDni() + " * "; linea += contacto.getTelefono() + " *"; System.out.println(linea); System.out.println("*******************************************************************************"); }); } public static void main(String[] args) { final int SALIR = 0; final int VER_AGENDA = 1; final int ADD_CONTACTOS = 2; Scanner sc = new Scanner(System.in); Agenda agenda = new Agenda(); boolean continuar = false; int opt = 0; do { // Pedir entrada mostrarMenu(); opt = Integer.parseInt(sc.nextLine()); switch (opt) { case SALIR: System.out.println("-- FIN --"); break; case VER_AGENDA: agenda.mostrarAgenda(); break; case ADD_CONTACTOS: do { String nombre, apellidos, dni, telefono; System.out.print("\rIntroduce el nombre (MAX length [20]): "); nombre = sc.nextLine(); System.out.print("Introduce los apellidos (MAX length [20]): "); apellidos = sc.nextLine(); System.out.print("Introduce el dni: "); dni = sc.nextLine(); System.out.print("Introduce el telefono (MAX length [9], 1er nmero 6 7): "); telefono = sc.nextLine(); if (!agenda.AddContacto(nombre, apellidos, dni, telefono)) System.out.println("Datos invlidos"); System.out.println("\r\rQuieres introducir otro? [s/N]"); if (sc.nextLine().equalsIgnoreCase("S")) continuar = true; else continuar = false; } while(continuar); break; } } while (opt != 0); } public static void mostrarMenu() { System.out.println("\r0. Salir"); System.out.println("1. Ver Agenda"); System.out.println("2. Aadir contacto/s\r"); } }
Java
UTF-8
3,489
3.453125
3
[]
no_license
import java.util.Random; import java.util.List; public class FrenchKnight extends Player{ Random rand = new Random(); int cowHeal = 40; final String castle = "The French Knight somehow found a castle to reside in. "; boolean isCastle; Cow cow; public FrenchKnight (World w, String name, Location location, int health, List<Thing> things, Thing goal){ super(w, name, location, health, things, goal); this.isCastle = false; this.cow = new Cow("cow", location, cowHeal); addThing(cow); } @Override public void play(){ boolean moved = false; Location newLocation; while (moved == false){ int r = rand.nextInt(5); switch (r){ case 0: newLocation = this.getLocation().north(); moved = move(newLocation); if (moved == true){ this.setLocation(newLocation); this.isCastle = false; } break; case 1: newLocation = this.getLocation().east(); moved = move(newLocation); if (moved == true){ this.setLocation(newLocation); this.isCastle = false; } break; case 2: newLocation = this.getLocation().south(); moved = move(newLocation); if (moved == true){ this.setLocation(newLocation); this.isCastle = false; } break; case 3: newLocation = this.getLocation().west(); moved = move(newLocation); if (moved == true){ this.setLocation(newLocation); this.isCastle = false; } break; case 4: moved = true; this.isCastle = true; break; } } } @Override public boolean move(Location newLocation){ boolean canMove = this.getLocation().isConnected(newLocation); if (canMove){ this.w.getRoom(this.getLocation()).removePlayer(this); this.w.getRoom(newLocation).addPlayer(this); } return canMove; } @Override public void interact(Player p){ if (p instanceof Human){ int r = rand.nextInt(3); int damage; String actionString = ""; switch(r){ case 0: actionString = "You approach the French Knight and ask if he can direct you to the Golden Idol. He says he already has one."; break; case 1: damage = 5; actionString = "The French Knight compares your mother to some variety of small rodent and likens your fathers scent to that of wild vegetation. You take " + damage + " damage."; p.setHealth(p.getHealth() - damage); break; case 2: damage = 20; actionString = "The French Knight throws a cow at you. You take " + damage + " damage."; p.setHealth(p.getHealth() - damage); addThing(cow); removeThing(cow); p.addThing(cow); break; } if (this.isCastle){ actionString = castle + actionString; } System.out.println(actionString); } } }
Markdown
UTF-8
806
2.640625
3
[]
no_license
# Data Serialization ## What are data serialization formats? XML, JSON, BSON, YAML, MessagePack, Protocol Buffers, Thrift and Avro. ## Resource [Big Data File Formats Demystified by Alex Woodie](https://www.datanami.com/2018/05/16/big-data-file-formats-demystified/) | Avro, Parquet and ORC [Data Serialization – Protocol Buffers vs Thrift vs Avro](https://www.bizety.com/2019/04/02/data-serialization-protocol-buffers-vs-thrift-vs-avro/) | Protocol Buffers, Thrift, Avro [An Introduction to Big Data Formats Understanding Avro, Parquet, and ORC - nexla](https://webcdn.nexla.com/n3x_ctx/uploads/2018/05/An-Introduction-to-Big-Data-Formats-Nexla.pdf) | Avro, Parquet, and ORC [AVRO vs Parquet — what to use?](https://medium.com/@minyodev/avro-vs-parquet-what-to-use-518ccbe8fb0c) | Avro, Parquet
TypeScript
UTF-8
7,060
3.765625
4
[]
no_license
// https://www.educative.io/courses/grokking-the-coding-interview/Y5zDWlVRz2p // // Needless to say that we need a maxHeap so that we can always greedily pop // out from the stack follow the given rule // The maxHeap should compare its elements in two ways: // 1. compare their frequencies // 2. if frequencies are the same, compate the sequenceNumber (the order the // element is pushed into the stack) // Thus, every time we are pushed in a new element, we need to: // 1. if it does not exist before, we need to init its sequenceNumber // 2. if it exists, increment its frequency // We push the element into the maxHeap // Every time when pop() is called, remove the root of the maxHeap. // Notice that if we repeatedly push in the same number e.g. 3, we should // store all these 3s in the maxHeap, so that we can pop out all these 3s. // In order to get the number's frequency in O(1) time, we also need a hashmap // to store each number with its frequency so far. // Notice that we don't need to update the frequency in the maxHeap when popped, // because when pushed in, the element.frequency is inited with its frequency at // that time, thus the frequency decreased by 1 each time it is popped automatically. // // Time: // - push: O(logN) (cost to push into the maxHeap) // - pop: O(logN) cost to remove the root of the maxHeap // Space: O(N) import { Heap } from 'typescript-collections' class NumElement { public number: number public freq: number public seqNum: number constructor(num: number, freq: number, seqNum: number) { this.number = num this.freq = freq this.seqNum = seqNum } compare(other: NumElement) { if (this.freq !== other.freq) { // the one with larger frequency has higher priority return this.freq - other.freq } else { // the one that comes later has higher priority return this.seqNum - other.seqNum } } } export class FrequencyStack { private maxHeap: Heap<NumElement> private freqMap: Record<number, number> private sequenceNum: number constructor() { this.sequenceNum = 0 this.maxHeap = new Heap<NumElement>((a, b) => a.compare(b)) this.freqMap = {} } push(num: number): void { if (this.freqMap[num] === undefined) { this.freqMap[num] = 0 } this.freqMap[num] += 1 this.maxHeap.add(new NumElement(num, this.freqMap[num], this.sequenceNum)) this.sequenceNum += 1 } pop(): number | undefined { const result = this.maxHeap.removeRoot() if (result !== undefined) { this.freqMap[result.number] -= 1 if (this.freqMap[result.number] === 0) { delete this.freqMap[result.number] } } return result === undefined ? undefined : (result.number as number) } } //--- r1 ---// // The pop operation follows some rule -> a priority queue, i.e. heap is needed // Define the element stored in the heap -- // value: the number's value // freq: the number's frequency when it is pushed // sequenceNum: the number's sequence number, so that we could pop out elements ordered // by the order they entered // Thus, everytime push(num) is called, we construct a new element of num and push it to the // heap; // In order to get the number's current frequency in O(1), the class need to maintain a hashmap // storing each number's current frequency. // pop() - remove the root of the maxHeap, decrease its frequency in the hashmap // Because in the element, we store the element's frequency when it enters, thus, the element's // frequency (order in the heap) got automatically updated when it is popped. // // Time: // - push: O(logN) // - pop: O(logN) // Space: O(N) class Element { public value: number public freq: number public seqId: number constructor(v: number, freq: number, seqId: number) { this.value = v this.freq = freq this.seqId = seqId } compare(other: Element): number { if (this.freq !== other.freq) { return this.freq - other.freq } else { return this.seqId - other.seqId } } } export class FrequencyStackR1 { private seq: number private freqMap: Record<number, number> private heap: Heap<Element> constructor() { this.seq = 0 this.freqMap = {} this.heap = new Heap<Element>((a, b) => a.compare(b)) } push(num: number): void { // 1. update freqMap if (this.freqMap[num] === undefined) { this.freqMap[num] = 0 } this.freqMap[num] += 1 // 2. push into the heap this.heap.add(new Element(num, this.freqMap[num], this.seq)) // 3. update sequence number this.seq += 1 } pop(): number | undefined { const top = this.heap.removeRoot() if (top !== undefined) { const topEle = top as Element this.freqMap[topEle.value] -= 1 // clear numbers that are fully popped out -- // otherwise the map will ended up to be enormously big if (this.freqMap[topEle.value] === 0) { delete this.freqMap[topEle.value] } } return top === undefined ? undefined : top.value } } //--- r2 ---// // // The element in the stack is popped out in some order -- thus, // store the element in a priority queue -- i.e. heap // The heap's order should be defined as described. We define a class Element // to store the element's value, frequency and sequenceNumber // - push: get the number's current frequency from the freqMap; // construct the Element instanstance; // push the instance into the heap; // - pop: remove the root of the heap; its frequency should be the element's current // frequency; update the freqMap; // (clean up entries with 0 frequencies in the freqMap) // NOTE that we actually stores every copy of the same letter into the heap -- we can safly // remove the root each time in pop() // // Time: // - push: O(logN) -- N is the number of elements in the stack // - pop: O(logN) // Space: O(N) class ElementR2 { private value: number private freq: number private seq: number constructor(value: number, freq: number, seq: number) { this.value = value this.freq = freq this.seq = seq } compare(other: ElementR2): number { if (this.freq !== other.freq) { return this.freq - other.freq } else { return this.seq - other.seq } } } export class FrequencyStackR2 { private freqMap: Record<number, number> private maxHeap: Heap<Element> private seq: number constructor() { this.seq = 0 this.freqMap = {} this.maxHeap = new Heap<Element>((a, b) => a.compare(b)) } push(num: number) { if (this.freqMap[num] === undefined) { this.freqMap[num] = 0 } this.freqMap[num] += 1 const newNum = new Element(num, this.freqMap[num], this.seq) this.seq += 1 this.maxHeap.add(newNum) } pop(): number | undefined { if (this.maxHeap.size() === 0) { return undefined } const top = this.maxHeap.removeRoot() top.freq -= 1 this.freqMap[top.value] = top.freq if (top.freq === 0) { delete this.freqMap[top.value] } return top.value } }
Markdown
UTF-8
3,628
3.09375
3
[]
no_license
--- title: "ICON Nodes" excerpt: "" --- This document presents what kinds of nodes are in the ICON network. Node means the computer server which participates in the blockchain protocol. All nodes keep the full or partial copy of blockchain data and execute transactions in the blocks for validation. So all nodes should be connected to the internet, and have their own address to identify themselves. ## Types of Nodes There are three types of nodes in ICON network. - **Peer nodes** can participate in the consensus protocol, so they can produce and propose a block. - **Citizen nodes** just synchronize the blockchain data and relay the transaction to the Peer node. - **Light clients** just synchronize the block headers for simple verification of transactions. ![types of nodes](types_of_nodes.png) The user and application can access (query or send transactions) these nodes through ICONex wallet or ICON SDK. They can also access the nodes using JSON RPC directly as well. ## Peer There are two types of Peer nodes, Public and Community Representative. As you see in the word "Representative", these nodes are supposed to be elected by ICONist or Community members. Details of the election are presented in [ICONSENSUS](https://icon.community/iconsensus/). Peer nodes are the essential entities of ICON network. They have roles to produce and validate the blocks, which contains transactions transmitted into ICON network. All transactions sent to ICON network are relayed or directed to Peer nodes. One of Peer nodes becomes a leader node, who has the right to propose a block on its turn. And the other Peer nodes validate the proposed block. The block is confirmed when 2/3 of Peer nodes agree on that block. Peer nodes will become a leader node in a pre-defined order, and produce one block on their turn. ### Public Representative (P-Rep) Public Representatives are the consensus nodes that produce, verify blocks and participate in network policy decisions on the ICON Network. ### Community Representative (C-Rep) Community Representatives have a role of bridging ICON Network and their own Community blockchain. They should relay the transactions and their proofs to the other blockchain. It is not decided whether C-Rep joins the consensus protocol or not. The detailed role of C-Rep will be defined after BTP (Blockchain Transfer Protocol) specification is finalized. ## Citizen Citizen nodes synchronize the blockchain data from Peer nodes. Citizen is not just a simple data replication store but verifies every block data by executing the transactions in the block. Therefore, we can trust the sanity of the block data downloaded from the Peer nodes. In addition, because Citizen does not participate in block generation, when it receives the transaction requests, Citizen relays the transaction requests to the Peer nodes. With the above two main functions, Citizen is typically deployed as a service end-point of ICON Network. Citizen answers the queries from the users, and relays transactions to the Peer nodes. It is designed that no transactions and queries are supposed to be sent to the Peer nodes directly. This architecture keeps the Peer nodes focusing on consensus, that is, producing and validating blocks. In addition, limited access to Peer nodes makes the ICON network safer from attacks. Since Citizen nodes verify the blocks and transactions, Exchanges or DApp operators are recommended to setup own Citizen nodes inside their network, rather than use publicly opened Citizen nodes outside their network. ## Light Client TBA
PHP
UTF-8
238
3.90625
4
[]
no_license
<?php //Create a script that displays 1-2-3-4-5-6-7-8-9-10 on one line. There will be no hyphen(-) at starting and ending position. for($x=1; $x<=10; $x++) { if($x< 10) { echo "$x-"; } else { echo "$x"."\n"; } } ?>
C#
UTF-8
1,715
2.59375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Paddle { /// <summary> /// The speed the player can move his bar with (bar meaning the block on the right side) /// </summary> private float _speed; /// <summary> /// The x-axis postion where the player object is locked in (meaning it cannot change the x-axis position from this) /// </summary> private float _xPositionLock; /// <summary> /// The transform that belongs to the paddle /// </summary> private Transform _paddleTransform; /// <summary> /// Controls this paddle /// </summary> private PaddleController _paddleController; /// <summary> /// Contstructor /// </summary> /// <param name="player">Reference towords the transform of the player</param> /// <param name="playerSpeed">The speed at wich the player can move</param> /// <param name="xPositionLock">The x-axis the player is locked on</param> public Paddle(float speed, float xPositionLock, Transform paddleTransform, PaddleController paddleController) { _speed = speed; _xPositionLock = xPositionLock; _paddleTransform = paddleTransform; _paddleController = paddleController; } /// <summary> /// Called by Tymon_Main to update this class /// </summary> public void Update() { // Get input from the paddle controller _paddleController.Update(); // Move paddle _paddleTransform.position = Vector3.MoveTowards(_paddleTransform.position, new Vector3(_xPositionLock, _paddleTransform.position.y + _paddleController.InputDirection, 0), _speed * Time.deltaTime); } }
Python
UTF-8
323
3.21875
3
[]
no_license
# difflib.get_close_matches returns a list of the best “good enough” matches. # This script is to demonstrate that from difflib import get_close_matches names = ['julian', 'pythonista', 'sara'] print(get_close_matches('python', names)) print(get_close_matches('jul', names)) print(get_close_matches('ara', names))
Swift
UTF-8
1,829
3.140625
3
[]
no_license
// // Interest Calculator.swift // GroupProject // // Created by Angela Garrovillas on 9/16/19. // Copyright © 2019 Angela Garrovillas. All rights reserved. // import Foundation struct InterestCalculator { var goal: Double var interestRate: Double var numOfYears: Int var total: Double = 0 var monthlyDeposits: Double static let defaultCalc = InterestCalculator(goal: Double(), interestRate: Double(), numOfYears: Int(), total: Double(), monthlyDeposits: Double()) static func calculateFromGoal(goal: Double, interestRate: Double, numOfYear: Int) -> InterestCalculator { let power = pow((1 + (interestRate / 12)), Double(12 * numOfYear)) let monthly = power / goal * 12 * Double(numOfYear) return InterestCalculator(goal: goal, interestRate: interestRate, numOfYears: numOfYear, total: 0, monthlyDeposits: monthly) } static func calculateFromMonthly(monthly: Double, interestRate: Double, numOfYear: Int) -> InterestCalculator { let power = pow((1 + (interestRate / 12)), Double(12 * numOfYear)) let goal = Double(numOfYear) * monthly * 12 * power return InterestCalculator(goal: goal, interestRate: interestRate, numOfYears: numOfYear, total: 0, monthlyDeposits: monthly) } mutating func makeAsArray() -> [(year: Int,totalInterest: Double, balance: Double)] { total = 0 var newArr = [(year: Int,totalInterest: Double, balance: Double)]() for year in 1...numOfYears { let power = pow((1 + interestRate / 12), 12) total += (monthlyDeposits * 12) * power let totalInterest = total - (monthlyDeposits * Double(12 * year)) let tuple = (year: year, totalInterest: totalInterest, balance: total) newArr.append(tuple) } return newArr } }
Java
UTF-8
9,815
1.875
2
[]
no_license
/** * <copyright> * </copyright> * * $Id$ */ package org.storydriven.storydiagrams.calls.util; import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl; import org.eclipse.emf.ecore.EObject; import org.storydriven.core.CommentableElement; import org.storydriven.core.ExtendableElement; import org.storydriven.core.Extension; import org.storydriven.core.TypedElement; import org.storydriven.storydiagrams.Variable; import org.storydriven.storydiagrams.calls.*; import org.storydriven.storydiagrams.calls.Callable; import org.storydriven.storydiagrams.calls.CallsPackage; import org.storydriven.storydiagrams.calls.Invocation; import org.storydriven.storydiagrams.calls.OpaqueCallable; import org.storydriven.storydiagrams.calls.ParameterBinding; import org.storydriven.storydiagrams.calls.ParameterExtension; /** * <!-- begin-user-doc --> * The <b>Adapter Factory</b> for the model. * It provides an adapter <code>createXXX</code> method for each class of the model. * <!-- end-user-doc --> * @see org.storydriven.storydiagrams.calls.CallsPackage * @generated */ public class CallsAdapterFactory extends AdapterFactoryImpl { /** * The cached model package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static CallsPackage modelPackage; /** * Creates an instance of the adapter factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public CallsAdapterFactory() { if (modelPackage == null) { modelPackage = CallsPackage.eINSTANCE; } } /** * Returns whether this factory is applicable for the type of the object. * <!-- begin-user-doc --> * This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model. * <!-- end-user-doc --> * @return whether this factory is applicable for the type of the object. * @generated */ @Override public boolean isFactoryForType(Object object) { if (object == modelPackage) { return true; } if (object instanceof EObject) { return ((EObject) object).eClass().getEPackage() == modelPackage; } return false; } /** * The switch that delegates to the <code>createXXX</code> methods. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected CallsSwitch<Adapter> modelSwitch = new CallsSwitch<Adapter>() { @Override public Adapter caseInvocation(Invocation object) { return createInvocationAdapter(); } @Override public Adapter caseParameterBinding(ParameterBinding object) { return createParameterBindingAdapter(); } @Override public Adapter caseOpaqueCallable(OpaqueCallable object) { return createOpaqueCallableAdapter(); } @Override public Adapter caseParameterExtension(ParameterExtension object) { return createParameterExtensionAdapter(); } @Override public Adapter caseCallable(Callable object) { return createCallableAdapter(); } @Override public Adapter caseExtendableElement(ExtendableElement object) { return createExtendableElementAdapter(); } @Override public Adapter caseCommentableElement(CommentableElement object) { return createCommentableElementAdapter(); } @Override public Adapter caseTypedElement(TypedElement object) { return createTypedElementAdapter(); } @Override public Adapter caseVariable(Variable object) { return createVariableAdapter(); } @Override public Adapter caseExtension(Extension object) { return createExtensionAdapter(); } @Override public Adapter defaultCase(EObject object) { return createEObjectAdapter(); } }; /** * Creates an adapter for the <code>target</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param target the object to adapt. * @return the adapter for the <code>target</code>. * @generated */ @Override public Adapter createAdapter(Notifier target) { return modelSwitch.doSwitch((EObject) target); } /** * Creates a new adapter for an object of class '{@link org.storydriven.storydiagrams.calls.Invocation <em>Invocation</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.storydiagrams.calls.Invocation * @generated */ public Adapter createInvocationAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.storydiagrams.calls.ParameterBinding <em>Parameter Binding</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.storydiagrams.calls.ParameterBinding * @generated */ public Adapter createParameterBindingAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.storydiagrams.calls.OpaqueCallable <em>Opaque Callable</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.storydiagrams.calls.OpaqueCallable * @generated */ public Adapter createOpaqueCallableAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.storydiagrams.calls.ParameterExtension <em>Parameter Extension</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.storydiagrams.calls.ParameterExtension * @generated */ public Adapter createParameterExtensionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.storydiagrams.calls.Callable <em>Callable</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.storydiagrams.calls.Callable * @generated */ public Adapter createCallableAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.core.ExtendableElement <em>Extendable Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.core.ExtendableElement * @generated */ public Adapter createExtendableElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.core.CommentableElement <em>Commentable Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.core.CommentableElement * @generated */ public Adapter createCommentableElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.core.Extension <em>Extension</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.core.Extension * @generated */ public Adapter createExtensionAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.core.TypedElement <em>Typed Element</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.core.TypedElement * @generated */ public Adapter createTypedElementAdapter() { return null; } /** * Creates a new adapter for an object of class '{@link org.storydriven.storydiagrams.Variable <em>Variable</em>}'. * <!-- begin-user-doc --> * This default implementation returns null so that we can easily ignore cases; * it's useful to ignore a case when inheritance will catch all the cases anyway. * <!-- end-user-doc --> * @return the new adapter. * @see org.storydriven.storydiagrams.Variable * @generated */ public Adapter createVariableAdapter() { return null; } /** * Creates a new adapter for the default case. * <!-- begin-user-doc --> * This default implementation returns null. * <!-- end-user-doc --> * @return the new adapter. * @generated */ public Adapter createEObjectAdapter() { return null; } } //CallsAdapterFactory
Markdown
UTF-8
6,245
2.859375
3
[]
no_license
谈画(1) 我从前的学校教室里挂着一张“蒙纳.丽萨”,意大利文艺复兴时代的名画。先生说:“注意那女人脸上的奇异的微笑。”的确是使人略感不安的美丽恍惚的笑,像是一刻也留它不住的,即使在我努力注意之际也滑了开去,使人无缘无故觉得失望。先生告诉我们,画师昼这张图的时候曾经费尽心机搜罗了全世界各种罕异可爱的东西放在这女人面前,引她现出这样的笑容。我不喜欢这解释。绿毛龟,木乃伊的脚,机器玩具,倒不见得使人笑这样的笑。使人笑这样的笑,很难罢?可也说不定很容易。一个女人蓦地想到恋人的任何一个小动作,使他显得异常稚气?可爱又可怜,她突然充满了宽容,无限制地生长到自身之外去,荫庇了他的过去与将来,眼睛里就许有这样的苍茫的微笑。 “蒙纳.丽萨”的模特儿被考证出来。是个年轻的太太。也许她想起她的小孩今天早晨说的那句聪明的话——真是什么都懂得呢——到八月里才满四岁——就这样笑了起来,但又矜持着,因为画师在替她画像,贵妇人的笑是不作兴露牙齿的。 然而有个十九世纪的英国文人——是不是Walter de la Mare,记不清了——写了一篇文章关于“蒙纳.丽萨”,却说到鬼灵的智慧,深海底神秘的鱼藻。看到画,想做诗,我并不反对——好的艺术原该唤起观众各个人的创造性,给人的不应当是纯粹被动的欣赏——可是我憎恶那篇“蒙纳.丽萨”的说明,因为是有限制的说明,先读了说明再去看图画,就不由得要到女人眼睛里去找深海底的鱼影子。那样的华美的附会,似乎是增多,其实是减少了图画的意义。 国文课本里还读到一篇“画记”,那却是非常简炼,只去计算那些马,几匹站着,几匹卧着,中国画上题的诗词,也只能拿它当做字看,有时候的确字写得好,而且给了画图的结构一种脱略的,有意无意的均衡,成为中国画的特点。然而字句的本身对于图画总没有什么好影响,即使用的是极优美的成句,一经移植在画上,也觉得不妥当。 因此我现在写这篇文章关于我看到的图画,有点知法犯法的感觉,因为很难避免那种说明的态度——而对于一切好图画的说明,总是有限制的说明,但是临下笔的时候又觉得不必有那些顾忌,臂如朋友见面,问:“这两天晚上月亮真好,你看见了没有?”那也很自然罢? 新近得到一本赛尚画册,有机会把赛尚的画看个仔细。以前虽然知道赛尚是现代画派第一个宗师,倒是对于他的徒子徒孙较感兴趣,像Gauguin,Van Gogh,Matisse,以至后来的Picasso,都是抓住了他的某一特点,把它发展到顶点,因此比较偏执,鲜明,引人入胜。而充满了多方面的可能性的,广大的含蓄的赛尚,过去给我唯一的印象是杂志里复制得不很好的静物,几只灰色的苹果,下面衬着桌布,后面矗立着酒瓶,从苹果的处理中应当可以看得出他于线条之外怎样重新发现了“块”这样东西,但是我始终没大懂。 我这里这本书名叫“赛尚与他的时代”,是日文的,所以我连每幅画的标题也弄不清楚。早期的肖像画中有两张成为值得注意的对比。一八六零年的一张,画的是个宽眉心大眼睛诗人样的人,云里雾里,暗金质的画面上只露出一部份的脸面与自领子。我不喜欢罗曼蒂克主义的传统,那种不求甚解的神秘,就像是把电灯开关一捻,将一种人造的月光照到任何事物身上、于是就有模糊的蓝色的美艳,黑影,里头唧唧阁阁叫着兴奋与恐怖的虫与蛙。 再看一八六三年的一张画,里面也有一种奇异的,不安于现实的感觉,但不是那样廉价的诗意。这张画里我们看见一个大头的小小的人,年纪已在中年以上了,波鬈的淡色头发照当时的式样长长地分披着。他坐在高背靠椅上,流转的大眼睛显出老于世故的,轻蔑浮滑的和悦。高翘的仁丹胡子补足了那点笑意。然而这张画有点使人不放心,人体的比例整个地错误了,腿太短,臂膊太短,而两只悠悠下垂的手却又是很长,那白削的骨节与背后的花布椅套相衬下,产生一种微妙的,文明的恐怖。 一八六四年所作的僧侣肖像,是一个须眉浓鸷的人,白袍,白风兜,胸前垂下十字架,抱着胳膊,两只大手,手与脸的平面特别粗糙,隐现冰裂纹。整个的画面是单纯的灰与灰白,然而那严寒里没有凄楚,只有最基本的,人与风雹山河的苦斗。 欧洲文艺复兴以来许多宗教画最陈腐的题材,到了赛尚手里,却是大不相同了。“抱着基督尸身的圣母像”,实在使人诧异。圣母是最普通的妇人,清贫,论件计值地做点缝纫工作。灰了心,灰了头发,白鹰钩鼻子与紧闭的嘴里有四五十年来狭隘的痛苦。她并没有抱住基督,背过身去正在忙着一些什么,从她那暗色衣裳的折迭上可以闻得见熓着的贫穷的气味。抱着基督的倒是另一个屠夫样的壮大男子,石柱一般粗的手臂,秃了的头顶心雪白地连着阴森的脸,初看很可怕,多看了才觉得那残酷是有它的苦楚的背景的,也还是一个可同情的人。尤为奇怪的是基督本人,皮肤发黑,肌肉发达,脸色和平,伸长了腿,横贯整个的画面,他所有的只是图案美,似乎没有任何其它意义。 “散步的人”,一个高些,戴着绅士气的高帽子,一个矮些的比较像武人,头戴卷檐大毯帽,脚踏长统皮靴,手扶司约克。那炎热的下午,草与树与淡色的房子蒸成一片雪亮的烟,两个散步的人衬衫里焖着一重重新的旧的汗味,但仍然领结打得齐齐整整,手搀着手,茫然地,好脾气地向我们走来,显得非常之楚楚可怜。
Markdown
UTF-8
4,741
2.859375
3
[]
no_license
--- coverImage: /posts/taming-unity/cover.jpg date: '2014-04-26T00:42:52.000Z' tags: - games - mvc - robotlegs - strangeioc - unit testing title: Taming Unity oldUrl: /c/taming-unity --- [![logo](https://www.mikecann.co.uk/wp-content/uploads/2014/04/logo.png)](https://www.mikecann.co.uk/wp-content/uploads/2014/04/logo.png) For the last couple of months I have been working on a few different things including many new releases of [Post To Tumblr](https://chrome.google.com/webstore/detail/post-to-tumblr/dbpicbbcpanckagpdjflgojlknomoiah?hl=en). Most of my time however has been spent working on an unnamed (as of yet) game in Unity. <!-- more --> Its my first time using Unity, having come from a predominantly Flash games background I was excited to have the power of C# with a WYSIWYG editor for rapid iterations, and indeed I did make rapid progress. I soon had a working gameplay prototype up and running and everything and everything was hunky dory. It worked but the code was far from pretty with dependencies between my components all over the place not to mention the headaches when I tried to introduce Unit Testing into the mix. The game I am developing is a turn based strategy with some complex gameplay rules, perfectly suited to unit testing I thought. Unfortunately however the power of Unity's rapid development is also its downfall. It allows you to do some pretty nasty things. It also uses a vast number of statics and singletons making testing rather tricky. I managed to muddle my way through things using Unity's recently released [Unit Testing Tools](https://blogs.unity3d.com/2013/12/18/unity-test-tools-released/) however things were far from ideal. The main issues were dependency hell and Managers. Unity seems to recommend "Managers" as a way to look after various parts of game logic. You create an empty game object then attach a manager component to it then reference that manager from anywhere. Seems okay (though there are numerous problems with this particularly when it comes to changing scenes) however the big problem is how to reference that manager from your components? The method I was using was in the Awake() I would use GameObject.FindObjectOfType(); then cache the result and use it. Fair enough but this still means I have a dependency in this component on the Manager. It also makes Unit Testing very hard because there is no way to pass in a mock Manager. A stopgap solution was to use constructors to pass in the manager: [code lang="csharp"] private MyManager \_manager; public MyClass(MyManager <span class="hiddenGrammarError" pre="">manager) { \_manager</span> = manager; } void Awake() { if(\_manager==null) \_manager = GameObject.FindObjectOfType(); } [/code] Still we have the dependency there however and my code was starting to get more and more complex. Plus Unity doesn't really like you instantiating MonoBehaviours using constructors so I would continually get warnings in my tests. Far from ideal, so I decided to go looking for an alternative. In the past I have worked a great deal with the Robotlegs framework and knew it was designed specifically to help with clear separation of use and help with managing dependencies for easy unit testing. So I wondered if anyone had ported Robotlegs to Unity. Well I was very happy to discover someone had and had done a good job of it in the form of [Strange IoC](https://strangeioc.github.io/strangeioc/). Strange is an MVCS framework very similar to Robotlegs so if you know Robotlegs you should be swimming. I wont go into the details of MVCS, checkout the [documentation](https://strangeioc.github.io/strangeioc/TheBigStrangeHowTo.html) or the Robotlegs documentation if you want to know more. Using Strange I was able to replace the dependencies in my components by converting most my components into "Views" which respond by displaying data and then dispatching signals which the rest of the application picks up in Commands and and updates the Models or uses Services to communicate with the database. It immediately made my code much more testable by removing many of the dependencies between my components. At the same time I was able to convert many of my Models and other "Manager" like classes to implement Interfaces which made my code much more portable should I choose to change parts or reuse bits in future projects. A disclaimer is that I have only used it for my menu systems and multiplayer services so far as thats what MVCS is ideally suited for and haven't converted my spaghetti game logic over to it yet so cant comment on it just yet. My main worry is that it may slow down the enjoyment of rapid iteration and development. I will have to think carefully about that as I go forward.
SQL
UTF-8
290
2.71875
3
[ "MIT" ]
permissive
create user :db_user with password ':db_password'; alter user :db_user createdb; alter user :db_user set client_encoding to 'utf8'; alter user :db_user set default_transaction_isolation to 'read committed'; alter user :db_user set timezone to 'UTC'; create database :db_name owner :db_user ;
C++
UTF-8
4,422
2.65625
3
[]
no_license
#include "ExecutorManager.h" namespace robot{ bool ExecutorManager::getWorldProperty() const{ return true; } bool ExecutorManager::setWorldProperty(){ return true; } bool ExecutorManager::sendMessage(Message* message){ messageQueueLock.lock(); messageQueue.push(message); messageQueueLock.unlock(); messageQueueNotEmpty.notify_one(); return true; } bool ExecutorManager::receiveMessage(Message* message){ //Notifications that should be processed by other executor if (message->getMessageType()==MessageType::NOTIFICATION){ Notification* notification=(Notification*)message; //We should stop enemy detected notification and pass it to motion executor if (notification->getTopic()==EnemyDetectedNotification::NAME){ return sendMessage(message); } }else if (message->getMessageType()==MessageType::START_MESSAGE){ this->sendMessage(message->clone()); } return taskManager->sendMessage(message); } bool ExecutorManager::addExecutor(AbstractExecutor* newExecutor){ newExecutor->registerManager(this); boost::upgrade_lock<shared_mutex> lock(executorsMapManipulation); boost::upgrade_to_unique_lock<shared_mutex> uniqueLock(lock); executorsMap[newExecutor->getName()]=newExecutor; return true; } void ExecutorManager::init(){ map<string,AbstractExecutor*>::const_iterator it=executorsMap.cbegin(); for (;it!=executorsMap.cend();++it){ it->second->init(); } } void ExecutorManager::stop(){ debug("Stopping executor manager"); shouldStop=true; this->sendMessage(new StopMessage("Executor manager")); } void ExecutorManager::main(){ shouldStop=false; startAllExecutors(); dispatcheMessage(); debug("*** Finished ***"); } void ExecutorManager::startAllExecutors(){ boost::shared_lock<shared_mutex> lock(executorsMapManipulation); map<string,AbstractExecutor*>::const_iterator it=executorsMap.cbegin(); for (;it!=executorsMap.cend();++it){ debug("Starting executor"); it->second->start(); } } Message* ExecutorManager::popNextMessage(){ boost::unique_lock<boost::mutex> lock(messageQueueLock); while (messageQueue.empty()) { messageQueueNotEmpty.wait(lock); } Message* message=messageQueue.front(); messageQueue.pop(); return message; } void ExecutorManager::dispatcheMessage(){ while(!shouldStop){ Message* message=popNextMessage(); if (shouldStop) break; switch (message->getMessageType()) { case NOTIFICATION: { Notification* notification=(Notification*)message; boost::shared_lock<shared_mutex> lock(executorsMapManipulation); for (map<string,AbstractExecutor*>::const_iterator it=executorsMap.cbegin();it!=executorsMap.cend();++it){ if (it->second->isSubscribed(notification)) it->second->processNotification(notification->clone()); } delete notification; } break; case COMMAND: { Command* command=(Command*)message; map<string,AbstractExecutor*>::iterator destIt; boost::shared_lock<shared_mutex> lock(executorsMapManipulation); if ((destIt=executorsMap.find(command->getDestination()))!=executorsMap.end()){ destIt->second->processCommand(command); } } break; case START_MESSAGE: { boost::shared_lock<shared_mutex> lock(executorsMapManipulation); for (map<string,AbstractExecutor*>::const_iterator it=executorsMap.cbegin();it!=executorsMap.cend();++it){ it->second->startMatch(); } } break; default: break; } } stopAllExecutors(); } void ExecutorManager::stopAllExecutors(){ boost::shared_lock<shared_mutex> lock(executorsMapManipulation); map<string,AbstractExecutor*>::const_iterator it=executorsMap.cbegin(); debug("Stopping all executors"); for (;it!=executorsMap.cend();++it){ it->second->stop(); } it=executorsMap.cbegin(); debug("Waiting to join on executors"); for (;it!=executorsMap.cend();++it){ it->second->join(); } } void ExecutorManager::setTaskManager(AbstractMessageHandler *_taskManager){ taskManager=_taskManager; } }
Java
UTF-8
456
1.609375
2
[]
no_license
/** * FileName: CourseCollectVo * Author: ljl * Date: 2021/7/15 11:50 * Description: * History: */ package com.ljl.guli.service.edu.entity.vo; import lombok.Data; import java.math.BigDecimal; @Data public class CourseCollectVo { private String courseId; private String courseTitle; private BigDecimal price; private Integer lessonNum; private String cover; private String gmtCreate; private String teacherName; }
C
UTF-8
774
2.578125
3
[ "MIT" ]
permissive
/* Your program is supposed to create a full red screen in MSDOS. The source of the binary (.com file) must be 5 bytes or less. No wild assumptions, the binary must work in MsDos, DosBox, and FreeDos alike. For winning, you have to post x86 assembler code which can be assembled with NASM (FASM) or directly the hex code of the binary. You can test you assembler code in an Online Dosbox. Code Example (six bytes): X les cx,[si] inc sp stosb jmp short X+1 Try x86 asm code in an Online DosBox Information on sizecoding for Msdos "M8trix" might be helpful Background information/ six bytes version */ #include <stdio.h> int main(void) { // www.pouet.net unsigned char code[] = {0x56, 0xC4, 0x04, 0xAB, 0xC3}; fwrite(code, sizeof(code), 1, stdout); return 0; }
C++
UTF-8
11,525
3.5
4
[]
no_license
#ifndef _MATHHELPER_H #define _MATHHELPER_H #include <cmath> // For voxels #define SUBDIV_X 0 #define SUBDIV_Y 1 #define SUBDIV_Z 2 #define VECTOR_INCOMING 0 #define VECTOR_OUTGOING 1 #define PI 3.14159265 /* * The Color class, RGB should be between 0 and 1 */ struct Color { // RGB double r, g, b; //default Color( double s = 0 ) : r(s), g(s), b(s) {} // constructors Color ( double r, double g, double b ) : r(r), g(g), b(b) {} // Non-modifying arithematic operators Color operator+(const Color& rhs){ return Color(r + rhs.r, g + rhs.g, b + rhs.b); } Color operator-(const Color& rhs){ return Color(r - rhs.r, g - rhs.g, b - rhs.b); } Color operator/(double rhs){ return Color(r/rhs, g/rhs, b/rhs); } Color operator*(const Color& rhs){ return Color(r * rhs.r, g * rhs.g, b * rhs.b); } Color operator*(double rhs){ return Color(r * rhs, g * rhs, b * rhs); } friend Color operator*(double lhs, const Color& rhs){ return Color(lhs * rhs.r, lhs * rhs.g, lhs * rhs.b); } // Modifying arithematic operators Color& operator+=( const Color& rhs ) { r += rhs.r; g += rhs.g; b += rhs.b; return *this; } // Comparisons bool operator!=(const Color& rhs) { return (r != rhs.r || g != rhs.g || b != rhs.b); } }; /* * The Point class. */ struct Point { // 3D point double x, y, z; //default Point ( double s = 0 ) : x(s), y(s), z(s) {} // constructors Point ( double x, double y, double z ) : x(x), y(y), z(z) {} // overloading operators bool operator==(const Point& rhs) { return (x == rhs.x && y == rhs.y && z == rhs.z); } bool operator!=(const Point& rhs) { return !(*this == rhs); } // Non-modifying arithematic operators Point operator+(const Point& rhs) { return Point(x + rhs.x, y + rhs.y, z + rhs.z); } Point operator-(const Point& rhs) { return Point(x - rhs.x, y - rhs.y, z - rhs.z); } Point operator* (double rhs) { return Point(x * rhs, y * rhs, z * rhs); } friend Point operator* (double lhs, const Point& rhs) { return Point(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } }; /* * The Vector class. */ struct Vector { // 3D vector double x, y, z; //default Vector ( double s = 0 ) : x(s), y(s), z(s) {} // constructor, considering a vector from origin -> (x,y,z) Vector ( double xn, double yn, double zn, bool norm = false ) : x(xn), y(yn), z(zn) { if(norm) { double len = sqrt( x*x+y*y+z*z ); if (len != 0.0) { x = x / len; y = y / len; z = z / len; } } } // constructor, from origin to destination Vector ( Point o, Point d, bool norm = false ) { x = d.x - o.x; y = d.y - o.y; z = d.z - o.z; if(norm) { double len = sqrt( x*x+y*y+z*z ); if (len != 0.0) { x = x / len; y = y / len; z = z / len; } } } // Non-modifying arithematic operators Vector operator+(const Vector& rhs) { return Vector(x + rhs.x, y + rhs.y, z + rhs.z); } Vector operator-(const Vector& rhs) { return Vector(x - rhs.x, y - rhs.y, z - rhs.z); } Vector operator/(double rhs) { return Vector(x/rhs, y/rhs, z/rhs); } Vector operator* (double rhs) { return Vector(x * rhs, y * rhs, z * rhs); } friend Vector operator* (double lhs, const Vector& rhs) { return Vector(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z); } }; /* * The Matrix class. * * Note: arithematic operations for matrixes will just assume the user is correct, * no check is done, e.g., the operations will not check the rows and columns of * two matrices when they are multiplied, it will just try to do it (will return * a runtime error if the user is using wrong parameters). */ struct Matrix { int row; int col; // matrix std::vector<double> matrix; // default Matrix ( int row, int col, double s = 0 ) : row(row), col(col) { for (int i = 0; i < row * col; ++i ) matrix.push_back(s); } // constructor Matrix ( int row, int col, double vals[] ) : row(row), col(col) { for (int i = 0; i < row * col; ++i ) matrix.push_back(vals[i]); } // create a matrix from a vector, since our vector is of size 3 // the rows and columns are known beforehand Matrix ( Vector v ) : row(3), col(1) { matrix.push_back(v.x); matrix.push_back(v.y); matrix.push_back(v.z); } // Array subscription double& operator[](const int index) { return matrix[index]; } // Non-modifying arithematic operators Matrix transpose () { double vals[row * col]; for( int k = 0; k < row * col; ++k ) { int i = k / row; int j = k % row; vals[k] = matrix[col * j + i]; } return Matrix(col,row,vals); } Matrix operator+ (const Matrix& rhs) { double vals[row * col]; for ( int i = 0; i < row * col; ++i ) vals[i] = matrix[i] + rhs.matrix[i]; return Matrix(row, col, vals); } Matrix operator- (const Matrix& rhs) { double vals[row * col]; for ( int i = 0; i < row * col; ++i ) vals[i] = matrix[i] - rhs.matrix[i]; return Matrix(row, col, vals); } Matrix operator* (const Matrix& rhs) { double vals[row * rhs.col]; for (int i = 0; i < row; ++i) { for (int j = 0; j < rhs.col; ++j) { vals[rhs.col*i+j] = 0; for (int k = 0; k < rhs.row; ++k) vals[i * rhs.col + j] += matrix[i * col + k] * rhs.matrix[k * rhs.col + j]; } } return Matrix(row, rhs.col, vals); } Matrix operator* (double rhs) { double vals[row * col]; for ( int i = 0; i < row * col; ++i ) vals[i] *= rhs; return Matrix(row,col,vals); } friend Matrix operator* (double lhs, const Matrix& rhs) { double vals[rhs.row * rhs.col]; for ( int i = 0; i < rhs.row * rhs.col; ++i ) vals[i] = lhs * rhs.matrix[i]; return Matrix(rhs.row,rhs.col,vals); } }; /* * The Ray class. */ struct Ray { // 3D Ray with origin and direction Point o; Vector d; // constructors Ray () {} Ray ( Point p, Vector v ) : o(p), d(v) {} Point getOrigin() { return o; } Vector getDirection() { return d; } }; /* * The Voxel class. */ struct Voxel { // follows right handed coord system double xLeft, xRight; double yBottom, yTop; double zFar, zNear; Voxel () {} Voxel(double xLeft, double xRight, double yBottom, double yTop, double zFar, double zNear) : xLeft(xLeft), xRight(xRight), yBottom(yBottom), yTop(yTop), zFar(zFar), zNear(zNear) {} Voxel splitFront (int subdiv) { if (subdiv == SUBDIV_X) return Voxel((xLeft+xRight)/2.0, xRight, yBottom, yTop, zFar, zNear); else if (subdiv == SUBDIV_Y) return Voxel(xLeft, xRight, (yBottom+yTop)/2.0, yTop, zFar, zNear); else return Voxel(xLeft, xRight, yBottom, yTop, (zFar+zNear)/2.0, zNear); } Voxel splitRear (int subdiv) { if (subdiv == SUBDIV_X) return Voxel(xLeft, (xLeft+xRight)/2.0, yBottom, yTop, zFar, zNear); else if (subdiv == SUBDIV_Y) return Voxel(xLeft, xRight, yBottom, (yBottom+yTop)/2.0, zFar, zNear); else return Voxel(xLeft, xRight, yBottom, yTop, zFar, (zFar+zNear)/2.0); } double splitVal (int subdiv) { if (subdiv == SUBDIV_X) return (xLeft+xRight)/2.0; else if (subdiv == SUBDIV_Y) return (yBottom+yTop)/2.0; else return (zFar+zNear)/2.0; } bool intersect (Ray ray, double t0, double t1) { Point o = ray.getOrigin(); Vector d = ray.getDirection(); double tmin, tmax, tymin, tymax, tzmin, tzmax; double divx = 1.0 / d.x; if (divx >= 0) { tmin = (xLeft - o.x) * divx; tmax = (xRight - o.x) * divx; } else { tmin = (xRight - o.x) * divx; tmax = (xLeft - o.x) * divx; } double divy = 1.0 / d.y; if (divy >= 0) { tymin = (yBottom - o.y) * divy; tymax = (yTop - o.y) * divy; } else { tymin = (yTop - o.y) * divy; tymax = (yBottom - o.y) * divy; } if ( (tmin > tymax) || (tymin > tmax) ) return false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; double divz = 1.0 / d.z; if (divz >= 0) { tzmin = (zFar - o.z) * divz; tzmax = (zNear - o.z) * divz; } else { tzmin = (zNear - o.z) * divz; tzmax = (zFar - o.z) * divz; } if ( (tmin > tzmax) || (tzmin > tmax) ) return false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; return ( (tmin < t1) && (tmax > t0) ); } Point getCenter() { return Point((xLeft + xRight) / 2.0 , (yBottom + yTop) / 2.0, (zFar + zNear) / 2.0); } Point getHalfLenghts() { return Point(std::abs(xRight - xLeft) / 2.0, std::abs(yTop - yBottom) / 2.0, std::abs(zNear - zFar) / 2.0); } }; /* * Non-class functions */ double distance ( const Point &p, const Point &q ) { double a = p.x - q.x; double b = p.y - q.y; double c = p.z - q.z; return sqrt(a*a + b*b + c*c); } double length ( const Vector &v ) { return sqrt( v.x*v.x+v.y*v.y+v.z*v.z ); } void normalize ( Vector& v ) { double len = length(v); if (len != 0.0) { v.x = v.x / len; v.y = v.y / len; v.z = v.z / len; } } Vector cross ( const Vector &v, const Vector &u ) { return Vector( v.y*u.z - v.z*u.y , v.z*u.x - v.x*u.z , v.x*u.y - v.y*u.x ); } double dot ( const Vector &v , const Vector &u ) { return ( v.x*u.x + v.y*u.y + v.z*u.z ); } // Reflect a vector v "hitting" a surface with normal N // this vector can have two directions // incoming -> going to the surface // outgoing -> going from the surface Vector reflect ( Vector v, const Vector &N, const int &direction ) { normalize( v ); if (direction == VECTOR_INCOMING) return (v - 2.0 * dot(v, N) * N); else return (2.0 * N * dot(v,N) - v); } // returns the index for the minimum value is a vector of doubles int indexMinElement ( const std::vector<double> &v ) { if (v.empty()) return -1; double minDist = *std::max_element(v.begin(), v.end()); int index = -1; for(unsigned int i = 0; i < v.size(); ++i) { if (v[i] != 0 && v[i] <= minDist) { minDist = v[i]; index = i; } } return index; } // returns a simple 3x3 identity matrix Matrix indentityMatrix () { double aux[] = {1,0,0,0,1,0,0,0,1}; return Matrix(3,3,aux); } #endif
Shell
UTF-8
295
2.53125
3
[]
no_license
#!/bin/bash set -ex DEV_IMAGE_NAME="jincort/frontend-supreme-happiness-develop" PROD_IMAGE_NAME="jincort/frontend-supreme-happiness" TAG="${1}" docker push ${DEV_IMAGE_NAME}:${TAG} docker build -f Dockerfile.prod --no-cache -t ${PROD_IMAGE_NAME}:${TAG} . docker push ${PROD_IMAGE_NAME}:${TAG}
SQL
UTF-8
1,434
4.25
4
[]
no_license
SELECT c.posting_date AS "Posting Date:Date:80", c.voucher_no AS "Voucher No:Text:150", c.debit AS "Amount Invoiced:Currency:120", c.credit AS "Payment Recieved:Currency:120", c.due AS "Amount Due:Currency:120", c.remarks as "Remarks:Text:360" FROM (SELECT posting_date, voucher_no, docstatus, debit, credit, SUM(debit - credit) OVER(ORDER BY posting_date,voucher_no ASC) AS due, remarks, party FROM ( (SELECT posting_date, voucher_no, SUM(debit) AS debit, SUM(credit) AS credit, remarks, party FROM `tabGL Entry` WHERE company=%(company)s AND party=%(party)s GROUP BY posting_date,voucher_no ) As a JOIN (SELECT name, docstatus FROM `tabSales Invoice` WHERE docstatus = 1 UNION SELECT name, docstatus FROM `tabPayment Entry` WHERE docstatus = 1 ) AS b ON a.voucher_no = b.name ) ) AS c WHERE c.posting_date BETWEEN %(from_date)s AND %(to_date)s ORDER BY c.posting_date,c.voucher_no ASC;
PHP
UTF-8
2,790
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Food; use App\Models\Meal; class FoodsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request, Meal $meal) { $this->validate($request, [ 'name' => 'required|string', 'protein' => 'required|integer', 'carbohydrates' => 'required|integer', 'fat' => 'required|integer' ]); $food = new Food($request->all()); $meal->foods()->save($food); return back()->with('message','Food created successfully.'); // $food = Food::create($validated); // $food = new Food(); // $request->validate([ // 'name' => 'required|string|max:55', // 'carbohydrates' => 'required|integer', // 'protein' => 'required|integer', // 'fat' => 'required|integer', // 'meal_id' => 'required', // ]); // $food->name = $request->name; // $food->carbohydrates = $request->carbohydrates; // $food->protein = $request->protein; // $food->fat = $request->fat; // $food->meal_id = $request->meal_id; // // $food->save(); // $food->save(); // return redirect()->back()->with('success', 'food created successfully.'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id, $foodID) { Food::destroy($foodID); return redirect()->back()->with('deleteFood','Food deleted successfully.'); } }
Java
MacCyrillic
3,383
3.203125
3
[]
no_license
import java.io.DataInputStream; import java.io.InputStream; import java.util.ArrayList; class FastScanner { private DataInputStream din; final private int bufferSize; private int bytesCount; private byte[] buffer; private int bufferCur; public FastScanner(InputStream in) { din = new DataInputStream(in); bufferSize = 1 << 8; buffer = new byte[bufferSize]; bytesCount = 0; bufferCur = 0; } private byte nextByte() { if(bufferCur == bytesCount) { try { bufferCur = 0; bytesCount = din.read(buffer, bufferCur, bufferSize); } catch (Exception e) { System.out.println(e); } if (bytesCount == -1) buffer[0] = -1; } return buffer[bufferCur++]; } public String nextLine() { StringBuilder ans = new StringBuilder(); try { byte c = nextByte(); if (c == -1) { return null; } while (c != '\r') { ans.append((char)c); c = nextByte(); } c = nextByte(); } catch (Exception e) { System.out.println(e); } return ans.toString(); } public int nextInt() { int len = 0; int ans = 0; byte[] s = new byte[bufferSize]; try { byte c = nextByte(); while ((c > '9' || c < '0') && c != '-') { c = nextByte(); } while (c >= '0' && c <= '9' || c == '-') { s[len++] = c; c = nextByte(); } try { ans = Integer.parseInt(new String(s, 0, len)); } catch (NumberFormatException e) { System.out.println(" :" + s); } } catch (Exception e) { System.out.println(e); } return ans; } public long nextLong() { int len = 0; byte[] s = new byte[bufferSize]; try { byte c = nextByte(); while ((c > '9' || c < '0') && c != '-') { c = nextByte(); } while (c >= '0' && c <= '9' || c == '-') { s[len++] = c; c = nextByte(); } } catch (Exception e) { System.out.println(e); } return Long.parseLong(new String(s, 0, len)); } public double nextDouble() { int len = 0; byte[] s = new byte[bufferSize]; try { byte c = nextByte(); while ((c > '9' || c < '0') && c != '-' && c != '.') { c = nextByte(); } while (c >= '0' && c <= '9' || c == '-' || c == '.') { s[len++] = c; c = nextByte(); } } catch (Exception e) { System.out.println(e); } return Double.parseDouble(new String(s, 0, len)); } public ArrayList<Integer> numbers() { ArrayList<Integer> ans = new ArrayList<Integer>(); StringBuilder s = new StringBuilder(); try { byte c = nextByte(); if (c == '\n') { c = nextByte(); } if (c == -1) { return null; } if (c == '\r') { return ans; } while (c != '\n') { if (c == ' ' || c == '\r') { try { ans.add(Integer.parseInt(s.toString())); } catch (NumberFormatException e) { System.out.println(" : " + s); } } else { s.append((char)c); } c = nextByte(); } } catch (Exception e) { System.out.println(e); } return ans; } }
TypeScript
UTF-8
572
3.5
4
[]
no_license
function addition(num1: number, num2: number): number { const add: number = num1 + num2; return add; } function multiplication(num1: number, num2: number): number { const multi: number = num1 * num2; return multi; } function subtraction(num1: number, num2: number): number { const sub: number = num1 - num2; return sub; } function division(num1: number, num2: number): number { const div: number = num1 / num2; return div; } console.log(addition(10, 20)); console.log(subtraction(10, 5)); console.log(multiplication(10, 2)); console.log(division(10, 3));
C#
UTF-8
728
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _piataAZ.Entities { public class Ad { private String _title; private String _description; private String _usernameEmployee; private String _image; public Ad(String title, String description, String usernameEmployee, String image) { _title = title; _description = description; _usernameEmployee = usernameEmployee; _image = image; } public String getDescription() { return _description; } public String getImage() { return _image; } } }
C
UTF-8
1,851
4.21875
4
[]
no_license
#include "util.h" #include <ctype.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> /** * Trim the given string by replacing the spaces with null character * @param char * str */ void str_trim(char * str) { uint8_t start_flag, end_flag; int len; start_flag = end_flag = 0; /* Remove leading spaces and count string length */ for (uint32_t i = 0; str[i] != '\0'; i++) { if (start_flag) len++; else { if (isspace(str[i]) == 0) start_flag = 1; else str++; /* Count string length */ } } /* Remove tailing spaces */ for (int i = len; i >= 0 && isspace(str[i]) != 0; i--) { str[i] = '\0'; } } /** * Create an array of string by spliting the given string by the delimiter * @param char * str * @param char delimiter * @return Array of string */ char ** str_split(char * str, char delimiter) { uint32_t arr_len; char ** str_arr; arr_len = str_count(str, delimiter); /* Create array */ if (arr_len > 0) str_arr = malloc(sizeof(char **) * arr_len); else return NULL; /* Nothing to split */ /* Spliting */ uint32_t arr_idx = 0; str_arr[arr_idx] = str; for (uint32_t i = 0; str[i] != '\0'; i++) { if (str[i] == delimiter) { str[i] = '\0'; str_arr[++arr_idx] = &str[i + 1]; } } return str_arr; } /** * Count the number of character c in the given string * @param char * str - Given * @param char c - Target * @return Number of character c in the string */ uint32_t str_count(char * str, char c) { uint32_t count = 0; for (uint32_t i = 0; str[i] != '\0'; i++) { if (str[i] == c) count++; } return count; }
C++
UTF-8
1,074
3.40625
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* partition(ListNode* head, int x) { if (head == NULL || head->next == NULL) return head; ListNode* start = new ListNode(0); start->next = head; ListNode* lptr = head; ListNode* lprev = start; while (lptr) { if (lptr->val < x) { lprev = lptr; lptr = lptr->next; } else { ListNode* rptr = lptr; ListNode* rprev = lprev; while (rptr && rptr->val >= x) { rprev = rptr; rptr = rptr->next; } if (!rptr) return start->next; lprev->next = rptr; rprev->next = rptr->next; rptr->next = lptr; lprev = rptr; } } return start->next; } };
C#
UTF-8
1,283
2.515625
3
[]
no_license
using UnityEngine; using System.Collections; using UnityEngine.UI; using System; public class SearchButtonOnClick : MonoBehaviour { public Text start; public Text fin; public Text time; public Text amount; public void OnClick() { ErrorHandler.hide(); GameObject init = GameObject.FindGameObjectWithTag("Init"); Init initScript = init.GetComponent<Init>(); initScript.startSearching(start.text, fin.text, getTime(), getAmount()); } private Time getTime() { try { string[] input = time.text.Split(':'); return new Time(Int32.Parse(input[0]), Int32.Parse(input[1])); } catch(Exception e) { if (time.text != "") ErrorHandler.printErrorMsgNoThrow("Zlý formát času!\n Vyhľadáva sa od momentálneho času"); return new Time(DateTime.Now.Hour, DateTime.Now.Minute); } } private int getAmount() { try { return Int32.Parse(amount.text); } catch (Exception) { if (amount.text != "") ErrorHandler.printErrorMsgNoThrow("Zlý počet zastávok určených na výpis!\n Vyhľadávajú sa 3 výsledky"); return 3; } } }
Java
UTF-8
1,580
2.375
2
[]
no_license
package com.qqhr.platfrom.handler; import com.qqhr.common.enums.TopicEnum; import com.qqhr.platfrom.executor.ExecutorPipeline; import com.qqhr.platfrom.interfaces.IHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; /** * @Author WilliamDragon * @Date 2021/4/19 14:07 * @Version 1.0 */ @Component public class HandlerMapping { private Logger log = LoggerFactory.getLogger(this.getClass()); ConcurrentHashMap<String, ExecutorPipeline> container = new ConcurrentHashMap<String, ExecutorPipeline>(); public void addHandler(String messageType, IHandler handler){ ExecutorPipeline executorPipeline = container.get(messageType); if(executorPipeline == null){ executorPipeline = new ExecutorPipeline(); container.put(messageType,executorPipeline); } executorPipeline.addHandle(handler); } public void removeHandler(String messageType, IHandler iHandler){ ExecutorPipeline executorPipeline = container.get(messageType); if(executorPipeline == null){ log.info("没有"+ messageType+ "对应的执行链"); } executorPipeline.removeHandle(iHandler); } public ExecutorPipeline doSelectExecutorPipeline(String messageType){ if(messageType != null){ return container.get(messageType); } return null; } }
C
UTF-8
1,367
3.546875
4
[]
no_license
// // main.c // 08_05_Challenge // // Created by jim Veneskey on 1/26/16. // Copyright © 2016 Jim Veneskey. All rights reserved. // #include <stdio.h> #include <stdlib.h> // Function prototype void buySellOrHold(int price); void finalDecision(char bsoh); int main(int argc, const char * argv[]) { // insert code here... int marketPrice; printf("Welcome to the Stock Market Decision Maker 1.0\n"); printf("Please enter the current market price for Widget Inc. "); scanf("%d", &marketPrice); printf("Stand by while this price is analyzed...\n"); buySellOrHold(marketPrice); return EXIT_SUCCESS; } void buySellOrHold(int currentPrice) { char decision; if (currentPrice > 100) { decision = 's'; } else if (currentPrice > 50 && currentPrice <= 100) { decision = 'h'; } else { decision = 'b'; } // display the decision to the user finalDecision(decision); } void finalDecision(char decide) { switch (decide) { case 's': printf("it is time to sell the stock...\n"); break; case 'b': printf("it is time to buy more stock...\n"); break; case 'h': printf("It is time to hold onto your shares for now.\n"); break; default: printf("Illegal input\n"); } }