let showDots = typeof project.showDots === 'boolean' ? project.showDots : false;

if (showDots) {
    // Somecode ...
}

Why, just why??

By Anonymous, 2017-08-08 11:41:49
        if (CATEGORY_NORMAL.equalsIgnoreCase(categorie)) {
            return assignGroupStartWithPrefix(assignmentGroups);
        } else if (CATEGORY_EXTERNAL.equalsIgnoreCase(categorie)) {
            return assignGroupStartWithPrefix(assignmentGroups);
        } 
By Anon, 2019-05-14 13:58:23


public static MyClass {
    private static volatile ProcessManager singleton = null;
    
    public static ProcessManager getInstance() throws Exception {
        if (singleton == null) {
            synchronized (MyClass.class) {
                if (singleton == null) {
                    singleton = new ProcessManager();
                }
            }
        }
        return singleton;
    }
}

The double-checking was invented prior to Java5.

The purpose is if the field isn't null, you don't have to synchronize. But since the java memory model specification was cleaned up and Synchronize/Volatile were given much better specification and semantics it is totally useless boilerplate that you should only write if you have to support Java4. There is a Google Tech Talk that covers this.

By cody, 2017-12-12 08:02:01
def MergeThings(config_file, list_of_things, output_dir):
    # read configparser config
    config = read_config(config_file)

    thing_string = ' --option '.join(list_of_things)

    cmd = ''
    cleaner_cmd = ''
    cleaner_cmd = """&& a=%s ; s=`python -c "b=[line.split() for line in  open('$a') if line.startswith('#COMMENT')][0][7:]; print '-ab ' +  ' -ab '.join([b[0]] +  b[-len(b)/2:])"`; java -Xmx1g -XX:ParallelGCThreads=1 -jar /path/to/a/java/command.jar -Z SelectThings -Y %s -W $a -U %s $s""" % (
        os.path.join(output_dir, config.get('PARAMETERS', 'NAME') + '.file.extension'), config.get('FILES' + config.get('PARAMETERS', 'REFERENCE'), 'REF'), os.path.join(output_dir, config.get('PARAMETERS', 'NAME') + '.cleaned.file.extention'))
    cmd = '%s -Xmx1g -XX:ParallelGCThreads=1 -Djava.io.tmpdir=/path/to/temp -jar %s -A doThings -B %s --option %s -otherOptions UNIQUE -C %s %s -D' % (config.get('SCRIPTS', 'JAVA'), config.get(
        'SCRIPTS', 'OTHER_SCRIPT'), config.get('FILES' + config.get('PARAMETERS', 'REFERENCE'), 'REF'), thing_string, os.path.join(output_dir, config.get('PARAMETERS', 'NAME') + '.file.extention.gz'), cleaner_cmd)

    return cmd

When scientists write code, sometimes it's not pretty. It's rather redacted ("thing" was not "thing" in the original). I especially love that the Bash part uses `` rather than $().

By AnonyMouse, 2019-07-17 04:14:11
{!! Form::select('ticket_category', \App\Models\Term::whereHas('taxonomy', function($query) {
    $query->where('slug', 'ticket_category'); 
  })->whereIn('id', ['15', '16', '17', '18'])
  ->pluck('name','id'), old('ticket_category'), [
    'id' => 'ticket_category', 
    'class' => 'form-control', 
    'placeholder' => 'Seleccione una categoría']
  )
!!}

to do it in an array if you can put it in the database so that you still burn the position

By ingbenjamincordero@gmail.com, 2020-05-08 01:39:27
if(!strncmp(pcTagName,strlim,(int)strlen(strlim))) return "";
By Anonymous, 2021-06-08 19:32:50
        int i = 0;
        while (conn == null && i < 116) {
            try {
                Thread.sleep(i < 30 ? 2000 : (i < 40 ? 6000 : (i < 56 ? 30000 : 60000)));
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                conn = Server.getConnection();
            } catch (Exception e) {
                //e.printStackTrace();
            }
            i++;
            if ((i < 41 && (i % 5) == 0)
                    || (i > 40 && i < 45)
                    || (i > 44 && i < 56 && (i % 2) == 0)
                    || (i > 55 && ((i - 56) % 3) == 0))
                System.out.print('.');
        }
By Anonymous, 2023-07-30 00:09:39
public class MetricsChecker
{
    protected const string AwaitingRecognitionCountMetricName = "AwaitingRecognitionCount";
    protected const string AwaitingExportCountMetricName = "AwaitingExportCount";
    protected const string NotYetDownloadedEventCountMetricName = "NotYetDownloadedEventCount";
    
    ...
    
    public virtual void PublishNotYetDownloadedEventCounts()
    {
        this.logger.Trace($"Starting to gather and publish {NotYetDownloadedEventCountMetricName}(s).");
        ...
    }
    
    ...
}
By Senior developer with 30 rear experience, 2019-12-13 16:22:28
if (botCount < botCount)
    this.reconnect();
}

My friend wrote this code recently

