instruction stringlengths 71 71.9k |
|---|
I have a custom module to import nodes from a .txt file. (Drupal 7). My problem is I have a lot of nodes to import and this function takes so much time.
$operations = array();
$items = array();
$limit = 100;
$i = 0;
$regs = db_query("SELECT * FROM {table_import_apunte} WHERE field_processed = :processed", array(':pro... |
I am thinking of using this as part of a header file to give me a useful string-manipulation tool. Elements is size of dest to prevent overflow:
int copystring(char *dest,char *source,int elements)
{
int run,omitted=0;
for(run=0;run<elements-1;run++)//last reserved for'\0'
{
dest[run]=source [run];
... |
I am using the following function to upload videos (around 1 gb). It works properly.
My requirements are (these checks are being done in a different function using the mediainfo library):
check if the file is a valid video file
check video count
check audio count
check video resolution
etc
Is this the right way t... |
I'm developing an Android activity which asks user to enter start and end dates and times in order to know a certain period of time. After picking start date, user picks start time, and then he/she picks end date and time. I have TimePickers and DatePickers showing up one after another by setting flags, and I feel like... |
I have a list of Workshops, each having open days (Monday, Tuesday etc.) and open time and close time (which will be same for each day). Now, Based on the current time, I need to find out next 7 days available slots. A slot is of 2 hour and is available if any of the workshop is open in that 2 hour time. The first slot... |
What do you think of this way to generate a random number from the total rows in a table? I would like to create a page that random.php precisely generates a random ID and shows it.
require 'includes/config.php';
$pdo->query('SELECT id FROM xxxx');
$pdo->resultset();
$total = $pdo->rowCount();
//echo random id
$id = ... |
Background: A client side I made recently has a component that is made from several (20+) rss-feeds, and the feeds are mashed into one using FreshRSS hosted on our servers. For some reason, FreshRSS sorts it in a weird order instead of the standard date latest to oldest.
So the output looks weird with the latest post ... |
Is there a more productive way to do this? Is my code up to standards or up to best practices?
<?php
/*
FILE: index.php
AUTHOR: Darcey Mckelvey
PURPOSE: View Products
*/
// Define product information
$products[0] = array(
'name' => 'Sneakers',
'price' => 2... |
I have a database with these tables, where each mapping table represents a "many-to-one" relationship between the table on the right and the table on the left (click to enlarge):
I am selecting a single item from product and then adding on all of the other attributes through joins. Here is my current SQL:
SELECT
... |
I have got two generic methods to call against a service. Depending on call, some methods return an object (passed in params), some don't (void). Can this be further improved? I have got to this point after refactoring a lot and removing anything which was repeated.
private static TResponse ServiceCall<TObjectToPass, ... |
This program asks the user for input three times, and based on that input, calculates the chmod. I have included comments with questions and clarifications in the code.
I would like to have these questions answered and help with making the if ... in ... part shorter, if that's possible.
'''
This program asks the user f... |
I have written some code in Node.js that takes a date as argument and return all the possible combination of social security numbers.
I'd really appreciate some advice when it comes to these areas:
Coding style
Code structure
In my code I have included a brief description on how these numbers are generated.
personnr.... |
I created a string splitter in C++. It splits a string in a lazy fashion and makes use of forward iterators to sequentially supply the next token from the string until it runs out of tokens.
#include <string>
#include <algorithm>
#include <regex>
#include <istream>
#include <iostream>
#include <vector>
#include <utilit... |
This is my first MVC app. I'm looking for best practice feedback on how to best bundle the files that I need, the order to bundle them, the placement of the @render methods within the containing html page.
BundleConfig
namespace StateAssessment
{
using System.Web.Optimization;
public class BundleConfig
{
... |
I have two little projects that I've been working on.
One is to find all palindromes:
function palindrome(str) {
var replaceStrChr = str.replace(/\W/g,'').replace(/ /g,'').replace(/_/g,'').toLowerCase();
var arrayifyStr = replaceStrChr.split('').reverse();
var stringifyStr = arrayifyStr.join('');
if (replaceSt... |
I am building a CSV file parser, and in order to get the appropriate Object to represent different data types found on the parsed files, I wrote the following function:
public static Object stringToDataType(String valueAsString) throws ParseException{
// detections ordered by probability of occurrence in Buffer_Ba... |
I have a program which calculates the sum of the digits in the number 21000. The program is not beautiful and I was hoping for some advice on how to improve it.
The idea I have used is to create an array with the first element equal to 20. The first element in the array represent 100 the second 101 and so on.
Then go t... |
I've been reading about AngularJS services and factories, and how you should strive for a thin controller, but as the project I've been working on grows it seems more and more impractical with as interconnected as the app is. For a little background, I am using UI-Grid to display most data in the app (20+ grids) and M... |
Could someone review this PHP code to see if my pages are coded safely to not allow common attacks (SQL injection, XSS, etc.)? I would be thankful, of course, for anyone to point out other problems in my code as well.
// getpaste.php
<?php
$db_conn_config = parse_ini_file('../private/db_conn.ini');
$servername = $db_c... |
Thanks to Gurkenglas for the help with the previous iteration: Haskell - Pig Latin Translator!
Given the constraint that the newtypes are required, what improvements could be made to the following Pig Latin translator?
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
import Control.Monad (when)
import ... |
I'm a Windows sysadmin who is new to C# and "professional" coding. My background is in VBScript ("get it done") and I've apparently built up a number of bad habits. I'm hoping a review of the following code can help me do things the right way when tasks are still easy so that more difficult projects go smoother.
I ne... |
This is my first program and I wanted to know if there was any way to improve the design or cut back on unnecessary coding.
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int side1; int side2; int side3;
int side1s; int side2s; int side3s;
Boolean... |
This is pretty straightforward, but is there a better way to do this?
function isWithinBounds(obj, pos) {
var oXmin, oXmax, oYmin, oYmax;
if (obj.startPos.x < obj.endPos.x) {
oXmin = obj.startPos.x;
oXmax = obj.endPos.x;
}
else {
oXmin = obj.endPos.x;
oXmax = obj.startPos... |
What the following code does is:
The key field is column0 (where sometimes there could be single key, and sometimes keys separated by comma).
The rest of the columns are also either single or comma separated. But based on the single key value from column0, the goal is to collect all the values as a set in the rest of ... |
Today I wrote an implementation of the unification algorithm found in Temur Kutsia's 2002 paper. I didn't just do this for fun, it's related to other research I'm doing. I'm feeling more confident in my Haskell these days, and I was going to go through this code to clean it up myself but, since this is a pretty general... |
I wrote a Python PEG parser generator that takes a grammar as a string, and returns a parser. The parser can parse its own syntax, and is feature complete with the original PEG paper, with some additions.
I'm looking for comments on the implementation itself, and the interface it uses. I also put in effort to make sure... |
This is a fire and forget task from within an existing WebAPI service. The code below simply sends a log event (might be that a client has connected to the service to perform some task) to another service and if it fails should not return an error to the client.
I simply want the exception logged and forgotten about, m... |
I could not think of any better way to raise to power, except this, but how do I refactor it? I should only use while loop, not for loop, not x**y.
I shall not use pow(x,y)
result = 1
base = 3
counter = 1
degree = 4
while counter <= degree:
result = base * result
counter += 1
print("counter %d a... |
I'm trying to find the fastest way to enqueue and dequeue items concurrently in Go.
There are some restrictions:
it needs to be unbounded
Memory allocation should be low
Multiple producers
(Single consumer)
This is what I've come up with so far:
package queue
import "sync"
type Queue struct {
buffer []interfac... |
In order to code the tests for my number theory library (a collection of routines that proved handy for coding challenges) I needed a reference source for primes up to 2^16.
I did not want to reference code in other modules to get those primes because I wanted the buck to stop right there instead of passing it on, and... |
I have keyphrases abc, xyz, pqr, mno, etc. Text - " this text contains abc and mno", want to find whether text contains keyphrase string. I am looking for an efficient solution.
<?php
$content = " this text contains keyphrases abc and mno ";
$tags = array(array('key_phrase'=>'abc'),array('key_phrase'=>'pqr')... |
(See the next iteration.)
I have this class for representing exact fractions. See what I have:
Fraction.java:
package net.coderodde.math;
import java.util.ArrayList;
import java.util.List;
/**
* This class implements a fraction consisting of a numerator and a denominator.
*
* @author Rodion "rodde" Efremov
* @ve... |
I have this HibernateDAO.java Class:
public abstract class HibernateDAO implements DAO {
private static final SessionFactory sessionFactory;
private static final ThreadLocal<Session> session = new ThreadLocal<Session>();
private static final ThreadLocal<Transaction> transaction = new ThreadLocal<Transact... |
I completed a task: The objective was to create a method with 2 arguments: a number to count to, and how many char/numbers in the resulting string.
Result: Let's say that "number" is 5, so it will count: 01234543210 BUT it will also add spaces to the sides to complete the 2nd requirement "lenght", so if long is 15, the... |
I'm playing around with some ideas about how to read aggregates from events.
From a high-level view I would love to have this:
class Apply ev ag where
apply :: ag -> ev -> ag
which to define how an Event ev should change an Aggregate ag if there is an instance of this class for the pair (if there is none then the ag... |
I created a simple todo list program in C++ with the ability to store multiple lists, and add and delete list elements.
I'm looking for suggestions on how to make it more efficient, obvious features/checks missing, standard compliance, etc.
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;... |
I'm trying to write a Python class that creates a matrix of zeros, then uses a random number generator to pick 'seats' on the matrix. It changes the zero in that seat to a one, until the matrix is all ones. Can someone critique/correct my code? (I also want the 'agent' to check its surroundings on the matrix, and try 3... |
I'm trying to build a prfix tree. So, using the following dictionary 'and','anna','ape','apple', graph should look like this:
I've tried 2 approaches: using associative array and using self-written tree/node classes.
Note: original dictionary is something about 8 MB and contains >600000 words.
Associative array aproac... |
I know Perl now has given and when to simulate switch/case statements, but these are still experimental and are not guaranteed to be in future versions. Also there was a Switch module for Perl that existed in older versions, but it used source filtering and was considered not very good either so it went away.
Because ... |
I have assignment to generate argument based decorator I wrote like this.
def my_decorator(*deco_args):
def wrap(f):
def wrapped_f(*func_args):
if len(deco_args) == 1 and len(func_args) ==1:
return f(func_args[0], deco_args[0])
elif len(deco_args) == 2 and len(func_a... |
I have the following code below that creates a new Bitmap object the same as the original but to ensure that its PixelFormat is 24bppRgb. Does anyone know if there is a faster way to do this:
using (Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb))
{
using (Graphics g = Graphics.Fro... |
Writing code to validate emails is a thing I don't like. It's usually pretty pointless as there's there is actually no right solution, so it leaves me with a certain sense of existential dread.
I've written some code that delegates most of the responsibility to System.Net.Mail.MailAddress. Unlike MailAddress, it plays ... |
I am using RxJava with retrofit to get data from an API then filtering the data with a for loop in the onNext Method. Is there any way not to use the for loop and just use RxJava to filter or improve the code?
_subscriptions.add(
jamSpeakServiceApi.getAllWords()
.subscribeOn(Sc... |
I am working on a JSP MVC web application. I am confused about Thread-Safe Servlet concept. Following is my code, please tell me is it thread safe or not. Also, tell me the reason that why it is thread-safe or not thread-safe.
JSP Code;
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="... |
Given a string, count how many times a sequence of characters (in this code, the sequence is "ei") appears until the user types '#', then print the amount. I would like to know how to improve the code.
#include <stdio.h>
#include <inttypes.h>
int main(void)
{
char ch, cur_ch, last_ch;
cur_ch = '\0';
uint16... |
My main.c includes this header file. Please let me know how I can improve it. I did my best but I don't know much about code conventions in C (I come from Java and Python).
#define _XOPEN_SOURCE 500
#ifndef OPENSHELL_OPENSHELL_H
#define OPENSHELL_OPENSHELL_H
#define CMD_LEN 1024
#define EXPAND_ALLOC 1... |
I have implemented three stacks in a single array in Java. Any advice on object oriented design, coding structure, logical part or any sort of advice would be appreciated.
public class ThreeStack {
private int[] stack;
private int first, last, mid;
private final int midPosition;
public ThreeStack(in... |
In our swift project, there are multiple service classes that encapsulate functions, mostly network-api calls. They implement a protocol, and depend on other service classes, e.g. an authorization service or a network facade.
Their instances should only exist once, hence they are designed as singletons, with a private... |
I am making a connect four type game for my end of the year project in my programming class. I am about to start building off of the console based version I have made and add a GUI, but I feel sort of if-y about the win algorithms and am wondering if I could improve them. The code for those is below:
public void ... |
How can I improve or shorten my implementation of the Luhn algorithm?
int digits;
cout << "enter the numer of digits" << endl;
cin >> digits;
int Acc_num[digits];
int shuma = 0;
The shuma variable is the sum.
I created an array to store the digits from the string credit_card.
And asked the user how... |
For an application with a graphical canvas, I want to generate N points. But then I want to link those points, and I want to find the best path through those points.
I wanted to use a dynamic programming approach as N will be limited to a maximum of 15 points.
The following program works for me running
python dp.py
wi... |
I have the following database schema. My goal is to obtain a result set that lists the total badge points earned by each user. The badges might be earned in different courses. I want to include the courseid and the average score per course.
Users table:
| id | username |
|----|----------|
| 1 | user1 |
| 2 | ... |
I'm doing a Python course for beginners, and the last assignment was to create a program using shutil and wxpython that can copy new files (created in the last 24 hours) from one folder into another, while leaving the old files alone.
I feel like it's pretty messy, and there are multiple functions that do almost the sa... |
I did a task for an interview and the solution was not accepted. The task was to implement the class search function by name. The number of classes in the input data from 0 to 100000. Class names are no longer than 32 characters, contains only letters and numbers, are unique.
The application starts with flags -Xmx64m -... |
A while back I wrote a simple little PHP script that searches the Steam community market for any TF2 strange weapons with strange parts on the first page of results for that weapon type. It works by retrieving the listings for each weapon using curl, runs a regex to retrieve the internal JS variable containing the item... |
This is another iteration of my previous question.
This program plays the game Chopsticks using the Minimax algorithm. I search the tree using recursion. The problem, however, is that it is just too slow. I can only search with a depth of about six; otherwise, it just takes too long. How can I improve my code for perf... |
A friend asked me to write a pen-and-paper dice roller, so I put this together. I'm still pretty new to Java Swing, so I was hoping I could have some advice on how I handled the layouts and everything, and also just that everything is clean and efficient. He wanted to be able to type the dice roll in DnD format (ex. 4d... |
eg:
5
/ \
3 4
/\ /\
7 8 9 1
should print: 5 3 7 8 4 9 1
#include <iostream>
include <stack>
using namespace std;`
class node{
public:
int val;
node* left;
node* right;
bool istraversed=false;
};
void printdfs(node* root){
stack<node*> s;
s.push(root);
while(!s.empty()){
node *temp = s.top();
... |
def forward_date_range(start_dt, end_dt, span_days):
#
# Generate tuples with intervals from given range of dates (forward)
#
# forward_date_range('2012-01-01', '2012-01-5', 2)
#
# 1st yield = ('2012-01-01', '2012-01-03')
# 2nd yield = ('2012-01-04', '2012-01-05')
start_dt = datetime.dat... |
(See the previous iteration.)
I have improved my Fraction implementation taking the answers in the previous iteration into account.
Differences
Both numerator and denominator are now instances of BigInteger.
The class also caches a BigDecimal representing the value of the ratio with no more than scale decimals.
When c... |
I took a challenge from a web site. I aim to have a runtime performance as good as possible. My solution was accepted, though I think it is not the most efficient because I saw others having a faster solution.
Are there dos and don'ts in regard to C++ programing in order to try to get the best performance possible.
Thi... |
Like many others I've been writing a shell command-line interpreter that can do a pretty decent pipeline parsing, first it splits the command at pipeline char (|), then it splits the substring at unquoted whitespace so that a pipeline e.g. $ ls -a -h -l|awk'{print $3}'|sort -n gets represented with a matrix A where A[... |
This method converts a string to mixed case, id est mixedCase("hello, world!") -> "HeLlO, wOrLd!".
// Any input string is lower case already
private static String mixedCase(String input) {
// getAsCharacterList() simply turns a string into a List of Characters.
List<Character> charactersAsList = getAsCharact... |
A made a shipping calculator, which consists of one field that is validated.
jsFiddle
HTML:
<div class="container main-container" id="mainContainer">
<h1>Калькулятор доставки</h1>
<div class="content-container" id="contentContainer"></div>
</div>
<script type="text/template" id="calculatorSubmitBut... |
As an exercise I repeated this Java question, but in Go: Convert string to mixed case
The objective is for every second letter to be converted to uppercase.
Go string processing is relatively new to me, and I am looking for feedback on the use of the unicode package, any other go language or library features I should b... |
I wrote a C program that builds a social network graph of characters in a novel. The program takes two text files as input: a list of the names of the characters in the novel, and the file of the novel itself. The output is a list of name pairs, representing times where those two names occurred within five lines of eac... |
My task is to use the following pseudocode and improve it (make it run faster). Also I have to analyze the runtime of the given pseudocode and of my new code that i improved.
What does this algorithm do? It finds the smallest and greatest number in an array and creates the difference of them.
Pseudocode (given in task)... |
The following query is taking over 800ms to run, and returning 300 rows. When deployed to SQL Azure, it takes much longer on an affordable price tier.
SELECT
Tests.Id,
Tests.Title,
Tests.AuthorId,
Tests.[Status],
Users.FirstName + ' ' + Users.LastName AS AuthorName,
(SELECT
COUNT(1)
... |
I'm trying to make a small parabola calculator just for fun. Is this code good?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define _X_UNTIL_Y(q,w) \
while (argv[1][q] != w) { \
q++; \
}
#define _ATOI(s,d,f,g) \
strncpy(s, ... |
I have written a simple PHP Script that takes $_POST input and uses it to add data to a .json file. Given the security flaws in my last post, I wanted to post this just to make sure. I can't see anyway for someone to attack my server using this program (especially because this is a script for an internal website), but ... |
In my application I have an accounts model:
class Account < ActiveRecord::Base
belongs_to :user
has_many :invoices
end
The Account model belongs to the User model. After the user is created, some default accounts must be created:
class User < ActiveRecord::Base
has_many :accounts
after_create do
Account.c... |
This is a class which provides a simple event system mechanism:
template <typename T>
class EventChannel
{
private:
using idType = unsigned int;
static idType& getId()
{
static idType id = 0;
return id;
}
static std::unordered_map<idType, std::function<bool(T)>>& getHandlers()
{... |
I have a WPF project with Prism 6 and EF6. In my project I have a MainTabModule which has four ViewModels. One of these ViewModels is called ContactViewModel.
The MainTabModule will initialize and resolve my EF context and will also resolve my services. Finally I register my views to the regions in the Shell. This mean... |
I'm trying to make a small program which takes a number (form 1 to 1000) and shows the primes between 2 and that number. Right now I have a quite functioning program (except a couple of bugs), but the problem is that it needs a lot of cycles. In the worst case scenario (limit = 1000) it takes roughly 2 million cycles t... |
Based on the previous question, I have improved it to make it insert regular function. Also, I have implemented a new template approach to obtain the signature from any function by testing its operator().
I would like to know how I can improve it further.
#include <functional>
#include <typeindex>
#include <string>
#in... |
I am trying to learn C coming from Python. Below is an implementation of bubble sort, slightly optimized. Any advice on best practices, readability, use of macros, and edge cases would be greatly appreciated.
// Int Bubble sort slightly optimized
// USAGE: ./bubble_sort 7 3 5 4 0 1
#include <stdio.h>
#include <stdlib.h... |
The purpose of the following function is to find all non-empty directories, and the files in those non-empty directories. It recursively checks each directory on an SFTP server to see if it has any files, and if it does, adds it to a default dict using the path as the key. The function uses paramiko.SFTPClient and stat... |
I have refactored a for loop into a function. I'm still a beginner at using C utility functions such as strtok, strdup, malloc andstrcpy. The program makes the correct output for another program (my program is a shell command language interpretor) showing that I have 1800 lines of code:
$ cat *.c *.h|wc -l
{cat} {err... |
I've a sample code to create a simple menubar here which works, but I'm not sure if that's the best way to code it. Can somebody please validate if there is a better way to do the same?
In short
I've create a sample page with a directive called <menu-bar>
<menu-bar></menu-bar>
The directive merely points to a templa... |
Interview Q: Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example: Given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.
For this problem, return the maximum sum.
My solution (pseudocode and code) is below. ... |
I'm very new to Python, and so I'm trying to learn it by doing simple programs, like a calculator. But I don't know if this is the "Pythonic" way to do it, or if I am making beginner errors.
So could someone please tell if something is wrong with it, and how to improve it?
Here is some sample input and output:
Enter t... |
I have two Dictionaries with around 65,000 KeyValuePairs each. I used foreach and if-else statements to compare them and get values, but it goes very slow. How could I optimize my code and gain more speed?
private void bgwCompare_DoWork(object sender, DoWorkEventArgs e)
{
var i = 0;
foreach (KeyValuePair<strin... |
I discovered the FizzBuzz test while looking up something else on stackoverflow, so I decided to try it and see what I would come up with. I'm kind of new to jquery and JavaScript, so I'm looking for a critique on my code. What can I do better? Changes? Simplifications?
My priorities on this were -
Maintainability &... |
I found myself wanting to brush up on some notions about parsers and grammars and, at the same time, to exercise my Haskell - I am a Haskell newbie; moreover, I haven't touched the language at all in a couple months.
You can find the complete result here, and, separated by hrs and without the module boilerplate, pasted... |
I made a program that can modify a list using commands that the user enters.
The commands that are supported are (used from actual program):
/add [value1] [value2] [valueN]... - Add a value to the list
/rvalue [value] - Removes a value from the list
/rindex [index] - Removes the value at the specified index from the l... |
My today's goal was to create a function, which would evaluate the entropy of a given string password. It's mostly about how random the password is.
This little code is based on the C# code from Jeff Atwood answer post on Calculating entropy of a string
Based on the wikipedia article I checked this as ok, still I am un... |
I've written tests that use Bash for testing a custom shell. I think the tests work but I'm sure you know better because this is my first test I write this way.
#!/bin/bash
echo "-- Testing our implementation of OpenShell --"
echo ""
echo "- If you have any problem in passing a test read the corresponding"
echo "- sou... |
I'm trying my hand at an address book and the goal is for it to have a bit more of error prevention. For instance, for the key "phone" to have 10 digits, and not allow alpha characters at section 4. I believe I have formatted this properly to the best of my ability. I understand this is very elementary as I'm new to an... |
def age_post(post) do
birthday = Timex.date({post.birthday_year, post.birthday_month, post.birthday_day})
now = Date.now
years = Timex.diff(now, birthday, :years)
Integer.to_string(years) <> " ans"
end
I'm quite new with the elixir language, I'm pretty sure you can get the same result than that... |
I have written my own solution to the Reader-Writers problems using semaphores based on the psuedocode from Wikipedia. I would like to gauge the correctness and quality of the code.
import java.util.concurrent.Semaphore;
class ReaderWritersProblem {
static Semaphore readLock = new Semaphore(1);
static Semaph... |
I have a response String as shown below which I need to parse it and store it my class. Format is shown below:
task name followed by this dotted line ------------- which is also fixed
and then just below key:value pair. It can have many key value pair
Below is the response string.
abc-------------
Load:79008
Peak:49... |
defmodule Baby.Post do
use Baby.Web, :model
schema "posts" do
field :cover, :string
field :email, :string
field :firstname, :string
field :lastname, :string
field :birthday_day, :integer
field :birthday_month, :integer
field :birthday_year, :integer
field :description, :string
f... |
I am preparing for a coding interview and I have the following questions:
Find the biggest positive number sequence in the Integer Array.
If Input is [1,2,5,6,-7,5,7,8,5,6,7,-6,7,0], then output should be
[5,7,8,5,6,7], which is the longest positive digit sequence.
Below is my code for the above program:
public c... |
I wrote a C++ implementation of a sparse table (I wrote it for an arbitrary function) and I want so much to ask for a review. I'd like to know how I can make it better, especially the consistency of the code and the design.
Explanation:
For example, you want to solve the RMQ problem with a lot of queries. You can preco... |
I need a function to remove duplicated pairs from a list. The following is example list:
a = [1, 1, 1, 2, 3, 5, 4, 4, 5, 2, 3, 3, 2, 3, 1, 6, 6, 6, 6]
I need remove all pairs [a[i], a[i+1]] if a[i] == a[i+1] until all such pairs eliminated:
[1, 1, 1, 2, 3, 5, 4, 4, 5, 2, 3, 3, 2, 3, 1, 6, 6, 6, 6]
[1, 2, 3, 5, 5, 2, 2,... |
I've created a simple utility class for use in my Unity2D project, which allows a Sprite to have separate sprites for when it is facing East, North, West, or South (that's the order that z-axis rotation places them in). There aren't too many Unity-isms in the code, and the part that I'm most concerned with is the inter... |
This is a simple pool allocator, based (to at least some degree) on a previous answer. The basic idea is pretty simple: allow a user to allocate objects of some type quickly (in relatively large contiguous chunks) and only free objects when the allocator itself is freed, then destroy all the objects and free the memory... |
I have a routine for determining the derivative of a function using the y-intercept (B) to infer the finite difference step (h). Instead of directly using smaller and smaller h, we can solve for the slope m in y=mx+B with a given B. That B represents a specific h after some substituting and simplifying where B = f(x)... |
I have a text file with the following three line pattern with blank lines in between. My script sorts alphabetically by each person's last name and preserves formatting. I would love to see other options to improve this in Bash. For example, the group command that redirects into final.txt repeats a lot. Also, it would ... |
I am studying Gang Of Four design patterns and I want to implement a builder pattern in Java.
It seems there are two options to build a builder pattern:
Using two different classes: A target class and a builder class
Using a nested static inner builder class inside the target class
Using builder class as a separate c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.