instruction stringlengths 71 71.9k |
|---|
I have the following model:
# == Schema Information
#
# Table name: clients
#
# id :integer not null, primary key
# first_name :string(255)
# last_name :string(255)
# email :string(255)
#
class Client < ActiveRecord::Base
def full_name
if first_name.blank? && last_name.blank?
'Na... |
Being my first time archiving data to the file system, I would like to have my code reviewed. This simple test project works as expected, but I want to see if what I am doing is following best practices. You open the app, put in text for the textfields, press button and strings are saved and displayed in labels. Whe... |
I'm trying to detect deposits that a user will make. I added explainatory comments inline.
Can you spot any flaws in it?
var _ = require('underscore')
var check = function(client, site) {
// check last 10 transactions
bitcoin_client.cmd('listtransactions', '*', 10, function(e, transactions) {
if (... |
Is this OK? (.Net 4.5)
try
{
StreamReader sr = = new StreamReader(ValidFilePathName);
line = file.ReadLine();
While (line != null)
{
line = file.ReadLine();
}
sr.Close();
}
catch
{
// blah Do nothing
}
I feel like there is something wrong with my pattern here. My concern is that whe... |
I am writing a card game in Javascript. The game is played with a 32 card deck.
When a card is selected to be played by a user, i do a validity check on the server to check whether it matches the games rules.
These are
A card may be played when it matches either the color or the value of the last card on the stack
If ... |
I have two working configurations that, on the surface, seem to do the same thing. They both accomplish the functionality that I need:
location ~ ^/(css|images|js)/ {
location ~ '^/(css|js)/[0-9]{8}-(.*)$' {
alias /$1/$2;
}
root /server/path/to/web/root;
}
AND
location ~ ^/(css|images|js)/ {
re... |
I cleaned a big repository for my team with this Python code. My goal was for every developer in my team to check if some bad email are in the commit, and replace the information by the good one. I use git filter-branch and a for loop in bash.
Because I can't make an array in an array in bash, I created a Python script... |
I am pretty deep into building a very multi-faceted little app in Excel with VBA. It does a number of tasks, all centered around using OPC to get tag values from several PLC's and doing various things with the info, like publishing a webpage (using a module I found, not mine), creating log files and tables and soundin... |
I had already solved this problem, but in an unnecessarily convoluted way that seems too specific. Can this be done better?
From a list:
(8 "layer-name" 10 x1 20 y1 10 x2 20 y2 10 x3 20 y3)
8, 10 and 20 are the "key-words" for layer-name, x-coord and y-coord respectively. The actual values follow the "key-words".
Re... |
int i = 0
for ( expectedErrors in errors ) {
final List<String> actualErrors = new ArrayList<>()
actualRequestMessages?.get(i++)?.errorData?.errors?.each {
item -> actualErrors.add("${item.message}")
}
assert [ ] == ((actualErrors - expectedErrors) + (expectedErrors - actualErrors)), [expectedEr... |
I'm writing my first C# Windows Store app and am learning C# from scratch. I'm trying to implement MVVM as I understand it and object orientated patterns, obviously though I'm expecting to be doing it wrong so looking for pointers as to what I should improve.
Below is a method that gets called when a user either click... |
I'm piecing together an Enemy script to attach to my characters. This is the portion that related the a game objects ability to patrol to given locations. Basically, patrolPoisitions are exactly what they say; they are defined in the editor. This is only the pertinent portion of the code, so there might be some straggl... |
I am working through challenges at CodeEval.com and wanted to get your input on my code for this challenge.
Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is.
... |
The question for reference:
The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?
answer: 6857
I'm looking for general feedback as to style and particularly usage of the STL. Efficiency is a concern but a simple link to a better algorithm will suffice.
#include ... |
I have two programs doing this task correctly, but at first I'm not sure if the code is correct (I mean absence of not efficient and superfluous pieces of the code). Then, I can't choose which one is better and smarter. Couldn't you do it for me?
First:
int n, p, q;
scanf_s("%d", &n);
p = 1;
q = 2;
char flag = 1;
w... |
Just wanted to gage how solid this code is. With moment cracking down on lazy formatting I thought this was a good way to parse the string for what format to use.
var string = $this.attr("data-date");
var withoutTime = "YYMMDD";
var withTime = "YYMMDDHHmm";
var format = function(){
if(string.length == withoutTime.len... |
I'm expanding the functionality of this SO answer.
Mainly I'm focusing on:
You can add as many handlers as you want.
You can remove (i.e. cancel) the handler.
You can receive the sender parameter in the handler closure.
You can add "oneshot" handler.
import UIKit
extension UIControl {
private class EventHandler... |
There was a fairly strangely written RPSLS game on Stack Overflow here.
That inspired me (read: I was bored and figured it would be fun) to write a better one. But I'm not sure what else there is that could be done to make it prettier.
This is my latest version:
public class RockPaperScissors {
public enum Choices ... |
Here is a "hello world" simple skeleton I wrote to get started on an HTML5/javascript game. I converted it from a python example provided in Coursera's "An Introduction to Interactive Programming in Python" which demonstrates how to start moving a ball around a canvas using arrow keys.
I did this as a learning exercise... |
I have a list of strings where I want to find the index of a first- and second-choice video compressor.
Logic: If the first choice is available, return its index. If not, and the second choice is available, return its index. If not, return zero.
Here is what I have now:
List<string> availableVideoCompressors = GetAvail... |
For example, the following row:
"a+12.3456-b-0.456789+1.3-45678"
will be transformed into
"a+12.34-b-0.45+1.3-45678"
That is, we need to cut out the figures after the point from the third figure. The signal of the row's end is the sign '&'.
With the getchar and putchar functions:
char c = 0, c_ = 0,flag=0;
while ((c = ... |
Today I was trying GSON after a while and went to the YQL console to run this query:
select * from yahoo.finance.xchange where pair in ("EURUSD","GBPUSD","INRUSD","JPYUSD")
and get back this JSON:
{
"query": {
"count": 4,
"created": "2014-12-11T18:41:23Z",
"lang": "en-US",
"results": {
"rate": [
{
... |
I have tests for simple POJO class ProgressableItem (i.e. the one which has attributes total work and work done).
I use JUnit 3 (it's from Android application).
public class ProgressableItemTest extends AndroidTestCase {
private ProgressableItem item;
@Override
protected void setUp() throws Exception {
... |
I have this little piece of front-end code, and I had a little code smell about the handling of errors.
request
.post(('/api/comment/:id/upvote').replace(':id', this.comment.id))
.end(function (err, res) {
if (err) {
log('Fetch error: %s', err);
return classes(targetElement).remove('sel... |
I have been solving the problem from UVA 10474. In this problem, there will be marbles with numbers written on them. For example suppose five marbles with numbers 50 , 43, 43, 43, 2, 90, 44. There will be several query with number and position has to be told in a sorted sequence. For example after sorting these looks l... |
Today, I created an input class with a method to check whether or not input via GET/POST exists, and another method to retrieve input from either GET/POST, without having to check both individually.
class input {
public static function exists($type = 'post') {
switch ($type) {
case "... |
I am just learning how to code in Ruby now with no prior experience. This is 3 towers of Hanoi where the user selects where to choose from and where to go with each disc, and not to have a bigger disc on top of a smaller one. It works (I've played it), but I repeat my code A LOT! Is there a better way to write this wit... |
The situation is this: I have a bunch of servers which are synced so that they all have the same data. Unfortunately, a disaster happened and the servers are all out of sync. My task is to re-sync all of the servers so that they all have the same sets of data. That is, I need to ensure that each server has a copy of ev... |
I wrote some code to parse Lua 5.2 strings in Lua 5.1, using patterns. It works perfectly as far as I tested.
local squote = "'"
local dquote = '"'
-- escape "sequences"
local escapeSequences = {
a = '\a',
b = '\b',
f = '\f',
r = '\r',
n = '\n',
t = '\t',
v = '\v',
['"'] = '"',
["'"] = "'",
['\\'] ... |
This here is a function that adds a graph node, with a unique id to an x,y matrix.
The rules are that :
The node id must be unique
Only one node can exist at a given coordinate.
Here's my function that attempts to add a node with given id, at given x y coordinates .
def addNode(self, node_id, x, y):
if self.no... |
I am working on another challenge from CodeEval.com and this is a bit harder. I would like to get some feedback on my logic of solving the challenge. Also there is probably one edge case that I missed because when I submit it to CodeEval I get different results. Once I received 95% correct and another time 100%.
The... |
Given the following definition of Cons:
data Cons a = Cons a (Cons a)
| Empty
deriving Show
I implemented a flatten function.
It's mean to work exactly like concat :: [[a]] -> [a], but for Cons.
flatten :: Cons (Cons a) -> Cons a
flatten Empty = Empty
flatten (Cons (Empty) ys... |
I simply need to check if a country is part of a particular continent (only one). The continent has around 50 countries. The list is constant and must be initialized at the time of creation. Which one of the solutions below is a better approach from performance point of view?
Having all the counties in a single strin... |
I am currently working on a class to make objects and vars available to child classes while attempting to avoid a singleton. Each child with dependencies extend this class and pass params (var names) of required dependencies. If parent construct is called and params is empty full registry is set.
Example of Registry:
c... |
This plugin is for article pages that has a very long main content (left side) and a shorter sidebar. When the user scrolls down mostly the right part will be white space.
What this plugin does is make the sidebar stick or make it fixed past a point and will stop sticking when it collides with the bottom part or a foot... |
I am wondering what the best practice for updating a list that only accepts unique items. Right now, I have a button that loads data from a database into a list. I can press this button numerous times to check if there is any new data in it. Here is the method I created:
private void loadNewDataFromDatabase()
{
... |
So I have multiple websites running under apache2 virtualhost - and I wanted to use GoAccess to process the access.log for each site.
The directory structure is like so:
/home/www/site1/html
/home/www/site1/log
/home/www/site1/stats
/home/www/site2/html
/home/www/site2/log
/home/www/site2/stats
Some sites contain two... |
Definition: A proper divisor of a natural number is the divisor that
is strictly less than the number.
e.g. number 20 has 5 proper divisors: 1, 2, 4, 5, 10, and the divisor
summation is: 1 + 2 + 4 + 5 + 10 = 22.
Input
An integer stating the number of test cases (equal to about 200000),
and that many lines follow... |
I have made a non-threaded version of counting words. The result was unexpected the non-threaded version was faster than threaded-parallel version.
Non-threaded version:
//
// program name: WordCounter
//
// usage: C:\>WordCounter.exe test.txt test1.txt
//
#include <future>
#include <iostream>
#include <iomanip>
#incl... |
This my first program in Haskell. I'm organizing a ping-pong tournament and I want to calculate a tournament table automatically. The table should contain scores in all games and some statistics (points, wins, losses, balls, ...). The input is hardcoded directly in the Haskell file.
import Data.Tuple
players = ["John... |
I have the following function that takes JSON and turns it into table rows:
function addDataFromJson(json) {
var data = json.data;
var rows = '';
$('.uiGridContent tbody').html('');
for (var i = 0; i < data.length; i++) // for each row
{
var columns = '';
for (var b = 0; b < Object... |
Linq methods like Distinct need IEqualityComparer object. But sometimes I just compares two objects and to create Comparer instance for that is seems redundant. So it would be nice to use static Equals method. But I'm not sure does not it break some guidelines.
public class ByteArrayComparer : EqualityComparer<byte[]>
... |
I'm trying to reduce the if statements and simplify this create action.
def create
@order = Order.create_from_result(JSON.parse(params['order']), JSON.parse(params['customer']))
# Ensure order saves before processing payment
if @order.persisted?
# Braintree transaction
result = @order.make_payment(params[:paymen... |
Here's a simple program I wrote to teach myself the basics of using a mouse for a potential HTML5/JavaScript game. The thing that tripped me up was event.clientX and event.clientY don't return the correct values as they stand. One has to get the offsets of the canvas object, which in turn may be a child object of other... |
For my web application I have to generate a sequence of following format:
<year><sometext><month><sequence>
For example:
2014TOYS11000001 -> for first sequence of month of November this year. If month has changed, we have to reset the sequence to 1.
The application is Spring-based, and I have used NoSQL (Mongodb) to... |
Using Backbone/Marionette, I'm building a simple widget that looks like:
I'm hoping to get some feedback on my approach because I think I may be doing it wrong.
jsfiddle
// widget/invites/person.js
var Person = Backbone.Model.extend({
defaults: {
name: ''
}
});
// widget/invites/people.js
var People =... |
I was looking for a way to calculate a score 'x' for each pair of elements in two separate arrays. The goal of the code is to return an output array containing the score for each entry in the input arrays.
from math import sqrt
import numpy as np
downs = np.genfromtxt('path\file.csv', dtype=long, delimiter=',', ski... |
I have a model Users that each instance have 3 features. It was alright until I wanted to tell if this instance can do the 1st feature, the 3rd or all.
I did a migration:
class AddStatusFeaturesToUsers < ActiveRecord::Migration
def change
add_column :users, :status_feature_a, :boolean
add_column :users, :stat... |
I wanted to see where I lined up with other users on tag badges (I wanted to count just bronze but figured I would start with all of them to start out with).
Here is the query that I ended up with:
SELECT
Users.Id as [User Link]
, Users.DisplayName
, COUNT (Badges.Id) AS Number_of_Tag_Badges
FROM
Badge... |
I'm trying to improve my code and i want to know if this is the best way to write this Switch or if there are other methods.
for(String word : words) {
switch(word.toLowerCase()) {
case "a":
a++;
break;
case "the":
the++;
break;
case "bird... |
What do you think about this implementation of quicksort? Is it possible to make it shorter?
/**
* 3-way quicksort
* <p/>
* Choose a value an put the greater values to the right, lowers to the
* left, and equals in the center. recursive. O(n^2) but avg O(n log n). Memory: In place
*/
public static void quickSort(i... |
I'm after creating an insert function for a 2 4 tree in Haskell. I'm just wondering if this is the best way to implement it (especially when handling the Root4s), or is there a better way. I know it's quite bulky, but I couldn't see another way of handling the roots with 4 branches.
insertRoot :: Ord t => t -> Tree t -... |
I'm learning how to develop for iOS and I want to begin with nib's before storyboard to get a better understanding.
I just set up 3 view controllers:
HomeVIewController
StackTableViewController
CreateViewController
The HomeVIewController.h:
#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController
- ... |
When you press CTRL you activate the "Register" mode. In this mode, when you click, the program stores the X and Y of the mouse. To turn it off, you press CTRL again. When you turn "Register" mode off, a message option box pops up asking "Perform actions?". If you respond "YES", the program will click on the registered... |
I would like to get feedback on this, which are just simple Response/Request classes.
I tried to keep it simple, so I made two interfaces and two classes:
RequestInterface.php
Request.php
ResponseInterface.php
Response.php
The use Foo\Storage\ArrayHandler as access; is just a class to access and set arrays, so I woul... |
I don't write C all that often, so things to look for would be memory leaks and such. I also recognize that I'm not validating the user input as well as I could - I could use some feedback on how I might do better at that with this particular problem. I'm interested in hearing everything you find wrong with this code... |
I noticed that I've a HUGE bottleneck in this following function of mine. I can't see how to make it faster.
These are the profiling test results(keep in mind that I'm using a PyQt GUI so times can be stretched):
cProfile Results
def write_workbook_to_file(self, dstfilename):
self.populaterownumstodelete()
# ac... |
I was asked this in an interview yesterday. I could add whatever methods, members and constructors I wanted but I couldn't change the signature of the provided toString and append methods.
I implemented something like this:
import java.util.ArrayList;
import java.util.List;
public class StringBuilder {
private List... |
We are building a game and we have a dialog system. Dialogs may open and stack on top of one another.
When every dialog opens, it registers itself to handle the BackButtonPressed event:
AppHelper.OnBackPressed += HandleBackPressed;
When the dialog closed, it unhooks from the event:
AppHelper.OnBackPressed -= HandleBac... |
This is my first by-self written code. Looking for advice on what not to or to do so I could deal with any bad habits now. It's a guessing game and works perfectly fine. I just wanted to know if more experienced programmers would see any huge mistakes in the coding style.
Basically it generates a number and then asks ... |
I have a dashboard to manage a learning center system. There are scenarios like admin create learning center and define a classroom in it and then assign some courses in it and assign students to those courses and assign a teacher for each courses.
In order to achieve this, I have to create lot of dropdownlists such a... |
Previous question:
Counting words in files - follow-up
I have fixed punctuation problems in my previous code by using template, because it is easy to understand and my focus on template mechanism. The same applies for optimizing code.
Source code
//
//program name: WordCounter
//
//usage: C:\>WordCounter.exe test.txt t... |
I implemented a version of the popular Tic Tac Toe game. It currently only supports two-player mode, but I'm planning to add artificial intelligence for user vs computer mode (which I don't know how, yet).
#include <stdio.h>
#include "cmdio.h" /* this defines getnum, yesno and select_menu */
#include <stdlib.h> /* exit... |
I have been trying to implement the Hash Table function in Java and here is what I came up with. I would just like to get an opinion on this work. Would there be a better way or any improvement to make to this code ?
HashTable.java : basically contains all the hastable functions to create the table, add a node and retr... |
This class can be used to access the Google Translate web interface and get translation result for large text (split up into sentences).
The Signal class is copied from here.
#!/usr/bin/env python3
import urllib.request
import urllib.parse
import re
import traceback
from multiprocessing.dummy import Pool
from bs4 impo... |
I recently learned that sometimes, when running code, the compiler(or whatever it is) ignores when there isn't enough memory for say, a string, and interacts with the string normally.
Yes, I know this is a "lucky" thing that shouldn't happen, but sometimes does.
I often find trouble when I'm trying to interact with the... |
Given a Python file containing a Python script written with bad style, this script will output a review adressing its problems.
RESERVED_KEYWORDS=['abs','dict','help','min','setattr','all','dir','hex','next','slice',
'any','divmod','id','object','sorted','ascii','enumerate','input','oct',
'staticmethod','bin','eval','i... |
Version 2 of A translator class in Python
Changes:
Style compliant to PEP8
Both orig_str and filename allowed to be any object with __str__ method
Improved type annotation
Multiprocessing is used to increase performance.
#!/usr/bin/env python3
import urllib.request
import urllib.parse
import re
import traceback
from... |
I searched for a notification script that shows inbox and rep change items on the browser tab in stackapps.com but either they didn't work or were outdated.
So, I've done this raw script myself and want to make it fool proof and robust:
This is my first ever user script. So want to make it better. (Even if it wasn't th... |
These are questions from an interview:
Reverse a string
Find matching anagrams in a word list
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class ReverseString
{
public ReverseString()
{
stri... |
I've been working on a basic Android game these days, but I'm a bit uncertain about my setup and need some advice. The basics of the game are simple: there are characters running on your screen and some of them perform specific actions at specific time intervals.
The code is pretty easy to follow if you know that it w... |
When a Wizard casts the Monster Summoning spell, all of the summoned monsters shall follow his command. Should the Wizard interact with his summoned monsters directly (what are the potential pitfalls in this case?) or indirectly through a mediator?
In my code below, I'm using a mediator, but since such a specialized m... |
For Project Euler I've implemented a BigRational. The functionality is rather limited, just things I needed or will probably need soon. The style departs a bit from the standard.
I found out that using the fancy names "numerator" and "denominator" made the code very hard to read with tons of long and broken lines full ... |
Recently, I wrote a C header file that defines a new type called HashMap that allows for the storage of key/value pairs.
I am just learning about the wonders of void pointers and as I use them, I get lots and lots of warnings about making pointers without a cast. The header file itself does not yield any warnings, but ... |
Previous question:
Counting words in files - follow-up 2
For simplifying the code, I have implemented std::regex rather than templates.
How can I improve this code further?
//
//program name: WordCounter
//
//usage: C:\>WordCounter.exe test.txt test1.txt
//
#include <iostream>
#include <iomanip>
#include <fstream>
#i... |
I've been asked to output the users name, what day of the week they were born on, output a line from a poem corresponding with the day they were born on, and their scores for a vark test. We were told to calculate the month of birth as a number and find the number/ month.
This is the first bit of code I've done and I'm... |
I'm writing a little tool for mangling MP3 collections and, as a challenge, I decided to write in in Hy, a dialect of Python that uses Lisp syntax. Like every good developer, I wrote out my list of policies that I want the tool to obey: "If the user doesn't specify a genre on the command line, use the most popular gen... |
I'm more concerned about the coding best practices and how it's written here than the actual algorithm and math. I'm concerned about stack constraints, passing arguments,..etc. If there is anything critically wrong in the way the code is written - I would really appreciate comments!
#include <iostream>
#include <vector... |
I am attempting to complete an assignment, which is basically Connect 3, instead of the classic Connect 4 game. The AI I am using is the exact same as the opponent, but the opponent wins more because it goes first. I've researched for days and cannot grasp MINIMAX, or think of ways to make this AI better.
public int ... |
I am trying to generate a game board (similar to a Monopoly board). I am new to Scala and am thinking that there may be a better way to do this. But improvements to the code are also welcome.
class BoardGenerator(squaresPerPlayer: Int, numberOfPlayers: Int) {
val directionTuples = Array((1, 0), (0, 1), (-1, 0), (0, -... |
I would like to speed up this function as much as possible in Matlab.
This is part of a bigger simulation project, and as it is one of the most called functions within the simulation, this is crucial.
For now, I tried generating a MEX file, but the speed was not better.
Vectorizing seems difficult (but would be benefic... |
Problem: to eliminate initial zeroes from numbers besides those followed by '.' or alone. For example if we input a-000123+bc+0000.0008-0000+0001.07 , we will get a-123+bc+0.0008-0+1.07).
Using putchar and getchar only. No strings and pointers involved. I have working code, but I think it's confusing and overloaded. ... |
This is my simple code for a Battleships game:
from time import sleep
from random import randint
from math import sqrt
global yes, no, board, length, height, area, gamesPlayed, \
wins, shipRow, shipCol, guessRow, guessCol, look
yes = ["yes", "y", "yeah", "yh", "sure", "again",
"uh-huh", "definitely", "why n... |
The following implementation is a bit different form the standard implementations I have read. Is it correct?
#include <malloc.h>
#include <stdio.h>
void heapify(int[],int,int);
void swap(int a[],int i,int j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void heap_sort(int a[],int l,int r){
for(int i=l;i<r;i+... |
For example, sequence "aasdf123456785fg87" will be transformed into "aasdf12345678fg", using getchar and putchar and then using strings.
With getchar and putchar:
char c = 0, c_ = 0;
char flag = 0;
while ((c = getchar()) != '.')
{
if (isdigit(c))
{
if (!isdigit(c_))
{
flag = 0;
... |
I have created a method that validates inputs based on a set of rules. If an error is found, it is put into an array which can later on be used to display the errors to the user.
Below is my code:
register.php
<?php
require_once('core/init.php');
if(input::inputExists()){
$validate = new validate();
... |
kexec is a way for a Linux kernel to directly boot another Linux kernel without going through the usual BIOS startup sequence, which can take several minutes on enterprise servers. The big problem with kexec is that Linux distributions don't set it up for you when you install a kernel, and setting it up yourself is man... |
I have written my first shell script that uses inotify-tools to monitor my Downloads directory. What I intend to do with the script is that, as soon as a file is downloaded, it moves that file to a folder named after its extension. For example: if it is test.pdf it will be moved to a folder named pdf.
The script is her... |
This code has several functions and procedures for the program to generate cards like '5 of diamond'. I would like to shorten the code.
def random(one,two):
import random
number = random.randint(one,two)
return number
def suit():
suitnumber = random(1,4)
if suitnumber == 1:
suitb = 'Spade'
... |
I have faced a scenario: the task was to read a file which contains 3 Millions IP Address.
There is a MySQL table which contains Id,PrimaryIP, PrimaryIP can by multiple IP separated by #, moreover that PrimaryIP can also contain CIDR IP.
In totally, there are 8000 records, each record with multiple IP and CIDR IP.
... |
Let's say that I want to query some API which will respond with array of random numbers:
[4, ..., 17, ..., 25]
To keep things simple enough, let's say that array has always 10 elements. For every element in that array, I need to emit via socket to all clients just ONE number every M seconds till end of array. When th... |
http://en.wikipedia.org/wiki/Monotone_cubic_interpolation
We have implemented it using the formula from Wikipedia :
public class MonotoneCubicSplineInterpolation
{
public static double[] Calc(double[] xs, double[] ys, double[] x_interp)
{
var length = xs.Length;
// Deal with... |
I have written a toolkit (hwrt) which has a plugin system. One type of plugin is a feature (see this) for many of them.
There are some restrictions of feature classes. I expect some structure amongst them:
# Every feature class must have a __str__, __repr__ function so that error
# messages can help you to find and fix... |
The task was to check for pairs of anagrams in a string list.
I first sorted all the words. and looped over the letters.
The interview continues with a follow-up, to do the same with limited memory.
I tried to implement a Hash function.
The dictionary return value is only for my convince in order to see all the pairs... |
This simply creates a table using the items passed in. I would like to make this function shorter and/or more efficient. What I have seems pretty redundant.
def apriori_creator(items, k):
"""Function that creates apriori table using supported candidates"""
table = []
the_length = len(items)
new_k = k-2... |
I'm trying to find an alternative way to write this code such as using different ways to achieve checking if it's a subset and insertion.
def candidates(table, candidates, minsupp):
count, supported = {}, {}
for item in table:
for c in candidates:
if c.issubset(item):
c... |
This is the original question.
I have implemented it in both ways. If I enter the word "icecream", should I output "ice" "cream" and also "icecream", or just "ice" and "cream"?
Is this a good example of dynamic programming?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Syst... |
The interview question was to traverse a tree into a list.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class TreeToList
{
public TreeToList()
{
// 0
... |
I wanted an uncomplicated project to get myself started again. Although this works I was wondering if it's the best approach, especially when it comes to validation parts? It seems to me that I'm potentially looping quite a while, and this may not be the best or even common practice. I was hoping the CR community could... |
I'm learning to program and I've chosen Python as my first language. I've written a function to count vowels in a string and print the number of occurrences of each of them. Please review my code and let me know if there is a better way of writing the same as I believe there is always room for improvement.
vowels = 'ae... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.