indentation preference and personality - coding-style

This question is similar in spirit to :
https://stackoverflow.com/questions/492178/links-between-personality-types-and-language-technology-preferences
But it is based specifically on indentation (spaces vs tabs and the number of spaces).
The reason I am asking here instead of searching is because I remember seeing a specific document writing about this. If I remember correctly, it also talked about why Linus prefers eight spaces.

The document you are referring to is, I believe, the Linux Kernel Coding Standard:
https://computing.llnl.gov/linux/slurm/coding_style.pdf
Personally, I prefer four spaces, straight up. I try to keep it to 79 characters per line, unless I don't feel like it or there's a long string. When parenthetical statements or comments spill, I align the beginning to the next tab stop on the first line (or one past the next indentation level if I have to,) then align thereafter. Here is a sample of some of my code (taken from some random codebase I'm working on.) Notice what I do with that multi-line conditional.
void R_RecursiveWorldNode (mnode_t *node, int clipflags){
msurface_t *surf;
static vec3_t oldviewangle, oldorigin;
vec3_t deltaorigin, net_movement_angle;
float len_deltaorigin;
float movement_view_diff; //difference between the net movement
//angle and the view angle (0 when
//movement during frame was straight
//ahead.)
VectorSubtract (r_origin, oldorigin, deltaorigin);
len_deltaorigin = abs(len_deltaorigin);
VectorCopy (deltaorigin, net_movement_angle);
VectorNormalize(net_movement_angle);
VectorSubtract (net_movement_angle, vpn, net_movement_angle);
movement_view_diff = abs (movement_view_diff);
// if we have either a new PVS or a significant amount of
// movement/rotation, we should actually recurse the BSP again.
if ( (r_oldviewcluster != r_viewcluster && r_viewcluster != -1) ||
len_deltaorigin > 12.0 || vpn[YAW] != oldviewangle[YAW] ||
movement_view_diff > 1.0 ) {
VectorCopy (vpn, oldviewangle);
VectorCopy (r_origin, oldorigin);
r_ordinary_surfaces = NULL;
r_alpha_surfaces = NULL;
r_special_surfaces = NULL;
__R_RecursiveWorldNode (node, clipflags);
}
surf = r_ordinary_surfaces;
while (surf){
GL_RenderLightmappedPoly( surf );
surf = surf->ordinarychain;
}
}
This comes, I think, from being a Python programmer. It's C equivalent of the default indentation scheme in the IDLE editor which I used to use a lot.

Related

Text typing effect in C# based on current FPS and characters per second?

I am working on a typing effect for TextMeshPro texts in Unity that should take into account both the current FPS and the user input 'characters per second' (to determine the speed).
The implementation runs in an IEnumerator and displays one or more characters of a given text at a time. After displaying the char(s), there is a 'yield return new WaitForSeconds()' before the next round of revealing begins. (It should be possible to display more than one char at a time, because WaitForSeconds() takes too much time in some cases, even if I enter very small numbers. So rather than waiting after every single char, it should be waited after a precomputed number of chars to maintain the specified typing speed.)
I'm not sure if my approach works as intended in the different possible scenarios and additionally, I'm not happy with the computations within the IEnumerator because I think it could slow down the revealing process.
I tested the typing effect with different FPS in PlayMode (by setting the FPS with "Application.targetFrameRate" manually) and noticed that with FPS lower than 30 the text is revealed very haltingly and thus the viewer gets frustrated because it looks laggy. Maybe someone has experience with this and can suggest an easier way of implementation?
// Precompute the time for displaying a single character by a given number of characters per second:
public void GetTimePerChar() {
if (_charsPerSecond > 0) {
TimePerChar = 1f / _charsPerSecond;
} else {
TimePerChar = 0f;
}
// Coroutine that reveals characters of a given text over time:
private IEnumerator DisplayText() {
/* some other code */
while (TmpText.maxVisibleCharacters < TotalCharCount) { // Reveal characters until the the total amount of chars is reached
if (CharsPerSecond > 0) {
TimePerFrame = Time.deltaTime; // How much time does 1 frame take
if (TimePerChar > 0) {
CharsPerFrame = TimePerFrame / TimePerChar; // How many chars can be displayed within a single frame
} else {
CharsPerFrame = 0f;
}
CharsPerRound = (int)Math.Ceiling(CharsPerFrame); // Rounded up number of chars (as fractions doesn't make sense to display)
TimePerRound = TimePerChar * CharsPerRound; // The individual waiting time before the next char(s) get revealed
TmpText.maxVisibleCharacters += CharsPerRound; // Reveal one or more characters at a time
if (CharsPerRound - CharsPerFrame > 0) { // If the number of chars got rounded up wait afterwards as long as it shall take to display them
yield return new WaitForSeconds(TimePerRound);
}
} else {
TmpText.maxVisibleCharacters = TotalCharCount; // With zero CharsPerSecond, display the whole text at once
}
}
/* some other code */
}

How can I randomize a video to play after another by pressing a key on Processing?

I'm quite new to Processing.
I'm trying to make Processing randomly play a video after I clear the screen by mouseclick, so I create an array that contain 3 videos and play one at a time.
Holding 'Spacebar' will play a video and release it will stop the video. Mouseclick will clear the screen to an image. The question is how can it randomize to another video if I press spacebar again after clear the screen.
I've been searching all over the internet but couldn't find any solution for my coding or if my logic is wrong, please help me.
Here's my code.
int value = 0;
PImage photo;
import processing.video.*;
int n = 3; //number of videos
float vidN = random(0, n+1);
int x = int (vidN);
Movie[] video = new Movie[3];
//int rand = 0;
int index = 0;
void setup() {
size(800, 500);
frameRate(30);
video = new Movie[3];
video[0] = new Movie (this, "01.mp4");
video[1] = new Movie (this, "02.mp4");
video[2] = new Movie (this, "03.mp4");
photo = loadImage("1.jpg");
}
void draw() {
}
void movieEvent(Movie video) {
video.read();
}
void keyPressed() {
if (key == ' ') {
image(video[x], 0, 0);
video[x].play();
}
}
void mouseClicked() {
if (value == 0) {
video[x].jump(0);
video[x].stop();
background(0);
image(photo, 0, 0);
}
}
You have this bit of logic in your code which picks a random integer:
float vidN = random(0, n+1);
int x = int (vidN);
In theory, if you want to randomise to another video when the spacebar is pressed again you can re-use this bit of logic:
void keyPressed() {
if (key == ' ') {
x = int(random(n+1));
image(video[x], 0, 0);
video[x].play();
}
}
(Above I've used shorthand of the two lines declaring vidN and x, but the logic is the same. If the logic is harder to follow since two operations on the same line (picking a random float between 0,n+1 and rounding down to an integer value), feel free to expand back to two lines: readability is more important).
As side notes, these bit of logic look a bit off:
the if (value == 0) condition will always be true since value never changes, making both value and the condition redundant. (Perhaps you plan to use for something else later ? If so, you could save separate sketches, but start with the simplest version and exclude anything you don't need, otherwise, in general, remove any bit of code you don't need. It will be easier to read, follow and change.)
Currently your logic says that whenever you click current video resets to the start and stops playing and when you hit the spacebar. Once you add the logic to randomise the video that the most recent frame of the current video (just randomised) will display (image(video[x], 0, 0);), then that video will play. Unless you click to stop the current video, previously started videos (via play()) will play in the background (e.g. if they have audio you'll hear them in the background even if you only see one static frame from the last time space was pressed).
Maybe this is the behaviour you want ? You've explained a localised section of what you want to achieve, but not overall what the whole of the program you posted should do. That would help others provide suggestions regarding logic.
In general, try to break the problem down to simple steps that you can test in isolation. Once you've found a solid solution for each part, you can add each part into a main sketch one at a time, testing each time you add something. (This way if something goes wrong it's easy to isolate/fix).
Kevin Workman's How To Program is a great article on this.
As a mental excercise it will help to read through the code line by line and imagine what it might do. Then run it and see if the code behaves as you predicted/intended. Slowly and surely this will get better and better. Have fun learning!

MT4 expert trade panel - "OBJ_RECTANGLE_LABEL"

MetaTrader4 Expert Advisor for Trade Panel.
How can I link some OBJ_RECTANGLE_LABEL for moving with another single object?
Link 'em indirectly
There is no direct support for linking a few GUI-objects to move with another one.
This does not mean, it is not possible to have it working like this.
In one Augmented Trader UI-tool, I needed to have both all the GUI-components and some computed values behaving under some similar logic ( keeping all the lines, rectangles, text labels and heat-map colors, under some common UI-control-logic ). All the live-interactive-GUI orchestration was locked onto a few permited user-machine interactions, where the user was able to move with a set of UI-control-objects, some of which were freely modify-able, whereas some were restricted ( with the use of the augmented reality controllers ) to move just vertically or just horizontally or were just locked to start as tangents from the edges of Bollinger Bands in such a place, where the vertical line of the UI-control-object was moved by the user, etc.
The Live-interactive-GUI solution is simple:
Besides the [ Expert Advisor ] create and run another process, the [ Script ] that would be responsible for the GUI-object automation. Within this script, use some read-only values from objects, let's say a blue vertical line, as a SENSOR_x1, an input to the GUI-composition.
If someone or something moves this blue vertical line, your event-watching loop inside the script will detect a new value for the SENSOR_x1andre-process all the UI-layout scheme by adding the just observed / detected motion of a SENSOR_x1_delta = SENSOR_x1 - SENSOR_x1_previous;This way, one can update the motion detector-loop in the [ Script ], chasing all the SENSOR_* actual values and promoting the detected SENSOR_*_delta-s onto all objects, that are being used in the GUI-layout composition.
Finally it is worth to stage the updates of the screen with a few enforced WindowRedraw(); instructions, throughout the re-processing of the augmented reality in the Live-interactive-GUI.
Code from a PoC-demonstrator
One may notice, the code is in a pre-New-MQL4.56789 syntax, using some there permitted variable naming conventions, that ceased to be permitted now. The scope of the Event-Monitor function ( a self-contained function, optimised for max speed / min latency in handling all the three corners of the MVC-framework ( Model-is Live-GUI project-specific, Visual-is the Live-GUI augmentation-specific, Controller-is flexible and composed as a sort of Finite-State-Machine, from principal building blocks and implemented via "object.method" calls in the switch(){}. Loop sampling rate works great down to few tens of milliseconds, so the Live-GUI is robust and smoothly floating on the Trader's Desk.
This is not best way but schematically shows what to do.
string mainObjectNAME,
dependantObjectNAME; // dependant - your obj label
void OnChartEvent( const int id,
const long &lparam,
const double &dparam,
const string &sparam
){
if ( id == CHARTEVENT_OBJECT_DRAG
|| id == CHARTEVENT_OBJECT_ENDEDIT
){
if ( StringCompare( sparam, mainObjectNAME ) == 0 ){
datetime time1 = (datetime) ObjectGetInteger( 0, mainObjectNAME, OBJPROP_TIME1 );
double price1 = ObjectGetDouble( 0, dependantObjectNAME, OBJPROP_PRICE1 );
if ( !ObjectMove( 0, dependantObjectNAME, 0, time1, price1 ) )
Print( __LINE__,
"failed to move object ",
dependantObjectNAME
);
}
ChartRedraw();
}
}
if you modify the mainObject by any of the recognised means ( by dragging or passing other parameters ) - then dependant object ( OBJ_RECT_LABEL in your case ) is moved with ObjectMove() or ObjectSet() functions.

FMOD Ex dropping sounds, eventually going silent

I'm attempting to port an old open-source FMOD 3 game (Candy Crisis) to the latest version of FMOD Ex 4 on OS X. Its sound needs are very simpleā€”it plays WAVs, sometimes changing their frequency or speaker mix, and also plays MOD tracker music, sometimes changing the speed. I'm finding that the game works fine at first, but over the course of a few minutes, it starts truncating sounds early, then the music loses channels and eventually stops, then over time all sound ceases. I can cause the problem to reproduce more quickly if I lower the number of channels available to FMOD.
I can get the truncated/missing sounds issue to occur even if I never play a music file, but music definitely seems to make things worse. I have also tried commenting out the code which adjusts the sound frequency and speaker mix, and that was not the issue.
I am calling update() every frame.
Here's the entirety of my interactions with FMOD to play WAVs:
void InitSound( void )
{
FMOD_RESULT result = FMOD::System_Create(&g_fmod);
FMOD_ERRCHECK(result);
unsigned int version;
result = g_fmod->getVersion(&version);
FMOD_ERRCHECK(result);
if (version < FMOD_VERSION)
{
printf("Error! You are using an old version of FMOD %08x. This program requires %08x\n", version, FMOD_VERSION);
abort();
}
result = g_fmod->init(8 /* was originally 64, but 8 repros the issue faster */, FMOD_INIT_NORMAL, 0);
FMOD_ERRCHECK(result);
for (int index=0; index<kNumSounds; index++)
{
result = g_fmod->createSound(QuickResourceName("snd", index+128, ".wav"), FMOD_DEFAULT, 0, &s_sound[index]);
FMOD_ERRCHECK(result);
}
}
void PlayMono( short which )
{
if (soundOn)
{
FMOD_RESULT result = g_fmod->playSound(FMOD_CHANNEL_FREE, s_sound[which], false, NULL);
FMOD_ERRCHECK(result);
}
}
void PlayStereoFrequency( short player, short which, short freq )
{
if (soundOn)
{
FMOD::Channel* channel = NULL;
FMOD_RESULT result = g_fmod->playSound(FMOD_CHANNEL_FREE, s_sound[which], true, &channel);
FMOD_ERRCHECK(result);
result = channel->setSpeakerMix(player, 1.0f - player, 0, 0, 0, 0, 0, 0);
FMOD_ERRCHECK(result);
float channelFrequency;
result = s_sound[which]->getDefaults(&channelFrequency, NULL, NULL, NULL);
FMOD_ERRCHECK(result);
result = channel->setFrequency((channelFrequency * (16 + freq)) / 16);
FMOD_ERRCHECK(result);
result = channel->setPaused(false);
FMOD_ERRCHECK(result);
}
}
void UpdateSound()
{
g_fmod->update();
}
And here's how I play MODs.
void ChooseMusic( short which )
{
if( musicSelection >= 0 && musicSelection <= k_songs )
{
s_musicChannel->stop();
s_musicChannel = NULL;
s_musicModule->release();
s_musicModule = NULL;
musicSelection = -1;
}
if (which >= 0 && which <= k_songs)
{
FMOD_RESULT result = g_fmod->createSound(QuickResourceName("mod", which+128, ""), FMOD_DEFAULT, 0, &s_musicModule);
FMOD_ERRCHECK(result);
result = g_fmod->playSound(FMOD_CHANNEL_FREE, s_musicModule, true, &s_musicChannel);
FMOD_ERRCHECK(result);
EnableMusic(musicOn);
s_musicModule->setLoopCount(-1);
s_musicChannel->setPaused(false);
musicSelection = which;
s_musicPaused = 0;
}
}
If someone wants to experiment with this, let me know and I'll upload the project somewhere. My gut feeling is that FMOD is busted but I'd love to be proven wrong.
Sounds like your music needs to be set as higher priority than your other sounds. Remember, lower numbers are more important. I think you can just set the priority on the channel.
Every time I play the following WAV, FMOD loses one channel permanently. I am able to reproduce this channel-losing behavior in the "playsound" example if I replace the existing jaguar.wav with my file.
https://drive.google.com/file/d/0B1eDRY8sV_a9SXMyNktXbWZOYWs/view?usp=sharing
I contacted Firelight and got this response. Apparently WAVs can include a looping command! I had no idea.
Hello John,
I've taken a look at the two files you have provided. Both files end
with a 2 sample infinite loop region.
FMOD 4 (and FMOD 5 for that matter) will see the loop region in the
file and automatically enable FMOD_LOOP_NORMAL if you haven't
specified any loop mode. Assuming you want one-shot behavior just pass
in FMOD_LOOP_OFF when you create the sound.
Kind regards, Mathew Block | Senior Platform Engineer
Technically this behavior contradicts the documented behavior of FMOD_DEFAULT (which is specified to imply FMOD_LOOP_OFF) so they are planning to improve the documentation here.
Based on the wave sample you supplied, FMOD is behaving correctly as it appears you've figured out. The sample has a loop that is honored by FMOD and the last samples are simply repeated forever. While useless, this is correct and the variance in the samples is so slight as to not be audible. While not part of the original spec for wave format, extended information was added later to support meta data such as author, title, comments and multiple loop points.
Your best bet is to examine all your source assets for those that contain loop information. Simply playing all sounds without loop information is probably not the best workaround. Some loops may be intentional. Those that are will have code that stops them. Typically, in a game, the entire waveform is looped when looping is desired. You can then write or use a tool that will strip the loop information. If you do write your own tool, I'd recommend resampling the audio to the native output sampling rate of the hardware. You'd need to insure your resampler was sample accurate (no time shift) and did not introduce noise.
Historically, some game systems had a section at the end of the sound with silence and a loop point set on this region. The short reason for this was to reduce popping that might occur at the end of a sound in a hardware audio channel.
Curiosly, the last 16 samples of your .wav look like garbage and I'm wondering if the .wav assets you're using were converted from a source meant for a game console and that's where the bogus loop information came from as well.
This would have been a comment but my lowly rep does not allow it.

ZPL - zebra: print justified text block without overwriting last line

I'm using the following command to print a justified text:
^FB1800,3,0,J^FT100,200^A0B,26,26^FH\^FDLONG TEXT TO BE PRINTED, WHICH DOESNT FIT IN ONLY 3 LINES...^FS
The command ^FB1800,3,0,J prints a field block in a width of 1800 dots, maximum 3 lines, justified.
The problem is that if the text exceeds the maximum number of lines, it overwrites the last line! :( That of course makes the text of the last line unreadable.
How can I avoid that? Does anybody know if is there a way to cut the exceeding text?
The documentation says exactly that this happens:
Text exceeding the maximum number of lines overwrites the last line. Changing the font size automatically increases or decreases the size of the block.
For reference: I'm using printer Zebra 220Xi4.
Any help would be appreciated. Thank you!
Take a look at the ^TB command. It is preferred over the ^FB command and truncates if the text exceeds the size defined in the TB params
I had just about the same problem, what fixed it in my case - although not the most elegant way - is to specify a higher number of maximum lines, and then formatting it in a way that only the first 3 are in the visible area.
In your case it would be for example ^FB1800,7,0,J instead of ^FB1800,3,0,J
This at least fixed it for me right away, because I print this text at the bottom of the label. If you need to have it somewhere in the middle or top, there might be some tricks with putting a (white) box on top of the overflow-area, since the Zebra printers seem to render before printing. Hope it helps.
Depending on the higher-level programming language you're using (assuming that you are), you could accomplish the same thing (truncate the text to be printed to a specified number of characters) with code like this (C# shown here):
public void PrintLabel(string price, string description, string barcode)
{
const int MAX_CAPS_DESC_LEN = 21;
const int MAX_LOWERCASE_DESC_LEN = 32;
try
{
bool descAllUpper = HHSUtils.IsAllUpper(description);
if (descAllUpper)
{
if (description.Length > MAX_CAPS_DESC_LEN)
{
description = description.Substring(0, MAX_CAPS_DESC_LEN);
}
}
else // not all upper
{
if (description.Length > MAX_LOWERCASE_DESC_LEN)
{
description = description.Substring(0, MAX_LOWERCASE_DESC_LEN);
}
}
. . .
This is what I'm using; is there any reason to prefer the "raw" ^TB command over this?

Resources