instruction stringlengths 71 95.1k |
|---|
The "vectorizing" of fancy indexing by Python's NumPy library sometimes gives unexpected results.
For example:
import numpy
a = numpy.zeros((1000,4), dtype='uint32')
b = numpy.zeros((1000,4), dtype='uint32')
i = numpy.random.random_integers(0,999,1000)
j = numpy.random.random_integers(0,3,1000)
a[i,j] += 1
for k in xr... |
I have been setting multiple variables like this
function doSomething() {
var FirstName = $FirstName.data("ov");
var LastName = $LastName.data("ov");
var Company = $Company.data("ov");
var Website = $Website.data("ov");
}
I just read some reviewed code and both reviewers advised setting the variable... |
I have many pages with functions that appear only once, which I am sure is really typical. I read that it's the best idea to use the local scope for functions when possible because the local scope is searched first, thereby making the function found sooner.
If I have no intention of reusing a function, is this the bes... |
Inspired by Don Stewart's article on Scripting with Haskell I tried a rewrite of a shell-script I did the other day. I was really astonished how easily it worked but as a whole it is about double the size of my shell script and some things feel a bit "clumsy".
myReadTile and getCurlIP have IO-return type, which seems ... |
#!/bin/bash
# Change the environment in which you are currently working.
# Actually, it calls the relevant 'lettus.sh' script
if [ "${BASH_SOURCE[0]}" == "$0" ]; then
echo "Try running this as \". chenv $1\""
exit 0
fi
usage(){
echo "Usage: . ${PROG} -- Shows a list of user-selectable environments.... |
The goal with this function is to find one DNA sequence within another sequence, with a specified amount of mismatch tolerance. For example:
dnasearch('acc','ccc',0) shouldn't find a match, while
dnasearch('acc','ccc',1) should find one.
EDIT: Function should also be able to find pat sequence in a sequence larger th... |
This is my code for sending mail in HTML format:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
impor... |
I have scoring system where I want to change icon color by changing CSS classes.
How can I optimize this jQuery? After testing, I found this the only alternative, but I trust there is a more simplified method.
// Count scores
$('#bodyScore').text((90 / myarray.length) * bodyScore + '/90');
// Change icon color
var bo... |
I feel like I should not be duplicating the code to gather the credit card number, but I am not sure how best to do it. Any suggestions?
$('input[name="payment\[cc_number\]"]').keyup(function() {
var ccNum = $(this).val();
ccNum = ccNum.replace(/[^\d]/g, '');
setSelectValue(ccNum);
});
$('input[name="payme... |
I have written this basic Heroes of Might and Magic 3 Battle Simulator. I am decent at procedural, C-style code and I am trying to get better at Object Oriented Programming. (I know procedural code be better suited for this problem, but I am comfortable with this material.)
Any and All critiques are appreciated (Spe... |
We are building a interactive tile-based (32x32 px) (game) map where the user can move around. However we experience lag (some sort of a delay on the movement) and we need to work around this problem. The "hack/lag" also happen on a local server so it's not because of the traffic yet.
Any suggestions how we can make th... |
I'm trying to parse addresses out of blocks of text, and have the following expression to do so:
/\d+\s(?:[sewnSEWN]\.?\s)?[\d\w]+\s(?:(?:[\d\w]+\s){0,3})?\w+\.?/
It will currently parse addresses such as:
300 E. Randolph St. Chicago, IL >> Returns 300 E. Randolph St.
5553 Bay Shore Drive >> Returns input
23 Joseph E ... |
i am new on java and i have not more knowledge about java. please help me for optimizing it as much as possible
public void q1(String str, int[] arr) {
String local = "findnumber";
for(int i=0; i<arr.length; i++) {
if(str.equals(local) && arr[i] * 2 > 10) {
Integer in = new Integer(arr[i]);
... |
Note, I choose not to use the Factory Pattern out of preference.
This is a ( M ) odel class in the MVC pattern.
Private functions return Booleans and public functions return strings which I then output to the browser from the Controller. The class returns a string from the invoke call.
Here is the only call to the cl... |
I usually program in python/javascript and am very new to php. I would appreciate some advice on how to improve the following form script.
Since this is for a highly trafficked website, I want it to be extremely secure, reliable and optimized.
Feel free to point out minor issues as well.
<?php
// avoid errors when in ... |
import System.Environment (getArgs)
import Random
main = do
args <- getArgs
let len = length args
let n = if len < 1 then 10000 else read (args !! 0) :: Int
let fileName = if len < 2 then show n ++ "-output.txt" else args !! 1
str <- rndStr n
writeFile fileName (str)
-- writeFile fileName (rndStr n)
-- ... |
I have this if else statement where I don't know how to remove the code duplication
if(array_key_exists($key,$cachetable))
{
if($cachetable[$key] != $newdata[$key])
{
//data existed but is not valid
//update the cachetable
$cachetable[$key] == $newdata[$key]
}
}
else
{
//data didn't existed before... |
This is a recursive descent parser for simple language with following grammar:
PROGRAM <- {STATEMENT ';'}* RETURN_STMT ';'
STATEMENT <- NAME_BINDING | TYPE_DECLARATION
TYPE_DECLARATION <- named_param identifier
NAME_BINDING <- identifier '=' EXPRESSION
EXPRESSION <- (simple arithmetics with (), +-*/ and unary minus, ar... |
I want to write better code.
This is a simple controller class for an administrator login.
Are there conventions or tips in PHP to rewrite this code and improve it?
<?php
class Administrators extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() ... |
First off, I'm just learning Haskell and I'm not proficient in that language yet.
I wrote this Haskell module to look for files in a Linux filesystem. It can use regular expressions as search patterns. I wrote two variants: one of them sends the search results to stdout, the other (shown here) gives a list with the sea... |
SELECT p.name,m.name
FROM parts p
INNER JOIN Manufacturers m ON p.man_id=m.id
ORDER BY p.name DESC
If not, what should be done for its optimization?
Here is the two tables:
CREATE TABLE `Manufacturers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB
... |
Is there a way to speed up the following python code:
auxdict = {0:0}
divdict = {}
def divisors(n):
divisors = []
for i in range(1, int(n**0.5) + 1):
if (n % i == 0):
divisors.extend([i, n/i])
divisors = list(set(divisors))
divisors.sort()
return divisors
def aux(k):
if k i... |
I am writing my first Android application and have mainly been using code examples online. However, I have been going hard at it for a while now and realize that I have some overlapping methods and such in my code.
I have three classes:
AndroidBluetooth (main activity)
BluetoothModel (the class that holds all of the B... |
I denotes independent, no dependencies.
<?php
/**
*Input - One Dimensional Non-Empty Post Array
*Ouput - Boolean on pass or fail
*/
class IText
{
private $text_array = array();
private $patterns = array(
'domain' => '/:\/\/(www\.)?(.[^\/:]+)/',
'prefix_url' => '/^(http:)|(... |
I had a task for a programmer position which I failed. I am a newbie programmer and I accept that. The only problem is that employer never told me what the actual problem with the code is. So maybe community will be able to give few hints on how to improve it.
The task was to write code which would parse a given webpag... |
I have some code here that changes the font size depending on what link you clicked and it works perfectly, I now want to add another feature but need some help. I want to add current font size which changes as you press bigger or smaller.
jQuery:
$(document).ready(function() {
function change_size(element, size) ... |
So I am using the following
<?php
function LuhnCalc($number) {
$chars = array_reverse(str_split($number, 1));
$odd = array_intersect_key($chars, array_fill_keys(range(1, count($chars), 2), null));
$even = array_intersect_key($chars, array_fill_keys(range(0, count($chars), 2), null));
$even = array_map(function(... |
I want to realize caching in WCF web service. I'm using the following code:
public interface ICache<T> : IDisposable where T : class
{
string Name { get; }
CacheItemPolicy CacheItemPolicy { get; set; }
long Count { get; }
bool IsDisposed { get; }
void AddOrUpdate(string key, ... |
I wanted to make a class that connects to my server and returns a value, a URL in this case. As Android 4.0 doesn't let me run network task on the main UI thread (rightly so) I have made this.
Please give me your feedback as to if it is thread safe or not and ways to improve it. I have never used ExecutorService or Fut... |
I have a list view which display in each view a Album's name, the associated Artist and the album art.
Here is the code of my ListFragment which display this list:
public class AlbumsFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
AlbumsAdapter mAdapter;
@Override
... |
I have Polygons on Google Maps API V3, and I would like to write this shorter:
var myCoordinates = [
new google.maps.LatLng(52.210722,21.007330),
new google.maps.LatLng(52.211695,21.007030),
new google.maps.LatLng(52.212707,21.006718),
new google.maps.LatLng(52.214166,21.006246),
... |
I am currently writing my first Android application, and am having trouble grasping how to structure it. From my previous programming experience I was planning on using a MVC design but now I don't know if I can implement that.
My program consists of several different activities which all need access to a single Bluet... |
I have learned a little Python for a few projects at work. This is my first finished application and I was hoping someone would take a look at it. I would love some tips on the mistakes I've made.
################################################################################
#Monthly Rollover System ... |
I have two .on() functions for separate dynamically added elements, they are:
$('body').on('click', 'img', function() {
modal(content[$('li.active a').attr("href")].images[$("img").index(this)]);
});
$('body').on('click', 'img', function() {
closeM();
});
The second function, I have shortened to
$("body").on("cl... |
I've created a simple daily task scheduler but I'd like to change this to a general task scheduler accepting more advanced schedules.
I'd like to have some critiques from other sets of eyes on my current implementation before I continue.
public class ScheduleJob
{
#region PRIVATE VARIABLES
private readonly Time... |
Can this time converter be written more efficiently? I'm new to Java, and I would like to know.
main
import javax.swing.JFrame;
public class main {
public static void main(String[] args) {
window wn = new window();
wn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wn.setSize(275, 170);
... |
I have been using a slightly modified Hamming Distance algorithm for approximate String Matching for patterns and wondering if there is something better out there. The t being the length of the text and p being the length of the pattern the worst case is roughly O(t*p). Which from looking at other Fuzzy String matching... |
I created my first Ruby program. Even though it works, I wondered whether I could do something different/better?
#!/usr/bin/ruby
class LuhnyBinChecker
def initialize(number)
@number = number
end
def check
createNumberArray
doubleSecond
sumNumbers
getResult
end
def createNumberArray
... |
My web application is simply supposed to take a search query, run a script on it that returns product information and then post it in an "endless" fashion on a web page, making one page with no pagination that is "infinitely" scrollable.
The web scraper I use, called Fletcher, which helps return usable results is slow ... |
I have been writing a small extension to the reCaptcha library.
class Captcha
{
private $config;
public $error;
public function __construct(array $config)
{
include './library/recaptchalib.php';
$this->config = $config;
}
public function render($error = null, $use_ssl = false)... |
I am wondering if anyone has any ideas for improving the following. Personally I am 'happy' with it, apart from the first for loop. I was thinking of another way of writing this, but perhaps it is ok.
def findnodepaths(nodepaths, graph, *nodes):
# nodepaths == list()
# graph == defaultdict(set)
# *nodes == 'foo','ba... |
I would appreciate some quick comments on this basic mergesort code.
Am I missing a big block in the langage?
First solution
open System
open System.Windows
open System.Collections.Generic
let shuffle (l:'a array) =
let ileft = LinkedList<int>(seq { 0 .. (l.Length - 1)})
let rec pick (ar:'a array) r =
m... |
I've just completed a JavaScript module and I've got a strong feeling that this is borderline spaghetti code. My task was to build a tagging form which adds selected tags to hidden outputs to be sent to a server.
var tags = [];
var createdTags;
var addedTags = [];
var isNewTag, selectedTag, i;
$("#created-tags").attr(... |
I have a dynamic form that users can add extra fields too. The group of fields are added and the input name stays the same but gets a incremental number attached to it. So for my insert php file I just check to see if the next value is set and if so it inserts all the required info. But this code doesn't look very 'str... |
This question is always on my mind. I usually alter the array while looping through its keys, based on my gut feelings:
foreach (array_keys($array) as $key) {
$array[$key] = perform_changes_on($array[$key]);
}
I'm aware of other methods, though. The array item can be passed by reference on the foreach call:
foreach ... |
This is the code I'm using at the moment
/*
* Adjust content height so that it always fills browser height
*
* written by Tom Jenkinson
*/
jQuery(document).ready(function() {
refreshContentSize(); //run initially
$(window).resize(function() { //run whenever window size changes
refreshContentSize(... |
I am playing around with brute force attack on my home network. I wrote the following script with Python. However progress is a little slow. Does anyone have a suggestion how to make this faster?
import socket
import urllib2, base64
import sys
import time
def afunction(password_start):
#-------------------------... |
I think it is quite OK already, but from a design-pattern perspective, it would be interesting to hear if I have done it right. I'm also interested to know whether the implementation is OK from a best-practice C++ point of view.
I made a helper class in order to easily position objects in cocos2d-x. The client can use... |
I'm preparing for an interview so I'm trying to solve some problems to stretch my mind. Here is one:
Describe how you could use a single array to implement three stacks.
And here is my implementation:
class StackUnderflowError extends RuntimeException {
public StackUnderflowError(String msg) {
super(msg);... |
(define (merge-sort lst (lt? <))
(define (truthy=? a b)
(eq? (not a) (not b)))
(let sort ((lst lst)
(size (length lst))
(flip #f))
(define (merge l r (res '()))
(cond ((null? l) (append-reverse r res))
((null? r) (append-reverse l res))
((truthy=? (lt... |
This class holds message types that are sent to the client which knows what to do with them. It is basically a small registry pattern where I can consolidate message types. |P| and |F| are read by the client...and I use these for simple data passing when I don't need the complexity of JSON. The programmer is expected... |
I have a file with an specific format. It's divided in stripes of 1058816 bytes:
4096 bytes with only a 64 bit unsigned integer.
An array of 512 64 bit unsigned integer.
An array of 512 32 bit unsigned integer.
An array of 512 elements with 2048 bytes each one.
I have to read the file, change some values and write it... |
I am trying to use jQuery to make calculations with a table containing football data. Can I improve what I have done here? Is my code well-structured and executed, or does it need improvements?
http://jsfiddle.net/userdude/kCanv/
HTML - Table
<table id="table-pts">
<thead>
<tr>
<th colspan="3"> </th>
... |
Please review the following code and list all the coding errors and poor coding practices that you can see in this code.
function output()
{
// Check authorization
if(is_authorized())
{
$authorized = true;
include('/path/to/' . $_REQUEST['module'] . '.php');
}
echo "<ul>"
$conn =... |
I'm learning F# and I've decided to solve Project Euler's Problem #81 with Dijkstra's algorithm.
In the 5 by 5 matrix below, the minimal path sum from the top left to
the bottom right, by only moving to the right and down, is indicated
in bold red and is equal to 2427.
131 673 234 103 18
201 96 342 965 150
63... |
This is a lock-free Container class. By Container I mean it will hold objects for iteration at a later time. To achieve \$O(1)\$ it returns a token from the put method which you can then use to remove the object. The token is actually the node in which the object has been placed.
It is instantiated with a fixed size an... |
I recently started learning jQuery and JavaScript and put this together for the site I work on here.
/*
* Manages the error report popups
*
* written by Tom Jenkinson
*/
jQuery(document).ready(function($) {
var bottomTableReport = {
timer: null,
init: function() {
this.mouseove... |
Yet another interview question:
Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.
First off, did I understand the question correctly? In other words, we are look... |
All models are in the model namespace and follow a naming convention. This makes it easy to consolidate control into cType() as shown below.
All control passes through cTYpe() which calls the correct model. It does this by way of the type parameter which is set by the call back function for the specified event.
Calls... |
This is an function that downloads a single file from an FTP server and saves it to disk
This is my first time doing anything with FTP, please let me know if i have missed anything.
public void DownloadFile(string fileloc, string saveLoc)
{
try
{
// Get the object used to communicate with the server.
... |
I have some code in Go that is attempting to compare two images and determine how different they are. The method is fairly crude, but it is fast enough. Basically it just compares both images pixel by pixel and for each pixel it determines how different they are by comparing the RGBA values separately and using the abs... |
I am new to Java, and I would like some tips from the 'pros'. I know of the Pascal naming system, and things like that, but how can I improve this code?
Menu.java
package com.x12.addsubtract;
import java.util.Random;
import java.util.Scanner;
public class Subtract {
Game game = new Game();
String[] question ... |
I have been trying to make this code go faster by trying to write it more efficiently and I don't know what else to do. I got it to 30 seconds but I have seen 23 and 24 and I have no idea on how to do it.
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMi... |
The client side version in JavaScript is here
This is the server side version of my control module. How does the structure look.
PostScript
Because this is a small prototype/app I have preferences or things I will consider when I will have a working prototype, they are - testing, try/catch/throw handling of errors, ... |
I'm in the alpha stages of development for my console RPG, and I need some input.
My main question is how should I handle attacks? (You'll see what I mean if you look through my world, item, and enemy classes code.)
Here are some code snippets and a link to my full code. Please note that my latest revision has some unf... |
I feel like I write this a lot in PHP:
$val = isset($var['foo']) ? $var['foo'] : '';
Is there a shorter way to write this? I can't use the ternary operator because the conditional is an isset check, not the value of the function itself.
|
I have a class that has 5 similar methods, they just relay input parameters and return a result - best practice would be to skip the class, but that's not what I'm asking about :) This is a method from the class:
public String deleteItem(Integer itemId,String username, String kpNumber) {
try {
retur... |
I have following code for a library management system.
Is the following code a proper implementation of the Repository Pattern?
How can I adapt this code to use generics?
Should I let MyOracleReservationRepository and MyOracleBookRepository be DataContracts if I am consuming this code as a WCF service (business Layer... |
I'm verifying South African IDs with jQuery, the code below works but Id like to know if it could be simplified in anyway or if there is a better way of doing things here?
South African IDs are verified as follows:
Using ID Number 8001015009087 as an example:
Add all the digits in the odd positions (excluding last dig... |
I'm trying to "sanitize" a textarea input by disallowing repeated characters like "!!!", "???", etc. add spaces after commas, and I would like to optimize the code because I'm not a pro at this.
jsFiddle
$("#post_input").keypress(function() {
var obj = this;
setTimeout(function() {
var text ... |
I post the following code writen all by hand. Why I have the feeling that it is a western spaghetti on its own. Second, could that be written better?
<div id="form-board" class="notice" style="height: 200px; min-height: 109px; width: auto;display: none;">
<script type="text/javascript">
jQuery(document)... |
The code below is slow. Any thoughts on speeding up?
dict1 = {}
dict2 = {}
list_needed = []
for val in dict1.itervalues():
for k,v in d1ct2.iteritems():
if val == k:
list_needed.append([val,v])
|
I'm a rank beginner in Python, and I am working my way through various relevant OpenCourseware modules. In response to the prompt
Write a procedure that takes a list of numbers, nums, and a limit,
limit, and returns a list which is the shortest prefix of nums the sum
of whose values is greater than limit. Use for.... |
My first attempt at a user registration code.
Login.php defines database log in variables (e.g. Database name, Table name, etc)
Header.php connects to the database.
I used ctype_alum for security of inputs. I also know that I shouldn't use mysql_error() for security issues but I've used the function as a placeholder.
W... |
Following is a working solution for a single xml ajax to retrieve category list, then individual ajax calls for each category. This was developed in response to a question on SO.
Solution creates one deffered for the category ajax call, and array of deffereds for the items ajax calls. Bottom of code nests $when(itemsCa... |
We were given two countries, namely Brazil and Argentina. Both had one inventory each with 100 iPods in them. The cost of an iPod in Brazil was 100/unit and in Argentina it was 50/unit. But to get iPods form Argentina, you also had to pay 400/10units. Now they give us some number and we had to find out which purchase w... |
How can this be improved?
def quick_sort(temp_list):
#Check if the array is having one element or not
if len(temp_list) == 1:
return temp_list
elif len(temp_list) >= 2:
l_list = list()
g_list = list()
#Choose a pivot
if len(temp_list) % 2 == 0:
pivot = temp_list[len(t... |
I have a class which throws a lot of exceptions:
try {
mapper.writeValue(outStream, myVal);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I think ... |
I'm currently getting the Facebook comments count over a query request to the Facbeook api.
The problem is, there are about 15 queries on each site which makes it real slow to load (up to 6 seconds)
The next step is to get the comments count from the array object, as there's no native PHP function for that i wrote my o... |
Question goes like this :
input: 1
output:
{}
input: 2
output:
{}{}
{{}}
input: 3
output:
{}{}{}
{{}}{}
{}{{}}
This is my program :
public class PrintBraces {
int n;
char []braces;
void readData()
{
java.util.Scanner scn=new java.util.Scanner(System.in);
System.out.print("Please en... |
I have a table containing URLs as they should appear in English and equivalent translations of them into other languages. Originally, I was told that there would always be an English translation, so when listing them in the application that updates them I just searched for the ones where iso = 'GB'. However, it turns... |
I have a servlet deployed in a Tomcat Servlet Container in this link, http://localhost:9764/example/servlets/servlet/HelloWorldExample. I want to send a HTTP request to that servlet using Java. Just I want to get the return as a String. Currently I am using this code to do it, Is it OK to use this code?
import java.io.... |
I am wondering if this is a good and correct way to write the implementation of two web service methods (get/set methods).
The setPerson method can be called from different threads from a pool, so I think the best way is to make the method synchronized. Or is it possible to lock the table when editing to avoid the sync... |
I use NPOI to copy Excel formula, but can't find an option to do it in a relative way. Therefore, I've written a function to implement it. The task is "easy". When copying a formula A1+B1 of C1 to C2, the result will be A2+B2. But the formula can do more than that. For example:
Left(A1, 3) of B1 to B2 => Left(A2, 3)
(... |
I have a custom SPList that has a field Assigned To, now I can add as many items as I want, and they can have same title and same User they are assigned to, but what I want is a script so that I only get the distinct number of user's email address, e.g. if a user is assigned to more then 1 item, I will get there email ... |
I've got a fairly performance sensitive need for fast prefix lookup, and I've built two different implementations trying to optimize for my use case. The first is built off a Trie implementation, and the second uses binary search. Testing them both, the Trie provides faster lookup, and much faster insertion, but dram... |
I am new to Python and want to have a "pythonic" coding style from the very beginning. Following is a piece of codes I wrote to generate all combinations and permutations of a set of symbols, e.g. abc or 123. I mainly seek for suggestions on code style but comments on other aspects of codes are also welcome.
import r... |
Problem
Starting in the top left corner of a 22 grid, there are 6 routes (without backtracking) to the bottom right corner.
How many routes are there through a 2020 grid?
Solution
Here is my solution
def step(i,j):
if(i==20 or j==20):
return 1
return step(i+1,j)+step(i,j+1)
print step(0,0)
But thi... |
I'm pretty sure there's a way to make this "3 times" duplicated code into only one. Any idea how to do this?
if (typeof sync.create!='undefined') {
for (var i = 0; i <sync.create.length; i++) {
sync.create[i].modified.id_partenaire=false;
};
}
if (typeof sync.update!='undefined') {
for (var i =... |
I am developing data-interfacing that converts between two different data models.
However, I must be sure that all required fields exist. Therefore I have written this utility class that I can easily use to verify required fields.
However I am unsure whether this is the best way because of the expression that needs to ... |
I've been learning Python 2.7 for about a week now and have written a quick program to ask for names of batters and printing a score sheet. I have then added the names to a list which I will use more in other future functions.
I have a few questions:
I feel like there is too much repetition in my code, such as the pro... |
I'm in the process of building some templates for Joomla, and although it all works as desired, I can't help thinking that there has to be a more elegant way to do this in PHP than my current approach. For the record, I'm still reasonably new to PHP!
Using collapsible module positions, I need to assign various CSS clas... |
var searchDetails = "";
searchDetails += $("#last-name").val();
searchDetails += searchDetails != "" ? " "+$("#first-name").val() : $("#first-name").val();
searchDetails += searchDetails != "" ? " "+$("#middle-name").val() : $("#middle-name").val();
if ($("#dob-dd").val() != "" || $("#dob-mm").val() != "" || $("#dob-yy... |
I have the following code, but I don't know how to make it run faster.
SELECT lot.order as lot_order,
lot.title as lot_title,
lot.id as lot_id,
lot.id_auction,
IF (
(SELECT bid
FROM bid
WHERE lot.id = bid.id_lot
ORDER BY bid.date DESC
LIMI... |
What would be the most efficent way to calculate this?
var reportLimit = 96*1024;
IEnumerable<int> memoryInUse =
things
.Where(sample => sample.IsOn)
.Select(sample => sample.MemoryInMb)
.ToArray();
int totalUnderReportLimit = memoryInUse.Where(ram => ram <= memoryCalcFactor).Sum();
int totalOverEqualR... |
Is there any way to improve this code? It looks a bit ugly for me.
if($url_chunks_num == 1) {
$this->controller = $this->pageData[0];
} elseif($url_chunks_num == 2) {
$this->controller = $this->pageData[0];
$this->action = $this->pageData[1];
} elseif($url_chunks_num > 2) {
$this->controller = $this->pa... |
count = 0
def merge_sort(li):
if len(li) < 2: return li
m = len(li) / 2
return merge(merge_sort(li[:m]), merge_sort(li[m:]))
def merge(l, r):
global count
result = []
i = j = 0
while i < len(l) and j < len(r):
if l[i] < r[j]:
result.append(l[i])
i +=... |
I'm building an option panel for a Wordpress theme. I'm just learning PHP and I wonder if there is any better (shorter) way to generate the social media links. Here's what I came up with and even tho it works, I think there are cleaner way to write it
<ul>
<?php if ( of_get_option('mm_sm_vimeo') ) { ?>
<li>
<a href="<?... |
I am running a Markov Chain Monte Carlo algorithm for updating a density distribution. There is a specific section of my code which tries to fill a very large matrix thetha.mh (of dimension 5000x2x60). the following code snippet is trying to fill the first dimension of my matrix, but the specific operation in second li... |
I have the following dataset
kkk<-data.frame(days=1:100,positive=rbinom(100,1,0.05))
Over the monitoring period of 100 days, if an event occurs then for that day kkk$positive==1 else kkk$positive==0
The following function, samples k=s.freq=1:12 number of times j=s.length=1:30 consecutive elements from the sample spac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.