instruction stringlengths 71 71.9k |
|---|
As part of learning Rails framework, I have small app in progress. Basically idea is, user can create IP address, define is it in use, to which server is assigned, which user is it using and role of IP address in web hosting environment. I have 3 models, IpAddress, IpAddressRole and IpAddressUser. User is able to defin... |
I'm working on a plain Ruby class within a Rails application.
For the total_leg_count method---is that the best way to go about achieving what I want? I feel like there's potentially a better way.
class AircraftTimeReport
...
def total_leg_count
count = 0
active_flights_within_timeframe.includes(:legs).ea... |
I wanted an easy way to augment objects, by adding functionality from any other object(s). More importantly, I needed a way to augment the object from multiple sources in a clean one-line solution.
The inheritance is done with this:
function extend(proto, args){
this[proto.id] = Object.create(proto);
proto.con... |
Since rsync lacks compression and I'm not a big fan of rdiff, I thought I'd try my own little backup script. Since I'm very inexperienced with file management in Python, I'm sure there is lot of room for improvement.
The script creates the entire folder structure within the backup folder and then creates syncs recursiv... |
I started to learn Rust some time ago and I wonder if there is some way to write Rust code that is both concise and safe — in particular, avoiding unwrap(), casting functions and try!().
Let's see an example. I wrote a software to generate random bookmarks and save them to a file, both in Rust and Haskell to compare.
F... |
This sorts a linked list using mergegort. Can you please critique my code and provide your thoughts on where I should improve my code?
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedList<T extends Comparable<T>> implements Iterable<T> {
private Node<T> head;
public Lin... |
I was poking around on my Raspberry Pi that I hadn't turned on or used in a while, and I stumbled upon this Python script that I wrote ~1.5 years ago, and I was intrigued.
Essentially, it's a 2D Minecraft clone with no concept of survival. It does have a slightly, complex control scheme, so here's a list of buttons tha... |
I wrote connection logic for a wrapper around RethinkDB in node.js. While it works, I know it can be cleaned up, and done in a better manner. Essentially the logic is start at the first host in config.hosts, if _connect() fails, then try the next host in the array. This continues for three times, or until config.hosts ... |
I have written this Java code for a data structure which includes 3 stacks to supports four operations in \$O(1)\$: push(int x), pop(), min() and max().
Instead of pushing new max and min in every push, I tried to optimize code in this way to have less space.
import java.util.Stack;
public class MyDS {
Stack<Inte... |
Please share your comments and better ideas, to print java graph, which manipulates selected (@Mask) fields as XX, thus avoid logging confidential data, through this tool.
GitHub
public class MaskLogger {
private static final String SERIAL_VERSION_UID = "serialVersionUID";
private static final String ELEMENT_DA... |
I was trying to learn to develop plug-ins in Eclipse and after following the tutorial provided with Eclipse, tried to expand the code by writing a short Java class to track and display mouse movements on a text area. I got the code for that too from an Oracle Java document. Following is the java class from where I call... |
I'm in need to make a byte[] -> T extension method and need it to be fast (no need for it being pretty)
This function will be called 100's of 1000's of times in very short succession in an absolute performance critical environment.
We're currently optimizing on "ticks" level, every tick translates to a couple milliseco... |
Task description
You are given a list and an item, find the length of the longest consecutive subsequence of the list containing only the item.
Testcases
[1, 1, 2, 3] 1 -> 2
[1, 0, 0, 2, 3, 0, 4, 0, 0, 0, 6] 0 -> 3
This code is pretty readable in my opinion but I fear that the \$O(N^2)\$ time complexity is sub-optim... |
Coming off a comment on this question, I figure it cannot hurt to post my Inventory work here as well.
Basically, I have Item, which is a base item, and then Container, which is a specialized item that has sub-items in it. The Container object, however, can be filtered to only permit (or restrict) certain items by some... |
I am working on a project which crunches plain text files (.lst).
The name of the file names (fileName) are important because I'll extract node (e.g. abessijn) and component (e.g. WR-P-E-A) from them into a dataframe.
Examples:
abessijn.WR-P-E-A.lst
A-bom.WR-P-E-A.lst
acroniem.WR-P-E-C.lst
acroniem.WR-P-E-G.lst
adapter... |
For my application, I need to use two slightly different algorithms for persisting an entity:
def persistRandomAlias(self, alias):
self.em.persist(alias)
try:
self.em.flush()
except DBALException as e:
if e.previous.code != 23000:
raise e
self.reloadEM()
sel... |
Question:
Special Pythagorean triplet, Euler Problem 9
A Pythagorean triplet is a set of three natural numbers, \$a<b<c\$, for which, $$a^2+b^2=c^2$$ For example, \$3^2+4^2=9+16=25=5^2\$.
There exists exactly one Pythagorean triplet for which \$a+b+c=1000\$.
Find the product \$abc\$.
I got the code to work using al... |
In my program, I prompt the user to enter a range of cities (in a spreadsheet), and then a range of review scores, and then make some decisions based on what the user has entered. Since the handling of the both user inputs (both ranges) is common to each, I have combined both into the single function getRanges() below.... |
This is not a novel interview problem. But I want to address it with the following points:
Implement the algorithm with Object-Oriented Design principles in mind.
Optimize the solution, if there are many continuous inputs.
Write simple unit tests (without using unit testing framework like gtest, boost.test)
Basically... |
My concerns:
Is the code pythonic
Is the code practical
I tend on expanding the usefulness of this script, if you don't think it's stupid idea. One thing I will implement is command-line arguments by way of argparse.
#!/usr/bin/env python
'''
Test if network is online by sending and http request to a remote
web-ser... |
Here is my basic password generator which saves your password to a .txt file which you can choose the name of etc.
import random
import string
import os.path
#random numbers section
num1 = random.randrange(100,999)
number_section = num1
#random letters section
string.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN... |
Here is what I'm starting with. It is just some <p> tags in a <div> tag.
<div id='mi_control' class='radius_all'>
<p id='mi_cover_l' class='menu_bottom small_dark'>Arcmarks © </p>
<p id='mi_about_l' class='menu_bottom small_dark'>About</p>
<p id='mi_privacy_l' class='menu_bottom small_dark'>Pr... |
I'm working on a tool to detect all exact tandem repeats in a DNA/RNA sequence. Part of the algorithm requires finding Longest Common Extension (LCE) values, which although can be computed in constant time, in practice it is (usually) better to use a naive \$O(n^2)\$ solution. The problem is that DNA sequences can cont... |
I have wrote an application which asks for the user id, and returns a link to the first available chat message:
Output
Enter user id:
322395
Fetching data...
http://chat.stackoverflow.com/transcript/17?m=231895#231895
Source code
module Main where
import Network.HTTP (simpleHTTP, getRequest, getResponseBody)
... |
I am building a config class for PHP which initially loads all given config files. To add files, users should be able to provide either a single file or a directory where files can be JSON or PHP.
Below is what I have so far, but it seems sluggish and inefficient to me. Is there a more elegant way to give users a wide... |
My program is complete and working, but I would like second opinions on it. The program prompts the user for a positive value that will serve as the maximum for the range that will be checked for perfect numbers. Although this is one of those do-what-you-want-with-it problems, I have to keep the two prototypes. Are the... |
I could not find a solution from my book's website (student-level access) but I feel that I am missing something that I'm supposed to learn from this exercise.
Instructions: Balls are dropped from the opening of the board. Every time a ball hits a nail, it has a 50% chance of falling to the left or to the right. The pi... |
This is stripped down from a project I'm working on:
let userFields = {
id: {
dbFields: 'id',
},
email: {
dbFields: 'email',
},
first_name: {
dbFields: 'first_name',
},
last_name: {
dbFields: 'last_name',
},
name: {
dbFields: ['first_name', 'la... |
I wrote a tokenizer/lexer (difference?) for Python in Haskell: this is my code on GitHub.
I already tested it out with some of CPython's standard library scripts, and it doesn't fail. However, it probably outputs non-conforming output. But I don't care about this right now.
What I'm looking for is a general (functional... |
This is a class that takes a PropertyInfo and makes a Control for it. You can access the value of the control through a property on the class called Value. Basically I get the data from the database for a specific type and create a form where I add the controls generated by instances of this class for each property of ... |
Following is my code for implementing basic symbol table in C. Please review my code and tell where I can improve my program.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdbool.h>
#define BUFFER_SIZE 1024
#define TOKEN_SIZE 32
typedef struct symbol
{
char* identifierNa... |
Basic algorithm:
Open document/huge text file
Use Map and List to separate the words. \$O(K)\$ time complexity (TC) considering \$K\$ distinct words.
If the word already exists in the list, increment the count of frequency, else add the new word. Constant TC.
Use a Collection to sort the list on the basis of frequency... |
I tried to make a social media slider with jQuery, HTML and CSS. This is available as a Fiddle.
Can I improve or debug any elements of it?
$(document).ready(function() {
$('.sa').hover(
function() {
$(this).css("margin-left") == "130px"
{
$('#sociallili').stop().animate({"margin-left": '+=130'})... |
I have this function that gets an item passed from another function, together with the subtotal and the fee of the item. The function has to act as fast as possible, as other people also want the item. However, the function seems to take a very long time, and almost never ends up buying the actual item because it was t... |
I've been learning C#, and today I made a simple Tic Tac Toe game. The code is pretty long, and I'm almost 100% positive that this can be done so much better. Please provide some advice, suggestions, and criticism.
byte _clicks = 1;
bool but1clicked, but2clicked, but3clicked, but4clicked, but5clicked, but6click... |
Number letter counts, Problem 17:
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or ... |
I am attempting to solve the Minimum Path Sum algorithm problem and I have a working solution, however there was an unwritten requirement that the algorithm not exceed an unspecified amount of time for any given matrix of size (m x n).
Given a m x n grid filled with non-negative numbers, find a path from top left to b... |
Recently, I started wrapping Meshes and Transform classes into new ones, but by doing this I came upon a problem: I needed to render all primitives, or meshes with a renderer. After studying a some game engines (especially the JME3 engine), I came up with this node-based rendering. It's really not complete yet, but fun... |
I have generated code which reads a file containing ways, take the individual waypoints and writes them into a new file, but only if the waypoint is not already present. At this moment my program stores the waypoint in a vector. Before the new found waypoint is written to the file the program checks if the waypoint is ... |
I used Spring MVC arch, and I need to be informed about correct names of methods and exceptions throwing.
/**
* @author Eugene G. Ustimenko
* @date Jan 19, 2015
*/
@Service
@Qualifier ("entityService")
public class BaseEntityService < T extends BaseEntity > implements IBaseEntityService < T > {
@Autowired
p... |
For this community challenge I made the racetrack game. I'm reading the race data from a text file, which is available here. This is only playable by entering the velocity at the console.
I've got two modules. I'm open for any comments.
Racetrack.hs
import Data.Serialize
import qualified Data.ByteString.Char8 as BStr
i... |
I decided to implement properly the Code Golf challenge about twisting strings. I report the assignement verbatim for convenience:
Twisting Words!
Given a string and a positive integer. You must twist the string, back
and forth.
Example Input / Output
Input
Programming Puzzles & Code Golf
4
Output
Prog
mmar
ing
z... |
I created my first shell script. It's an audio logger that runs on the hour for an hour and restarts. Although if it is started within the hour it will only run until the end of the hour.
I've added it to Startup Applications with the command:
gnome-terminal -e /home/admin/Desktop/audiolog.sh
However when it starts up... |
guys.
The code below is spring security web adapter. I do not like configure(HttpSecurity) method that generates security confirmation policy.
Any ideas to do it more readable and clear?
/**
* Spring security configuration
*
* @author Eugene Ustimenko
* @date Nov 5, 2014
*/
@Configuration
@EnableWebSecurity
public clas... |
This code is about manipulating each value in a 2D array. My method below is called based on how I want the values in the array to be manipulated (process).
For the first method in the switch statement - as an example, I am calling AllCaps() method to manipulate the value.
What I am trying to avoid is repeating stateme... |
What I've hastily named the Scissors API brings the cut-copy-paste paradigm made popular by word processors to the realm of list processing. The Scissors API is fluent, provides methods to manipulate a list, and maintains context through the use of a customizable clipboard.
An example: Fixing Yoda’s grammar
A good star... |
I gave a shot at implementing Maybe for C++ and a slight twist in my implementation is that it uses thread_local static instance of Just and Nothing + placement new operator to minimize the number of (de)allocations.
This is the first time I'm using thread_local and placement new operator, so I could be doing something... |
I have a class Address, a class AddressTest and I am trying to write unit tests for its constructors and getter setters.
Address:
/**
* The bean Address.
*
* @author Sandeep Chatterjee
* @since 24/8/2015
*/
class Address {
private BigInteger addressId;
private String name;
private String address;
... |
What would be the best way to refactor following methods?
private string CalcualtePercentageDifference(string temp1, string temp2)
{
double number1 = ParseDouble(temp1);
double number2 = ParseDouble(temp2);
double percentageDifference = 0;
if (number1 == 0 || number2 == 0)
... |
Following a lot of research and mainly based on this tutorial I came up with the following structure in my application:
ObjectBase - all view models inherit it:
public abstract class ObjectBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged = ... |
First off, this is version 2 of a previous question about the same macro: Previous Version. Thank you to Raystafarian, RubberDuck and everyone in chat who helped me make it better.
The Macro accesses a workbook containing 8 worksheets each with similarly structured but not identical tables of data (submitted business f... |
How can I improve this window timeout alert code? I need to add it to some third-party master page and don't want to add a separate file for it.
It must be JS only and IE-8 supported.
jsFiddle
(function () {
// timedRefresh(10); //3600000
delayedAlert();
var timeoutID;
function delayedAlert() {
... |
I've made a simple HTML→Markdown converter in Javascript and am looking for any feedback. For now, I've basically used Stack Exchange's /editing-help as a guide as to what to convert, but I might look at CommonMark's spec later on.
It uses DOMParser() and then goes through the child nodes to convert things.
My test HTM... |
Write a method rarest that accepts a map whose keys are strings and
whose values are integers as a parameter and returns the integer value
that occurs the fewest times in the map. If there is a tie, return the
smaller integer value. If the map is empty, throw an exception.
For example, suppose the map contains mapping... |
I think this code looks ugly, especially with the multiple try-catch blocks, but I don't know how to rewrite it:
public String handleFileUpload(@RequestParam String url,@RequestParam String fileName, RedirectAttributes redirectAttributes, HttpServletResponse response) {
InputStream inputStream;
try {
... |
I run a tiny open source project to help create speech aids for disabled people (the GitHub is here).
One of the things that is useful is for people to design speech setups in Powerpoint, and then have the PowerPoint file processed to extract the images and the other information. The script below processes the PowerP... |
Currently I have an application that is relying on Bootstrap's Grid layout. I originally chose it because it was easy to learn and looked good. However, it didn't handle nesting as well as I thought it would. After investigating and finding out that it used float for all the grid classes, I don't like it as much.
... |
I am solving problem GRAVITY on SPOJ. Each test case is a rectangular ASCII grid of dimensions m × n, and you have to determine whether it is possible to find a path from the 'S' square to the 'T' square, moving using the space squares and avoiding '#' obstacles, in at most O steps (diagonal steps allowed).
I am using ... |
I actually had a real life need (outside work, no less) to come up with every single permutation of N elements (the N in my case being 12, so a total of 12! = 479,001,600) and run each one against a simple evaluation to produce some metric in order to determine which permutation is the most optimal.
Since I have some b... |
This code puts or changes ID3 tags to media files based on their file names. It assumes the files are in this format:
morbid angel - maze of torment.mp3
The resulting tag would be:
Artist: morbid angel
Title: maze of torment
I use boost::filesystem to iterate through the directory and taglib to manipulate the ta... |
I while ago I experimented with macros in C and came up with the idea of implementing a generic vector library using macros.
This code uses the non standard typeof extension that returns the type of an expression.
#ifndef VECTOR_H
#define VECTOR_H
#include <stdlib.h>
#include <string.h>
#define VECTOR_OF(T) struct { ... |
I've written a 'Mini Twitter' (that's what I've called it) in Python. It includes a text-based login screen and user panel where you can create Tweets, and change your username and password.
Users' names, passwords and whether or not it is an administrator is logged in a text file. It also logs Tweets Users have made i... |
I am looking for the best way of parsing JSON in Swift 2.0.
I have this JSON
{
"latitude": 37.8267,
"longitude": -122.423,
"currently": {
"time": 1440110395,
"summary": "Clear"
}
}
and field summary is NOT always visible in response.
My model object and parsing method:
enum JSONErrorType: ErrorType {... |
This is a calculator I've made in C#. Is there any way to improve it? Surely there is a way to get rid of all the ifs that are nested inside one another.
namespace CalculatorCA
{
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<i... |
I have been told that it would be wise to split up my code into semantically useful blocks. I tried the following but I need feedback.
What I already did:
As you can see I create two .csv files, so it seemed logical to have two functions. One for the main dataset, the other for a frequency table
I only import modules ... |
As a follow-up to this question concerning Python I present you with the exact same thing - for R.
Initially I started with R. However, it takes 44 minutes to run when unleashed on all my data. I then looked for an alternative. I read about Python and got advised to use pandas by a colleague. So I set out on an advent... |
I want to know about best practice for this SplashScreen class:
public class SplashScreen extends Activity {
// time out to splash screen
private static int SPLASH_TIME_OUT = 2000;
private Runnable mjumpRunnable;
private Handler mHandler;
//image view to validae logo
ImageView validatelogo;
... |
This is an interview problem:
Given a token stream, find the K most frequent tokens in real time (the order of these k tokens does not matter).
My approach:
Use a hash table (unordered_map in c++) to maintain the frequency of tokens.
Use a min heap to maintain the k most frequent tokens.
Update the hash table and th... |
I have implemented a solution to Project Euler problem #60. In summary, the problem asks to find the smallest sum of a set of five prime numbers such that the decimal strings of any two numbers in the set concatenated together form the decimal string of a prime.
I'd like some comments on the structure and style of my p... |
I'm new to Haskell and am confused by why my code seems to preform so poorly, and wonder if there's something I've not grasped about the coding philosophy behind the language, or the best way to take advantage of its features.
For example, I have started, as an exercise (yet another) simple Enigma machine simulator (fo... |
I haven't written any Java in years and I wanted to catch up a little, especially on newer features. I started looking at streams and aggregate operations and came up with the following solution to Project Euler #7 (find the 10001st prime).
package com.example;
import java.util.stream.IntStream;
import org.apache.commo... |
After populating the stock_tmp table, i'm running these SQL queries via legacy mysqli wrapper code. I don't think this code needs additional locks to prevent people from seeing incorrect data. Is that correct?
DELETE FROM stock WHERE ean NOT IN (SELECT ean FROM stock_tmp);
REPLACE INTO stock SELECT * FROM stock_tmp;
|
I have code that converts each character of a String to an int and returns the difference between odd and even numbers. Can this code be simplified?
int compareSumOfDigits(String N) {
int e=0,o=0;
for (int i =0;i<N.length();i++){
int t = Character.getNumericValue(N.charAt(i));
if(t%2==0)
e+=t;
else
o+=t... |
I have a class Fighter in a software for planning boxing events. I implemented its hashCode() and equals() since I collect them in various data structures in many places.
Now I want to persist specific planned boxing events which themselves contain the same Fighters in different lists. I am using JAXB for this purpo... |
I created a basic jQuery plugin to make a basic sliding tile puzzle.
/*
* tilePuzzle.src.js
*
* A simple tile puzzle jQuery plugin by @matthewfedak
*
*/
/*jslint browser: true*/
/*global $, jQuery, alert*/
(function ($) {
"use strict";
$.fn.tilePuzzle = function (options) {
var self = $(this);
var t... |
Here is my script that registers a user to a database. I am still very much a newbie when it comes to this topic so any guidance would be greatly appreciated.
<html>
<head>
<title>Register</title>
</head>
<body>
<?php
require ("opendboLogin.php");
main();
function main()
{
if(!isset($_POST['submit'])) //if user t... |
I'm working with some Clojurescript code that reacts to user input over three sliders. These sliders get stored in a map, and I need to make sure that the sum of all is <= a max value. Every time a value from the map is modified I have the guarantee that it will be in the [0, max] range, and I must reduce if necessary ... |
I'm designing a Factory in C++ with raw pointers, but I'd like to use smart pointers when possible as is recommended with the Factory pattern in newer C++. Unfortunately my compiler is a bit old (gcc 4.4.6) and not all of the features of C++11 (let alone C++0x) are available to me.
I cannot use nullptr, which is the mo... |
This code inserts the number 4 into a vector's even indexes.
vector<double> vecCoeffs;
// Put the coefficient 4 into each even index and 2 for each odd index
for(int i = 0; i <= 10; i++){
vecCoeffs[i];
if(i % 2 == 0 ){
vecCoeffs.push_back(4);
}else{
vecCoeffs.push... |
int Octet(double m, int Ax, int Ay, int Bx, int By)
{
int octetNo = -1;
double dx = Bx - Ax;
double dy = By - Ay;
//m = dy / dx;
if(0<=m && m<=1)
{
if(Ax<Bx) octetNo = 1;
else if(Bx<Ax) octetNo = 5;
}
else if(0>=m && m>=-1)
{
if(Bx<Ax)
octetNo =... |
I need to send and receive data. Here is solution for my original problem. I want to know how safe my finished code is and how I can improve it. Here is my first try. Now I need to get review for my new code.
void sslWrite(SSL *ssl, const void *buf, unsigned size)
{
int writedTotal = 0;
const char *ccBuf = re... |
I've made an "simple" / "small" MVC-like PHP system. I've used some code of an project I used before and ask questions about it back then to.
The thing is, it works (the admin part to begin with), but I'm not sure about the quality of the code. I know that there are mainly no comments, but they will be added when I'm s... |
I built a couple Vector2 structures (Vector2 and Vector2F) for use with a particular project, so I'm mostly requesting best practices here.
The biggest concern is that I'm not making any assumptions I shouldn't be. I would like any comments that are relevant on the interface and whether it's too light, or if it's just ... |
This Macro takes my company's 2 main sources of all-client data (each a data table in a separate worksheet) and aggregates them into a 3rd list, by matching a unique account number (for clients that have an account number).
As always, I'm welcome to all feedback on any aspect of the Code and in particular, I'm interest... |
I'm trying to find my bug or any potential bottleneck that cause my program to be really slow. The script is to get all the followers and friends and save that in MongoDB.
import pymongo
import tweepy
consumer_key = ''
consumer_secret = ''
access_token = ''
access_token_secret = ''
from pymongo import MongoClient
cli... |
If anyone has the patience to take a look at my first python snake game, I'd be very grateful for any feedback. I am fairly new to programming and Python, but am looking to improve so any constructive feedback is appreciated.
import Tkinter
import time
import random
UP = u'\uf700'
DOWN = u'\uf701'
LEFT = u"\uf702"
RIG... |
I tried to find a generic way to deal with associations. I ended up with this code which seems to fit my needs:
#include <iostream>
#include <tuple>
#include <set>
#include <string>
template <typename D, typename... Ts>
class Relations;
namespace std
{
template <std::size_t I, typename D, typename... Ts>
auto... |
I have two javascript functions that generate a D3 Stream graph. I feel I may be excessively and unnecessarily iterating over my dataset to get it into the desired form.
How might I optimize or simplify this?
d3.json("/sleeps", function(d) {
sleepStream(d);
});
function sleepStream(d) ... |
The idea here is to pick a skill at random for the player each round. Four skills will be chosen, they are all random, and the same skill can repeat multiple times.
The player has a skill level for each ability. The higher the skill level, the greater the chance that the skill will be chosen.
Rather than use floats a... |
Here is the original question. I've incorporated a lot of the feedback and I'm ready for another round of feedback and suggestions.
Here is the PHP file's output. It creates a volunteer signup report (in HTML, viewable in your browser, based on data in an SQL database) for volunteer managers to review. I plan to use th... |
I wrote Ruby code (copied below) but was told that the code does not compile (it does on my computer) and that it does not answer the question:
Create a class called Scrabble that implements a method called score that accepts one word as a parameter and returns the scrabble score associated with that word
The code co... |
I have an ordering system that uses SharePoint. Below I've included a small snapshot of the system that is used in a WPF form when the user clicks a button to refresh the order listing. The outcome is a populated WPF datagrid. Note that this code is using C# 6.0 as well.
Everything works well, and it's quite quick, but... |
I have the following code to share my website through some social networks when the user clicks some divs with the appropriate icons.
var loc = encodeURIComponent(document.location.href);
$(document).ready(function() {
$("#shareFacebook").click(function() {
window.open('https://www.facebook.com/sharer/sharer.ph... |
I'm tying to convert from this formatted string:
$filtersStr = "id:1||name:alex";
to:
['id' => 1,'name' => 'alex']
My solution for now:
foreach(explode('||', $filtersStr) as $filter){
list($k, $v) = explode(':', $filter);
$filters[ $k ] = $v;
}
I'm looking for a more elegant way.
|
In my Angular app, users click on different icons. When a user clicks on respective icon, I can show the icons gallery, as well shuffle the view.
Apart from this shuffling functionality, I need to hide whatever other gallery is already open.
For that, I've written the following function, but, I think it could use some ... |
This is a follow-up question: Game server packet handler
I have applied most of the suggestions and now the code looks like this:
import java.io.IOException;
import server.engine.*;
public class ServerPacketHandler extends PacketHandler {
@Override
public void handlePacket(final Packet p) throws ArrayIndexOut... |
I have been trying to solve the following problem on hackerrank.com, but when I submit the code it shows unsuccessful submission due to timeout. Can anyone help me out?
Sherlock and the Beast
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class test {
pu... |
Here's a merge sort I wrote trying to learn Scheme.
(define mergesort
(lambda (l cmp)
(define merge
(lambda (left right)
(cond
((null? left) right)
((null? right) left)
((cmp (car left) (car right)) (cons (car left) (merge (cdr left) right)))
(else (merge righ... |
I have just made a game called Hangman. I have added some stuff which people don't normally use, like cheat-code/s, time.sleep().
How can I improve this, in both readability and methodology?
import random
import time
hangman = (
"""
_________
|/
|
|
| ... |
In this program there is a single remote server which performs miscellaneous work. Because there is only one server, it seems like a singleton pattern could fit well.
The problem that a distributed program introduces is that every client will have its own version of a static variable. Therefore I have defined a basic ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.