By Anonymous, 2017-12-13 17:47:25
public static class time
{
    public const int minutes_per_hour = 60;
    public const int seconds_per_minute = 60;
    public const int hours_per_day = 24;
    public const int minutes_per_day = minutes_per_hour * hours_per_day;
    public const int seconds_per_day = seconds_per_minute * minutes_per_day;
    public const int days_per_year = 365;
}
By Anonymous, 2018-10-15 17:15:52
$(document).on('click', '.edit-item', function(event) {
    let row_id = event.currentTarget.attributes['data-row'].value,
    data = dataIndex[
        dataIndex.findIndex(i => i.id === Number(row_id))
    ];
    $('.modal-body div:nth-child(1) input').attr('value', data.name)
    $('.modal-body div:nth-child(2) input').attr('value', data.category)
    $('.modal-body div:nth-child(3) #basicSelect').val(data.status)
    $('.modal-body div:nth-child(4) input').attr('value', data.price)
    $('.modal-body div:nth-child(5) input').attr('value', data.bju.mass)
    $('.modal-body div:nth-child(6) input').attr('value', data.bju.calories)
    $('.modal-body div:nth-child(7) input').attr('value', data.bju.proteins)
    $('.modal-body div:nth-child(8) input').attr('value', data.bju.fats)
    $('.modal-body div:nth-child(9) input').attr('value', data.bju.carbohydrates)
}
)
By Nik Destrave, 2021-05-30 21:59:31
  @Override
    public ResponseEntity<AuditLogPagedResults> getLogEntries(
    		@ApiParam(value = "Environment ID", required = true) @PathVariable("environmentId") Long environmentId,
	   	  	@ApiParam(value = "ID of the queue manager to browse") @Valid @RequestParam(value = "queueManager", required = false) Long queueManager,
	   	  	@ApiParam(value = "ID of the queue to browse") @Valid @RequestParam(value = "queue", required = false) Long queue,
	   	  	@ApiParam(value = "Browse for messages newer than a date/time") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) @RequestParam(value = "from", required = false) @Valid LocalDateTime from,
	   	  	@ApiParam(value = "Correlation ID to browse for") @Valid @RequestParam(value = "correlationId", required = false) String correlationId,
	   	  	@ApiParam(value = "Page of results to return") @Valid @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(value = "Number of results in a page") @Valid @RequestParam(value = "pagesize", required = false) Integer pagesize) {
        Pageable pageable = PageRequest.of(page != null ? page : 0, pagesize != null ? pagesize : defaultPageSize, new Sort(Sort.Direction.DESC, Audit.MSG_PUT_TIMESTAMP_FIELD));
        Page<Audit> auditEntries = null;
        Timestamp msgPut = (from != null ? Timestamp.valueOf(from) : null);

        /*
         * Environemnt is always supplied.  If we have queue or queue manager, assume that's what the caller wants.
         * We may also have some optional parameters - put timestamp, correlation ID
         */
        if (queue != null) {
        	//retrieve queue name
        	String queueName = null;
        	Optional<WMQQueue> queueEntity = wmqQueueRepository.findById(queue.intValue());
        	queueName = queueEntity.get().getQ_name();
        	
        	//see if we have timestamp or correlation ID
			if (msgPut != null) {
				if (correlationId != null) {
					auditEntries = auditRepository.findByQNameAndCorrelIdAndMsgPutTimestampGreaterThanEqual(queueName, msgPut, correlationId, pageable);
				} else {
					auditEntries = auditRepository.findByQNameAndMsgPutTimestampGreaterThanEqual(queueName, msgPut, pageable);
				}
			} else {
				if (correlationId != null) {
					auditEntries = auditRepository.findByQNameAndCorrelId(queueName, correlationId, pageable);
				} else {
					auditEntries = auditRepository.findByQName(queueName, pageable);
				}
			}
        } else if (queueManager != null) {
            List<Integer> managerIds = Arrays.asList(queueManager.intValue());
        	//see if we have timestamp or correlation ID
			if (msgPut != null) {
				if (correlationId != null) {
                    auditEntries = auditRepository.findByManagerIdsAndCorrelIdAndMsgPutTimestampGreaterThanEqual(managerIds, msgPut, correlationId, pageable);
				} else {
                    auditEntries = auditRepository.findByManagerIdsAndMsgPutTimestamp(managerIds, msgPut, pageable);
				}
			} else {
				if (correlationId != null) {
                    auditEntries = auditRepository.findByManagerIdsAndCorrelId(managerIds, correlationId, pageable);
				} else {
                    auditEntries = auditRepository.findByManagerIds(managerIds, pageable);
				}
			}
throw new java.lang.UnsupportedOperationException("Implementations does not exist");
        } else {
	        List<Integer> managerIds = findManagerIds(environmentId);
	
	        if(managerIds.isEmpty()) {
	            //No QueueManager so no possible log entries
	            return ResponseEntity.ok().body(null);
	        }
	
	        if (msgPut != null) {
	            auditEntries = auditRepository.findByManagerIdsAndMsgPutTimestamp(managerIds, msgPut, pageable);
	        } else {
	            auditEntries = auditRepository.findByManagerIds(managerIds, pageable);
	        }
        }
        
        
        /*
        if (correlationId != null && msgPut != null) {
            auditEntries = auditRepository.findByCorrelIdAndMsgPutTimestampGreaterThanEqual(correlationId, msgPut, pageable);
        } else if (queueName != null && msgPut != null) {
            auditEntries = auditRepository.findByQNameAndMsgPutTimestampGreaterThanEqual(queueName, msgPut, pageable);
        } else if (queueName != null) {
            auditEntries = auditRepository.findByQName(queueName, pageable);
        } else if (correlationId != null) {
            auditEntries = auditRepository.findByCorrelId(correlationId, pageable);
        } else {
            List<Integer> managerIds = findManagerIds(environmentId);

            if(managerIds.isEmpty()) {
                //No QueueManager so no possible log entries
                return ResponseEntity.ok().body(null);
            }

            if (msgPut != null) {
                auditEntries = auditRepository.findByManagerIdsAndMsgPutTimestamp(managerIds, msgPut, pageable);
            } else {
                auditEntries = auditRepository.findByManagerIds(managerIds, pageable);
            }
        }
*/
        if (auditEntries != null) {
	        AuditLogPagedResults results = new AuditLogPagedResults();
	        results.setPageNumber(pageable.getPageNumber());
	        results.setPageSize(pageable.getPageSize());
	        results.setPages(auditEntries.getTotalPages());
	        results.setResults(mapperFacade.mapAsList(auditEntries.getContent(), AuditLogEntry.class));
	        return ResponseEntity.ok().body(results);
        } else {
        	throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found");
        }
    }

    
    /* (non-Javadoc)
	 * @see com.arcelormittal.springTemplate.web.MessagesApi#getLogEntry(java.lang.Long, java.lang.Long)
	 */
	@Override
	public ResponseEntity<AuditLogEntry> getLogEntry(Long environmentId, Long logId) {
		Optional<Audit> entry = auditRepository.findById(logId);
		if (entry.isPresent()) {
			return ResponseEntity.ok().body(mapperFacade.map(entry.get(), AuditLogEntry.class));
		} else {
			throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Not found");
		}
	}

