instruction stringlengths 71 71.9k |
|---|
In my shop system I'm using the PDO lastInsertId to assign the order_id to the products that belongs to it like this:
$connection->beginTransaction();
try
{
$sql = "INSERT INTO orders (customer_id, order_price, order_date, order_hour)
VALUES (?, ?, ?, ?)";
$query = $connection->prepare($sql);
$... |
Given:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
My Solution:
def sum_multiples(num, limit):
""" Calculates the sum of multiples of a given number.
Args:
nu... |
I’ve created a much cleaner, better designed version to my parallel sieve. I’ve implemented most of EBrown’s micro-optimizations but also revamped the code on my own (that is not in direct response to someone’s answer).
public class Sieve32FastV2
{
private static ArgumentException BadUpperLimitException(string pa... |
Given:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
Solution:
class Main {
public static int sumMupltiple(int num, int limit) {
int numOfMulitples = (limit - 1) / num;
... |
This is my first foray into OOP, so I'd appreciate any kind of advice!
Here is the problem description:
On the first line of the input, you will receive a number specifying
how many lines of input to read. After that, the input consists of
some number of lines of text that you will read and determine whether
or ... |
I am building my first Laravel web app and I have created a class to handle API requests for a model called Quote. In what ways can the code be improved or reduced?
<?php
namespace App\Http\Controllers;
use Illuminate\Http;
use Illuminate\Http\Request;
use App\SuperQuote\Transformers\QuoteTransformer;
use App\Supe... |
Sometimes, I need to change the color of <hr> elements in an email.
The only achieveable way is by using CSS. But not every email client supports CSS. Most clients delete separated stylesheets. And some even delete stylesheets altogether!
With a lot of trial, I came up with the following:
<font color="red"><hr align=... |
I'm working on my first Windows Forms tool for a project; this is my first time using C# extensively. Right now, my only objective is to be able to open an XML file and have the resulting XML in hand. I know this works, but I want to know if there's a better, or proper, way to do it.
There is also the issue that when I... |
Recently, I wanted to see how I might could track state changes to objects, and manage relationships (1 to 1, 1 to N, N to N) between types in C#. This was a really interesting project, and I'm wondering how it might be improved.
Full code
The full code can be found here, which includes a test project.
Basics: Tracka... |
I am creating a program that will analyse encrypted text using Kasiski examination in order to find possible key length:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <time.h>
char *file_get_contents(char *filename, char *fmode) {
FILE *f = fopen(filename, fmode);
fseek... |
I've made a concurrent implementation of the Big Step Giant Step discrete log solver in Go. I'm pretty new to this branch of math, but it seems slow. Any way to speed it up or is this the limit of this particular algorithm?
package main
import (
"fmt"
"math/big"
"runtime"
)
const increment = 1000
var proc... |
I'm trying to find patterns of different length in a given string. How can I improve it? Are there problems?
function find(pattern,str) {
var arr = [];
for (i= 0;i<str.length;i++) {
if(pattern== str.slice(i,pattern.length+i)) {
arr.push([i,pattern.length-1+i]);
};
};
if(!arr.length) { retu... |
It has been a very long time since I've used Python.
What I'm looking for: I would like to create a 6-by-6 random matrix where each component is either 1 or 2, so that there are 18 ones and 18 twos.
Attempt:
import numpy
import random
array = numpy.zeros((6, 6))
while (array == 1).sum() != 18 or (array == 2).sum() != ... |
Given:
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
... |
I'm using this code for checking if two List<T> are equal or not:
public static bool EqualsAll<T>(this IList<T> a, IList<T> b)
{
if (a == null || b == null)
return (a == null && b == null);
if (a.Count != b.Count)
return false;
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
... |
From https://www.chrisstucchio.com/blog/2013/actors_vs_futures.html:
A very nice feature of Futures is that they are highly composable.
Consider the following problem. I want to return an HTTP result to a
user based on the following criteria:
If a cookie is set, I'll return them a result from the cookie. If I
ha... |
This is a function definition from an external dll, that I'm calling from my code:
LZHAM_DLL_EXPORT lzham_compress_status_t LZHAM_CDECL lzham_compress(
lzham_compress_state_ptr pState,
const lzham_uint8 *pIn_buf, size_t *pIn_buf_size,
lzham_uint8 *pOut_buf, size_t *pOut_buf_size,
lzham_bool no_more_input_bytes_... |
I was wondering if there was a better way to do this. Would that mean there would need to be no client-side refreshing to show the cookies when they are created?
<?php
class cookieMonster
{
public static $lastDestroyed;
public function __construct() { }
/**
* Register a cookie with the browser.
... |
Missionaries and cannibals problem is a well known Toy Problem to learn basic AI techniques.
I implemented it using iterative deepening depth-first search algorithm. My state is represented by a 3-element vector <A,B,C> where A represents the side of the boat (0/1), B and C represents the number of cannibals and miss... |
The problem
The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043... |
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1... |
I'm trying to study network diffusion. I took the code form this. However, I would like to see if there's any potential to optimize the code to be faster and clearer. This is what I'm trying to do.
In a node, get all the successors and loop through to get the property in an edge to see if the probability is more than ... |
I have this array within array which contains a lot of values:
183 =>
array (size=3)
0 => string 'DE' (length=2)
1 => string '2015-06-09' (length=10)
2 => string 'GK' (length=2)
184 =>
array (size=3)
0 => string 'DE' (length=2)
1 => string '2015-06-08' (length=10)
2... |
I have prepared a small makefile for a small project, but I am trying to find what would be the best practices; up to now I have gathered these:
relatively idiomatic (typical structures, flows, var names for Least Astonishment)
define the products in terms of the inputs (if I have .c files and want an exec, why shoul... |
I've been learning Java for a very short period of time but with a couple of pointers, I've been able to put this simple VAT calculator together. If anyone could offer any ideas for improvement that'd be great!
import java.text.DecimalFormat;
import java.util.Scanner;
public class TaxCalc {
public static void ma... |
First I have method called in LoginActivity to call my login API. This is my Listener that reads user input and then passes it to a method to call the API:
OnClickListener onSigninClick = new OnClickListener() {
@Override
public void onClick(View arg0) {
String Pass = password.getText().to... |
I am a beginner level programmer and recently I started learning OOP,
so I made a simple war game
import random
cardsstart = 4 * range(2, 15)
cardsstart.extend([15, 15]);random.shuffle(cardsstart)
cardslen = len(cardsstart)/2
class cards:
def __init__(self):
"""intializes a set of cards(deck) to the object
... |
I have a regex pattern that will match some elements from a string and give them a particular name. For example, #^(?<foo>.*)$# will match the whole string and name it foo.
My problem is that the matches also contain the "classic", numbered matches.
For example:
<?php
$pattern = '#^(?<foo>.*)$#';
$str = '123';
$matche... |
When hashing a password, I understand it is best not to use functions such as SHA1 or MD5.
This function is working fine and I want to know if it can be improved to increase site security.
class safePassword
{
public static function makeSafe($password)
{
$salt = "mySalt";
$hash = hash("sha256", ... |
I am parsing the following line of code via a specific format.
Line is:
S|111111|87654321|Bar UK|BCreace UK|GBP|24/08/2010|
The Format is:
Index Field Length
S0 - 1
S1 - 6
S2 - 34
....
...
S6 - 10
I am validating using many if statements. Could anyone suggest a better approac... |
I was involved in some code-review discussions about UnitOfWork and Repository pattern implementation with EF, which put me in some sort of confusion.
Yes, I know that EF already implements UnitOfWork and Repository pattern, but the question is not about that. I am just asking for your opinion regarding existing code b... |
I have the following data structure that's obtained from a third party:
var data = [
["Parent1", "Parent1.1", "Parent1.1.1"],
["Parent2", "Parent2.1", "Parent2.1.1"],
["Parent3", "Parent3.1", "Parent3.1.1"],
["Parent1", "Parent1.2", "Parent1.2.1"],
["Parent1", "Parent1.2", "Parent1.2.2"]
];
Where c... |
I've just finished working on a multi-threaded network queue and was wondering where I could improve. I'm a little rusty when it comes to waits and such.
The idea is to queue up network actions whilst waiting for a form of network internet connectivity. I also added the ability to prioritize which network actions shoul... |
This provides (my own) implementation of ToBase64String and FromBase64String (since the .NET implementations suck), and a ToBase32String (since .NET hasn't one).
/// <summary>
/// Provides extensions to convert certain objects to certain other objects.
/// </summary>
public static class StringHelpers
{
/// <summary... |
Recently, I wrote a simple program to solve the change-making problem. Rather than the tabular dynamic programming solution (described in the link), I tried to write a solution that uses memoization.
usd = [25, 10, 5, 1]
def make_change(W, denoms=usd):
"""
Solves the change-making problem where W is
a giv... |
I would like to read a file into a list when I create the class below. Once the list is ready, I would like to access it outside the class in order to process more code based on the list which now contains my file. Can the code be improved upon?
class ReadFile(object):
def __init__(self, filename):
self._da... |
I have included almost all features that real poker game contains, but even tho I tried to make it as clean as possible, I think it can be done much better. I used inheritance to somewhat distinct player seating, getting ready for hand to actually playing the game, but then again some things as moving the button depend... |
I am developing a project that converts SQL server file to MySQL file based on some assumptions. I have written a function that takes the string source as input and it extracts the database name. Is there any way to improve the code?
public String getDatabaseNameFromMySqlServerFile(String source) {
String sourceFi... |
I am presently working on refactoring ReactJS code away from directly manipulating this.state and towards using this.setState() only (which I should have been doing from the beginning).
The contents of this.state in my application include containers with varying numbers of objects. They are entirely JSON-serializable, ... |
I'm designing a generic interface for a MessageEntry class for a .h file.
I'm looking for guidance on form and terminology (would I call this an interface/template/generic class?):
#ifndef cppmq_message_types_h
#define cppmq_message_types_h
template <class T>
struct MessageEntry {
public:
MessageEntry<T>() {}
Me... |
I have a couple of images in my database and I need to check if the images are still good or if they're deleted or corrupted. I came up with a solution but it's very slow. I was wondering if there was a way to make this faster.
img = 'http://some_image_cdn.com/images/image.jpg'
begin
Nokogiri::HTML(open(img))
rescue
... |
An easy, terribly written but working, Caeasar (Monoalphabetic) cipher implementation, with a GUI (Graphical User Interface).
Cipher.java
class Cipher {
static final String alphabet = "abcdefghijklmnopqrstuvwxyz";
public static char shift(char ch, int amount) {
return alphabet.charAt((alphabet.indexOf... |
I've been working on this user script to hunt for a specific string in an HTML webpage with the goal of finding the time at which it appeared. This feels needlessly complicated and I would like advice on how too condense and upgrade the code to more simply find the time.
// ==UserScript==
// @name Magma Time... |
I'm creating a program that averages four numbers - three from a file and one from user input. Simple enough. But the catch is, the professor is going to be deliberately trying to break the program.
I'd like advice in any regard, but remember the focus is on robustness.
import java.util.*;
import java.io.*;
public c... |
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.
HW1 - Validating Credit Card Numbers - Full description
A shortened problem statement:
Validate a credit card number by th... |
I'm a beginner in the coding world, and I've been learning Java recently. I tried to make a small text game with the limited knowledge that I currently have of Java. I would like you to tell me ways to improve my code, so that I can learn it better. I currently feel my code is a bit messed up, but at least it's a start... |
I'm writing a Telephone class and it has a method called getDigits which takes in a String parameter and returns the number that would appear on your phone if you typed in those letters the old fashioned way.
Example: Typing in "CAT" would return 228.
I wrote the following code and it works but I wanted to know if anyo... |
I'm new to Doctrine and had a hard time deciding how to get random rows within it without creating custom DQL functions or using a native query.
The solution I have come up with is below. This is within a custom repository for an Entity. I'm hoping for some constructive criticism in regards to it, however it currently ... |
Problem Statement
Suppose you have a string \$S\$ which has length \$N\$ and is indexed from \$0\$ to \$N−1\$. String \$R\$ is the reverse of the string \$S\$. The string \$S\$ is funny if the condition \$|S_i−S_{i−1}|=|R_i−R_{i−1}|\$ is true for every \$i\$ from \$1\$ to \$N−1\$.
(Note: Given a string \$str\$, \$str_... |
I am working through UPenn CIS 194: Introduction to Haskell (Spring 2013). Since I am not able to take the course for real I am asking for CR (feedback) as it could be from teacher in that course.
HW2 - Log file parsing - Full description
{-# OPTIONS_GHC -Wall #-}
module LogAnalysis where
import Log
parseMessage :: S... |
This is an accounting program (and my first attempt at a web app of any kind) where users need to get and retrieve objects from different JSON URLs and at different levels. Rails is used for the back.
I'd like to know if the following process is the best to use:
User clicks button to toggle some boolean value
Local JS... |
I have a very long switch statement with more than 18 cases. I want to make it more comfortable and easier for the maintenance, but I have no idea how ...
switch($key)
{
case 'male':
return $filter = array($gender , '=', 'male');
break;
case 'female':
return $fil... |
I wrote a simple script to translate (a subset of) StackExchange markdown to HTML. I used Regex for this task, but luckily I only had to use simple patterns.
Modularization
I also wrote a Regexp-generating function as I noticed that in Markdown you are always looking for things inside such and such symbols, I feel like... |
I'd like to get some feedback on an example web API I've put together. It's mavenized and available on GitHub here.
Setup
The only thing you'd have to change to run this locally is line 31 in src/main/java/com.example.config.PersistConfig.java:
String databaseLocation = "jdbc:derby:C:\\Users\\Kevin\\Desktop\\SpringExam... |
I am interested in hearing views on this new Module I am adding to an existing system to handle sale items from a 3rd party Software system. This system sends (XML) messages to our system, we need to look up our database and sell the item if present.
Before I continue going down the route I am, I would like opinions on... |
This project is from the subreddit for beginner Python projects:
The goal of the project is to create a program that allows the user to choose a time and date, and then prints out a message at given intervals (such as, every 3 seconds) that tells the user how much longer there is until the selected time. If the chosen... |
The following code grabs the HTML-encoded, multi-line content of a text field. It then splits the content on line breaks, and finally displays it with commas as separators.
I would like to have this code reviewed to see if there is a simpler way to grab the string, split and display it.
Note - I hated the idea of wri... |
I have setup agenda tasks to periodically retrieve and possibly insert new SE sites and tags in my MongoDB database.
Some things that bother me in particular:
Lots of code duplication
No string formatting to inject variables in it
Many callbacks -- is this the preferred way to work?
Updating/inserting entries in the d... |
I am working with MongoDB through Docker, and I have a terrible bash command to pull the Docker Machine IP so I can sanely connect locally.
export dockerip="$(docker-machine ls | awk '{print $5}' | sed -n '2p' | sed 's/tcp:\/\///' | sed 's/\:2376//')"
mongo --host "$dockerip" --port 27017
How can I optimise the docker... |
I wrote a method that takes an array T[] array (T is a type parameter) and a second array int[] indices. The method should remove those entries from array, whose indices are stored in indices. Then, the resulting array will be "returned" as an out-parameter T[] rest. Finally, there is a second out parameter T[] removed... |
Given
You’re given the pointer to the head node of a linked list, an integer to add to the list and the position at which the integer must be inserted. Create a new node with the given integer, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates ... |
This Haskell program just aligns the text lines on the given substrings.
I took inspiration from here, but my code is not golfed.
import Data.Function
import Data.Ord
import Data.List
import Data.List.Split
alignOn :: String -> [String] -> [String]
alignOn char lines = map padline lines
where
partBeforechar = h... |
I am posting this as a follow up to the Tic Tac Toe class in Python question. I have made extensive changes and rearchitected the code. I now have a board class, a game class, players and an application that ties them all together.
While at this point I have got only a 3x3 board, I have designed my code to be scalable ... |
I have implemented a function to produce a 32-bit checksum of a file using the following method: checksum = word_1 + word_2 + ... + word_n, where word_i is the 32-bit words the file consists of.
Here are several questions I'm very interested about:
Is the way I read file word by word correct or there is a better way? ... |
I'm coding for a function that checks the longest word (or words) in a string:
If multiple words are of the same size, those words have to be displayed.
If a single word is inputted, that word has to be displayed.
Words should consist only of alphabets.
The following code has been tested and displays the correct inpu... |
This code is working and was tested for over 10000 images. I have many headerless images, i.e images which are binary files with known dimensions. Some of the images have a visible area which is different from the size of the binary files which have padding.
For example, the image is 100x100, however the file size is 1... |
I'm trying to parse an object generated from an Excel file. The output lists each cell with its contents. If the cell is just a number then it remains a number but if the cell contains a formula (has attribute f) I want to make that a getter so whenever that cell is called the result is updated in case the other cells ... |
Is there a simpler way to implement this function?
function has_duplicates(arr) {
var myObject = {};
for (var key in arr) {
if (myObject[arr[key]])
return true;
else
myObject[arr[key]] = true;
}
return false;
}
console.log(has_duplicates(["foo", "bar", "baz", "quux", "foo"]));
|
I'm currently learning C with The C Programming Language by K&R and this is my current exercise:
Rewrite appropriate programs from earlier chapters and exercises with pointers instead of array indexing. Good possibilities include getline, atoi, itoa, reverse, strindex and getop.
This is my atoi solution with pointers... |
As an exercise I want to have a single window application (in Swift on Mac OS X) with 4 views, each controlled by an independent view controller and have their own XIB file. I have working code, but I feel I've done it the wrong way, so the question is have I used a bad design pattern?
My main concern is the empty view... |
I am working on an Android application for reading NFC cards. I came to a point when I needed to design an abstract class to streamline the process of creating views for visualizing and editing various forms of data by subclassing the abstract class with views like BinaryView, HexView, StringView, et cetera.
I became a... |
I want to generate some random data and store it in a container. I split the container into disjoint intervals using iterators and pass them to a thread function (I hope its body isn't important here).
There are several design-related questions here:
Is it a good practice to solve such task in this manner?
If it is, d... |
I'm working on a TopCoder problem which seeks to find the letters preventing an input sentence from being a pangram in all caps, alphabetical order.
MissingLetters.h
#ifndef _MISSING_LETTERS_H_
#define _MISSING_LETTERS_H_
#include <string>
#include <set>
#include <utility>
class MissingLetters {
public:
Missing... |
I'm writing a game in C# Monogame, and I've decided to make my project as modular as possible.
GitHub
At first, I've had a single project with a folder that's separated inside to other folders which represent different systems in the game (Items, Abilities, Stats).
I've started by making a .dll project for everythi... |
I'm trying to teach myself C++ from Stroustrup's Principles and Practice Using C++ (second edition) and I've gotten to the drill in chapter 4. The problem tells me to make a program that takes in a number with a unit of either feet, inches, meters, and centimeters, as well as log the largest and smallest numbers the us... |
This is my first experimentation with the producer-consumer problem (and thread manipulation in general), so any feedback on taboos and fixes is greatly appreciated!
#include <condition_variable>
std::condition_variable cv;
#include <iostream>
#include <random>
#include <mutex>
std::mutex mtx;
#include <thread>
// ... |
I have written a simple state machine. Comments and feedback are welcome.
#include <stdio.h>
#include <stdlib.h>
typedef enum Event
{
eEVENT_X,
eEVENT_Y,
eEVENT_Z,
}Event;
typedef enum States
{
eSTATE_X,
eSTATE_Y,
eSTATE_Z
}States;
int e = eEVENT_X;
int s = eSTATE_X;
struct state_transition... |
I have a number of messages with a payload as a list of items. My goal is to transform the message payload without losing the relation between the message and payloads.
Isn't it possible to rewrite the code to a single pipeline without creating an instance of a nested pipeline for each message?
using System.Threading.T... |
Given
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Solution
def max_factor(num):
"""Find the maximum prime factor."""
factor = 2
while factor * factor <= num:
while num % factor == 0:
num /= factor
factor += 1
... |
I've just created a method that toggles menu visibility. At the moment I've gone with an if..else which checks my flag and acts appropriately. Can anyone offer any suggestions on how to make this snippet better? Maybe it shouldn't all live in the same snippet? Maybe I should be combining the show/hide logic that's dupl... |
I've written this small generic library for the purpose of my Bachelor's thesis. It's fully functional and unit tested and I want to get as many opinions as possible regarding overall code quality (readability, naming, structure, coupling, cohesion, etc.).
GitHub (this project is licensed under the terms of the MIT lic... |
I have script for get three values (minimal numbers) from array :
$(document).ready(function(){
var _array = [1,2,3,4];
var save = 0;
var _new_array = [];
var nearDistance = [];
$.each(new Array(3),function(n){
if (_new_array.length < 1){
save = Math.min.apply(Math,_array);
... |
I'm looking at writing a simple proxy. At the moment I've got a logger, command line argument parse and simple daemon (it does nothing beyond logging).
Next I'll be looking at starting the network-related work, but before that I wanted to get a review to see if there's anything wrong with my basic approach at the momen... |
The following module AssertLibraryFunction improves upon CheckLibrariesExists in two respects:
It honors the optional argument REQUIRED of find_package: if the check fails, it raises a FATAL_ERROR. It also honors QUIET.
Its result is cached in a variable named ${LIBNAME}_${FUNCTION}. Therefore, argument 4 of CheckLibr... |
I am familiar with the simple use of QSqlQuery::prepare() and QSqlQuery::bindValue() as in:
QSqlQuery query;
query.prepare("SELECT name, address FROM members WHERE id = :id");
query.bindValue(":id", member_id);
query.exec();
In this scenario I show a list of people (members) to the user, all with a check-box in front.... |
I have many different methods like ones below, but is there way I could improve them and remove duplicate code ?
public static ADUser Load(string userName)
{
using (PrincipalContext pc = MyUtilities.GetPrincipalContext())
using (UserPrincipalExtension user = UserPrincipalExtension.FindByIdentity... |
I'm trying to create a list of subpaths from a flattened array.
Here's the starting point:
var flat = [
{path: "/" },
{path: "A" },
{path: "A.A"},
{path: "A.B"},
{path: "A.C"},
{path: "B" },
{path: "C" }
]
The goal is that anything under a parent would be a subpath of that. So the goal would look li... |
I created a form with title, body and tag input and there are 3 tables: posts, tags and post_tag.
Now I use this function to add new tags and attach them to the post
postcontroller.php
public function store(Request $request)
{
$input = $request->all(); //get inputs value
$tag = $input['tag'];
... |
I am using KnockoutJS to bind some values. I have a date value TimeByDay that I bind like this:
<span data-bind="text: new Date(TimeByDay)"></span>
But I would also like to transform the date on a different location and simply add a day to the TimeByDay value.
I can do it like this:
<span data-bind="text: new Date(new... |
I wrote this tiny library yesterday. The goal was to implement enums in JavaScript with type-safety. I modeled the implementation similar to enums in Java, since that is what I am most familiar with.
It seems to work like you would expect, but I wanted to make sure that what I did makes sense and that there isn't some ... |
I've been writing a program to improve my Javascript skills.
It's a very simple app for typing practicing.
var excercise = "The Battle of Westerplatte was the first battle in the Invasion of Poland and marked the start of the Second World War in Europe. Beginning on September 1, 1939, German naval forces and soldiers... |
Problem:
Given an sorted array of N distinct integers, find floor value of input 'key'. Say, A = {1, 2, 3, 5, 6, 8, 9, 10} and key = 7, we should return 6 as outcome.
How can I optimize my solution?
private static int CalclualteFloorValue(int[] _sortedarray, int l, int r, int key)
{
if (_sort... |
I was working on the binary Bayesian network classifier I asked about earlier.
See also Part II/II.
See also the next iteration of Part I.
TERMINOLOGY
We are given a directed acyclic graph (dag) \$G = (V, A)\$, where \$V\$ is the set of nodes and \$A \subseteq V \times V\$ is the set of directed arcs, and a weight fun... |
This is the continuation of Binary Bayes network classifier in Java - Part I/II
TERMINOLOGY
We are given a directed acyclic graph (dag) \$G = (V, A)\$, where \$V\$ is the set of nodes and \$A \subseteq V \times V\$ is the set of directed arcs, and a weight function \$p \colon V \to [0, 1]\$. For any node \$u \in V\$, \... |
I've created a Grid with a RecyclerView similar to the GoogleIO 2014's generic media player one.
GoogleIO generic music player
Mine
The thing is that the images doesn't load immediately, but with a delay, so I had to put that "dirty" code for add a crossfade every time an image is loaded.
Beside that, I just want the... |
I wrote this pretty straight forward begin and end overloads for istream_iterator.
Is this standards compliant? Any problems with usage?
#include <iostream>
#include <iterator>
#include <fstream>
namespace std
{
template <typename T>
std::istream_iterator<T> begin(std::istream_iterator<T> iter)
{
... |
In my project I need to have one class as singleton which must be globally accessible:
board.h:
#pragma once
#include "io/io.h"
#include "lib/drv/gpio.hpp"
class Board {
public:
static const unsigned int CORE_FREQ = 48000000;
static const unsigned int SYSTICK_FREQ = 1000;
volatile uint64_t tickCounter;
... |
Since I've looked far and wide for a good example of this to no avail, I have created my own using the JSONArray and JSONObject classes. It took me a while to realize that the push method for JSONObject overwrites everything previously pushed.
public static JSONArray getJSON(String url) throws IOException, JSONExceptio... |
This script allows you to practice your typing skills, as soon as you finish typing a new word appears for a non-stop typing experience. The code has in memory the top 100 words as per the Pareto Principle and Zipf's Law, of these, the top 10 are more common than the rest.
To start, type start.
Tested in Linux, Python ... |
The below code is a solution I put together for the Project Euler #11 question which asked to find the largest product of 4 numbers of any direction in a matrix (horiz, vertic, and diag all acceptable.)
Coding methodology: To me this is the most important. Is the algorithm I used feasible or mostly correct, if not how... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.