End pint to do a dynamic query in JPA.

By Anonymous, 2019-10-02 23:31:22
Select * from Order  --doesn't work
select * from [order] --works
--it's planning module in our system...

I think, it's really bad idea to use reserved words in names of tables. I'm surprised, that this db doesn't contain table named like [select]...

By solbrain, 2017-12-28 08:04:28
fn second_word(s: &String) -> &str {
    let bytes = s.as_bytes();
    let mut k = 0;
    let mut n =0;
    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            k = k + 1;
            if k == 1 {
                n = i;
            }
            else if k == 2 {
                return &s[1+n..i];
            }

        }
    }

    &s[..]
}

the code looks like shit

By big_shaq123, 2022-05-10 15:27:32
 # 5-level loop, forgive me...
        for xi, xs in enumerate(X):
            for yi, ys in enumerate(Y):
                for zi, zs in enumerate(Z):
                    lx, ly, lz = len(xs), len(ys), len(zs)
                    # construct points
                    xx, yy, zz = custom_meshgrid(xs, ys, zs)
                    world_xyzs = (
                        torch.cat(
                            [xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)],
                            dim=-1,
                        )
                        .unsqueeze(0)
                        .to(count.device)
                    )  # [1, N, 3]

                    # cascading
                    for cas in range(self.cascade):
                        bound = min(2**cas, self.bound)
                        half_grid_size = bound / resolution
                        # scale to current cascade's resolution
                        cas_world_xyzs = world_xyzs * (bound - half_grid_size)

                        # split batch to avoid OOM
                        head = 0
                        while head < B:
                            tail = min(head + S, B)

                            # world2cam transform (poses is c2w, so we need to transpose it. Another transpose is needed for batched matmul, so the final form is without transpose.)
                            cam_xyzs = cas_world_xyzs - poses[
                                head:tail, :3, 3
                            ].unsqueeze(1)
                            cam_xyzs = cam_xyzs @ poses[head:tail, :3, :3]  # [S, N, 3]

                            # query if point is covered by any camera
                            mask_z = cam_xyzs[:, :, 2] > 0  # [S, N]
                            mask_x = (
                                torch.abs(cam_xyzs[:, :, 0])
                                < cx / fx * cam_xyzs[:, :, 2] + half_grid_size * 2
                            )
                            mask_y = (
                                torch.abs(cam_xyzs[:, :, 1])
                                < cy / fy * cam_xyzs[:, :, 2] + half_grid_size * 2
                            )
                            mask = (
                                (mask_z & mask_x & mask_y).sum(0).reshape(lx, ly, lz)
                            )  # [N] --> [lx, ly, lz]

                            # update count
                            count[
                                cas,
                                xi * S : xi * S + lx,
                                yi * S : yi * S + ly,
                                zi * S : zi * S + lz,
                            ] += mask
                            head += S
By Anonymous, 2022-05-13 14:03:28