How many spaces is a tab in Java, Rust, C++, Python, C#, Powershell, Golang, Javascript

How many spaces is a tab in Java, Rust, C++, Python, C#, Powershell, Golang, Javascript

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How many spaces is a tab in Java, Rust, C+, Python, C#, Powershell, Golang, etc.

A tab is not made out of spaces. It is a tab, whether in Java, Python, Rust, or generic text file editing. It is represented by a single Unicode character, U+0009.

It does not generally mean “insert this many spaces here” either. It means “put the cursor at the next closest tab stop in the line”. What that means exactly depends on the context. On an old typewriter I had, a tab key would advance the roller to the next column that was a multiple of 10

How many spaces is a tab in Java

That is pretty much the same function as the tab character does.

Just for reference, modern text editors have their tab stops set to either every 4 or every 8 characters. That doesn’t mean that 1 tab = 4/8 spaces, that means that putting in a tab will align the cursor with the next multiple of 4/8 columns

How many spaces is a tab in Java

In mainstream IDEs you can set the tab key to insert a desired number of spaces instead of a tab character.


 The concept of tab independent of space is rarely used these days. In any case, what the character represents is decoupled from what the key does is decoupled from what the screen shows.

In many IDEs, the tab character inserts the required number of spaces to advance to the next tab line. This is often a default.

I imagine it’s a compromise between tab loving extremists and space advocates. The ideal whitespace character is a subject of intense debate among programmers.


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

Source: Quora

  • I just understood why programming is hard
    by /u/turtle_13 (programming) on March 18, 2024 at 6:53 pm

    I've been programming for 3.5 years and this person made sense for me submitted by /u/turtle_13 [link] [comments]

  • (2023) Source Generators - C#
    by /u/fagnerbrack (programming) on March 18, 2024 at 6:13 pm

    submitted by /u/fagnerbrack [link] [comments]

  • 11 Ways to Optimize Kubernetes Registry Performance
    by /u/codingdecently (programming) on March 18, 2024 at 5:44 pm

    submitted by /u/codingdecently [link] [comments]

  • Creating a GUI application in Haskell
    by /u/emigs95 (programming) on March 18, 2024 at 5:43 pm

    submitted by /u/emigs95 [link] [comments]

  • Oh Sh*t, My App is Successful and I Didn’t Think About Accessibility
    by /u/jacobs-tech-tavern (programming) on March 18, 2024 at 5:21 pm

    submitted by /u/jacobs-tech-tavern [link] [comments]

  • Running PostgreSQL Inside Your Browser With PGLite
    by /u/Active-Fuel-49 (programming) on March 18, 2024 at 5:13 pm

    submitted by /u/Active-Fuel-49 [link] [comments]

  • C++ creator rebuts White House warning
    by /u/Franco1875 (programming) on March 18, 2024 at 5:07 pm

    submitted by /u/Franco1875 [link] [comments]

  • Empirically Supported Code Review Best Practices
    by /u/troikaman (programming) on March 18, 2024 at 4:26 pm

    submitted by /u/troikaman [link] [comments]

  • Introduction To Low Latency Programming: Clarify Program Scope
    by /u/theseawolfe (programming) on March 18, 2024 at 3:38 pm

    submitted by /u/theseawolfe [link] [comments]

  • xAI open sources their LLM - Grok
    by /u/bubblehack3r (programming) on March 18, 2024 at 3:35 pm

    submitted by /u/bubblehack3r [link] [comments]

  • Optimizing the Particle Life: From 400 to 4 million particles
    by /u/nucle4r_attack (programming) on March 18, 2024 at 3:33 pm

    submitted by /u/nucle4r_attack [link] [comments]

  • Implementing Vertical Form Controls
    by /u/feross (programming) on March 18, 2024 at 3:30 pm

    submitted by /u/feross [link] [comments]

  • Five Koans of Software Architecture
    by /u/tonystubblebine (programming) on March 18, 2024 at 3:08 pm

    submitted by /u/tonystubblebine [link] [comments]

  • We used Redis to solve our Dynamic Task Scheduling and Concurrent Execution issues, here's how
    by /u/Only_Piccolo5736 (programming) on March 18, 2024 at 2:12 pm

    submitted by /u/Only_Piccolo5736 [link] [comments]

  • mongo-playground - Visual Studio Marketplace
    by /u/Charming-Treacle-726 (programming) on March 18, 2024 at 1:49 pm

    submitted by /u/Charming-Treacle-726 [link] [comments]

  • WebSockets vs Server-Sent-Events vs Long-Polling vs WebRTC vs WebTransport
    by /u/ApartmentWorking3164 (programming) on March 18, 2024 at 1:30 pm

    submitted by /u/ApartmentWorking3164 [link] [comments]

  • require(esm) in Node.js
    by /u/mariuz (programming) on March 18, 2024 at 1:16 pm

    submitted by /u/mariuz [link] [comments]

  • Zig, Rust, and other languages
    by /u/Xaneris47 (programming) on March 18, 2024 at 8:14 am

    submitted by /u/Xaneris47 [link] [comments]

  • JetBrains launches this new gen CI/CD with self-optimizing pipelines
    by /u/yegnau (programming) on March 18, 2024 at 8:12 am

    submitted by /u/yegnau [link] [comments]

  • Beginners Guide — Inner,Outer,left and right JOINS in SQL
    by Ashwini Shalke (Programming on Medium) on March 18, 2024 at 6:46 am

    What are Joins?Continue reading on Medium »

  • Top 5 ai programming languages 2024 You should know
    by pranjali AI (Programming on Medium) on March 18, 2024 at 6:25 am

    Python:Continue reading on Medium »

  • Yang mau jp siang ini Wa 081949831596 Link gacor : https://heylink.me/fika805
    by Fika Putri (Programming on Medium) on March 18, 2024 at 6:22 am

    Continue reading on Medium »

  • Complexity analysis of recursive functions.
    by John Anto (Programming on Medium) on March 18, 2024 at 6:19 am

    IntroductionContinue reading on Medium »

  • Simplifying Python Internationalization and Localization: A Practical Guide for Developers
    by Max N (Programming on Medium) on March 18, 2024 at 6:17 am

    Expand Your Python Applications’ Reach with Internationalization and Localization TechniquesContinue reading on Python in Plain English »

  • My Personal Tips for Not Getting Bored in Learning Programming
    by Josef Cruz (Programming on Medium) on March 18, 2024 at 6:17 am

    Even after doing it for a decade.Continue reading on JavaScript in Plain English »

  • 3 reasons why Devin will not replace programmers
    by AK (Programming on Medium) on March 18, 2024 at 6:11 am

    Lately, my timeline has been flooded with questions such as, “Will AI replace programmers in 2024?” or “Will AI take away my job?” These…Continue reading on Medium »

  • 7 Best CI/CD Tools for React in 2024
    by Jonathan Saring (Programming on Medium) on March 18, 2024 at 6:08 am

    Continuous Integration (CI) tools are pivotal in automating the software development process, especially for dynamic frameworks like React…Continue reading on Bits and Pieces »

  • Unveiling the Power of QuickBooks Cloud Hosting: Streamlining Financial Management in the Digital…
    by saksham singh (Programming on Medium) on March 18, 2024 at 5:55 am

    Small or huge agencies constantly seek ways to streamline operations and raise efficiency in a contemporary, fast-paced digital landscape…Continue reading on Medium »

  • Bloom Filters
    by /u/fagnerbrack (programming) on March 18, 2024 at 4:08 am

    submitted by /u/fagnerbrack [link] [comments]

  • Useful Uses of cat
    by /u/fagnerbrack (programming) on March 18, 2024 at 3:16 am

    submitted by /u/fagnerbrack [link] [comments]

  • announcing freenginx.org
    by /u/fagnerbrack (programming) on March 18, 2024 at 2:21 am

    submitted by /u/fagnerbrack [link] [comments]

  • JPEG DCT text lossifizer
    by /u/CrossFloss (programming) on March 17, 2024 at 8:32 pm

    submitted by /u/CrossFloss [link] [comments]

  • AWS Makes Cloud Formation Stack Creation up to 40% Faster
    by /u/rgancarz (programming) on March 17, 2024 at 6:09 pm

    submitted by /u/rgancarz [link] [comments]

  • The High-Risk Refactoring
    by /u/fagnerbrack (programming) on March 17, 2024 at 12:11 pm

    submitted by /u/fagnerbrack [link] [comments]

  • [META] The future of r/programming
    by /u/ketralnis (programming) on October 9, 2023 at 4:03 pm

    Hello fellow programs! tl;dr what should r/programming's rules be? And also a call for additional mods. We'll leave this stickied for a few days to gather feedback. Here are the broad categories of content that we see, along with whether they are currently allowed. ✅ means that it's currently allowed, 🚫 means that it's not currently allowed, ⚠️ means that we leave it up if it is already popular but if we catch it young in its life we do try to remove it early. ✅ Actual programming content. They probably have actual code in them. Language or library writeups, papers, technology descriptions. How an allocator works. How my new fancy allocator I just wrote works. How our startup built our Frobnicator, rocket ship emoji. For many years this was the only category of allowed content. ✅ Programming news. ChatGPT can write code. A big new CVE just dropped. Curl 8.01 released now with Coffee over IP support. ✅ Programmer career content. How to become a Staff engineer in 30 days. Habits of the best engineering managers. How to deal with your annoying coworkers, Jeff. ✅ Articles/news interesting to programmers but not about programming. Work from home is bullshit. Return to office is bullshit. There's a Steam sale on programming games. Terry Davis has died. How to SCRUMM. App Store commissions are going up. How to hire a more diverse development team. Interviewing programmers is broken. ⚠️ General technology news. Google buys its last competitor. A self driving car hit a pedestrian. Twitter is collapsing. Oculus accidentally showed your grandmother a penis. Github sued when Copilot produces the complete works of Harry Potter in a code comment. Meta cancels work from home. Gnome dropped a feature I like. How to run Stable Diffusion to generate pictures of, uh, cats, yeah it's definitely just for cats. A bitcoin VR metaversed my AI and now my app store is mobile social local. 🚫 Politics. The Pirate Party is winning in Sweden. Please vote for net neutrality. Big Tech is being sued in Europe for gestures broadly. 🚫 Gossip. Richard Stallman switches to Windows. Elon Musk farted. Linus Torvalds was a poopy-head on a mailing list. Grace Hopper Conference is now 60% male. The People's Rust Foundation is arguing with the Rust Foundation For The People. Terraform has been forked into Terra and Form. Stack Overflow sucks now. Stack Overflow is good actually. ✅ Demos with code. I wrote a game, here it is on GitHub 🚫 Demos without code. I wrote a game, come buy it! Please give me feedback on my startup (totally not an ad nosirree). I stayed up all night writing a commercial text editor, here's the pricing page. I made a DALL-E image generator. I made the fifteenth animation of A* this week, here's a GIF. 🚫 AskReddit type forum questions. What's your favourite programming language? Tabs or spaces? Does anyone else hate it when. 🚫 Support questions. How do I write a web crawler? How do I get into programming? Where's my missing semicolon? Please do this obvious homework problem for me. Personally I feel very strongly about not allowing these because they'd quickly drown out all of the actual content I come to see, and there are already much more effective places to get them answered anyway. In real life the quality of the ones that we see is also universally very low. 🚫 Surveys and 🚫 Job postings and anything else that is looking to extract value from a place a lot of programmers hang out without contributing anything itself. 🚫 Meta posts. DAE think r/programming sucks? Why did you remove my post? Why did you ban this user that is totes not me I swear I'm just asking questions. Except this meta post. This one is okay because I'm a tyrant that the rules don't apply to (I assume you are saying about me to yourself right now). 🚫 Images, memes, anything low-effort or low-content. Thankfully we very rarely see any of this so there's not much to remove but like support questions once you have a few of these they tend to totally take over because it's easier to make a meme than to write a paper and also easier to vote on a meme than to read a paper. ⚠️ Posts that we'd normally allow but that are obviously, unquestioningly super low quality like blogspam copy-pasted onto a site with a bazillion ads. It has to be pretty bad before we remove it and even then sometimes these are the first post to get traction about a news event so we leave them up if they're the best discussion going on about the news event. There's a lot of grey area here with CVE announcements in particular: there are a lot of spammy security "blogs" that syndicate stories like this. ⚠️ Posts that are duplicates of other posts or the same news event. We leave up either the first one or the healthiest discussion. ⚠️ Posts where the title editorialises too heavily or especially is a lie or conspiracy theory. Comments are only very loosely moderated and it's mostly 🚫 Bots of any kind (Beep boop you misspelled misspelled!) and 🚫 Incivility (You idiot, everybody knows that my favourite toy is better than your favourite toy.) However the number of obvious GPT comment bots is rising and will quickly become untenable for the number of active moderators we have. There are some topics such as Code of Conduct arguments within projects that I don't know where to place where we've been doing a civility check on the comments thread and using that to make the decision. Similarly some straddle the line (a link to a StackOverflow post asking for help and the reddit OP is the StackOverflow OP, but there's a lot of technical content and the reddit discussion is healthy). And even most 🚫s above are left up if there's a healthy discussion going already by the time we see it. So what now? We need to decide what r/programming should be about and we need to write those rules down so that mods can consistently apply them. The rules as written are pretty vague and the way we're moderating in practise is only loosely connected to them. We're looking for feedback on what kind of place r/programming should be so tell us below. We need additional mods. If you're interested in helping moderate please post below, saying why you'd be a good mod and what you'd would change about the space if you were. You don't need to be a moderator elsewhere but please do mention it if you are and what we could learn on r/programming that you already know. Currently I think I'm the only one going down the new page every morning and removing the rule-breaking posts. (Today these are mostly "how do I program computer" or "can somebody help me fix my printer", and obvious spam.) This results in a lot of threads complaining about the moderation quality and, well, it's not wrong. I'm not rigorously watching the mod queue and I'm not trawling comments threads looking for bad actors unless I'm in that thread anyway and I don't use reddit every single day. So if we want it to be better we'll need more human power. FAQ: Why do we need moderation at all? Can't the votes just do it? We know there is demand for unmoderated spaces in the world, but r/programming isn't that space. This is our theory on why keeping the subreddit on topic is important: Forums have the interesting property that whatever is on the front page today is what will be on the front page tomorrow. When a user comes to the site and sees a set of content, they believe that that's what this website is about. If they like it they'll stay and contribute that kind of content and if they don't like it they won't stay, leaving only the people that liked the content they saw yesterday. So the seed content is important and keeping things on topic is important. If you like r/programming then you need moderation to keep it the way that you like it (or make it be the place you wish it were) because otherwise entropic drift will make it be a different place. And once you have moderation it's going to have a subjective component, that's just the nature of it. Because of the way reddit works, on a light news day r/programming doesn't get enough daily content for articles to meaningfully compete with each other. Towards the end of the day if I post something to r/programming it will immediately go to the front page of all r/programming subscribers. So while it's true that sub-par and rule-breaking posts already do most of their damage before the mods even see them, the whole theory of posts competing via votes alone doesn't really work in a lower-volume subreddit. Because of the mechanics of moderation it's not really possible to allow the subreddit to be say 5% support questions. Even if we wanted to allow it to be a small amount of the conten, the individuals whose content was removed would experience and perceive this as a punitive action against them. That means that any category we allow could theoretically completely take over r/programming (like the career posts from last week) so we should only allow types of content that we'd be okay with taking it over. Personally my dream is for r/programming to be the place with the highest quality programming content, where I can go to read something interesting and learn something new every day. That dream is at odds with allowing every piece of blogspam and "10 ways to convince your boss to give you a raise, #2 will get you fired!" submitted by /u/ketralnis [link] [comments]

Git Cheat Sheet

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

Find Useful Git commands in this Git Cheat Sheet.

Here is a basic Git cheat sheet:

git init – Initialize a new git repository

git clone [repository] – Clone an existing repository

git status – Check the status of your repository


git add [file] – Add a file to the repository

git commit -m "[message]" – Commit changes with a message

git push – Push changes to a remote repository


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

git pull – Pull changes from a remote repository

git branch – Show the current branch

git branch [branch-name] – Create a new branch

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

git checkout [branch-name] – Switch to a different branch

git merge [branch-name] – Merge a branch into the current branch

git log – Show the commit history

git diff – Show changes between commits

git reset --hard [commit] – Reset repository to a specific commit

git stash – Stash changes

git stash apply – Apply stashed changes

Please note that this is a basic cheat sheet and git has many more functionalities and options, it is worth reading the git documentation to learn more.

  • Clone a project:
    git clone git_repo_url project_name
  • Switch to a branch locally:
    git checkout branch_name
  • Modify a file, then save and push it to remote repo in current branch
    git add path_to_file_modifeid/file_name
    git commit -m “Description of modification”
    git push
  • Get a new version of a file after modifying local version
    git checkout path_to_file_modified/file_modified
  • Get latest version of current branch
    git fetch
    git pull
    if you have local changes, you will be prompted to commit or stash them before pulling.
  • Create a new branch based on current branch and switch to it
    git checkout –b branch_name
  • Switch to master branch
    git checkout master
  • Merge branch_name to master
    git merge branch_name
  • Delete local branch
    git branch -d branch_name
  • Undo a merge or pull
    git reset –hard
  • Undo a commit locally and on the remote branch
    git reset –hard commit_id
    git push –force
  • Get remote url of a local branch
    git remote show origin

Source: https://git-scm.com

Script with hash tables on windows and Linux

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to declare and write a script with hash tables on windows and linux

A hash table, also known as a hash map, is a data structure that is used to store key-value pairs. It is an efficient way to store data that can be quickly retrieved using a unique key.

Here is an example of how to declare and write a script with a hash table in Python:

# Declare an empty hash table
hash_table = {}

# Add some key-value pairs to the hash table
hash_table[‘key1’] = ‘value1’
hash_table[‘key2’] = ‘value2’
hash_table[‘key3’] = ‘value3’

# Access a value using its key
print(hash_table[‘key2’]) # Output: “value2”


# Modify a value using its key
hash_table[‘key2’] = ‘new value’
print(hash_table[‘key2’]) # Output: “new value”

# Delete a key-value pair using the `del` statement
del hash_table[‘key1’]

# Check if a key is in the hash table using the `in` operator
print(‘key1’ in hash_table) # Output: False


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

# Output: False

In this example, we declare an empty hash table using the {} syntax. We then add some key-value pairs to the hash table using the [] syntax. We access a value using its key, modify a value using its key, delete a key-value pair using the del statement, and check if a key is in the hash table using the in operator.

I hope this helps! Let me know if you have any questions.

    • Hash tables with powershell on windows

      Declaration:
      $states=@{“Alberta” = “Calgary”; “British Columbia” = “Vancouver”; “Ontario” = “Toronto” ; “Quebec” = “Montreal”}

      Name
      _____
      Value
      _______
      AlbertaCalgary
      British ColumbiaVancouver
      OntarioToronto
      QuebecMontreal

      Add new key-value in hashtable:
      $states.Add(“Manitoba”,”Winnipeg”)

      Remove key-value in hashtable:
      $states.Remove(“Manitoba”,”Winnipeg”)
      Change value in hashtable:
      $states.Set_Item(“Ontario”,”Ottawa”)
      Retrieve value in hashtable:
      $states.Get_Item(“Alberta”)
      Find key in hashtable:
      $states.ContainsKey(“Alberta”)
      Find Value in hashtable:
      $states.ContainsValue(“Calgary”)
      Count items in hashtable:
      $states.Count
      Sort items by Name in hashtable:
      $states.GetEnumerator() | Sort-Object Name -descending
      Sort items by Value in hashtable:
      $states.GetEnumerator() | Sort-Object Value -descending

    • Hash tables with perl on linux or windows

      Declaration:
      my %hash = (); #Initialize a hash
      my $hash_ref = {}; # Initialize a hash reference. ref will return HASH
      Clear (or empty) a hash
      for (keys %hash)
      {
      delete $hash{$_};
      }
      Clear (or empty) a hash reference
      for (keys %$href)
      {
      delete $href->{$_};
      }
      Add a key/value pair to a hash
      $hash{ ‘key’ } = ‘value’; # hash
      $hash{ $key } = $value; # hash, using variables
      Using Hash Reference
      $href->{ ‘key’ } = ‘value’; # hash ref
      $href->{ $key } = $value; # hash ref, using variables
      Add several key/value pairs to a hash
      %hash = ( ‘key1’, ‘value1’, ‘key2’, ‘value2’, ‘key3’, ‘value3’ );
      %hash = (
      key1 => ‘value1’,
      key2 => ‘value2’,
      key3 => ‘value3’,
      );

      Copy a hash
      my %hash_copy = %hash; # copy a hash
      my $href_copy = $href; # copy a hash ref
      Delete a single key/value pair
      delete $hash{$key};
      delete $hash_ref->{$key};

Hash tables with python on linux or windows

Hash tables are called dictionary in python.
Declaration:
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}
Accessing Values
print “dict[‘Name’]: “, dict[‘Name’]
print “dict[‘Age’]: “, dict[‘Age’]
Output:
dict[‘Name’]: Zara
dict[‘Age’]: 7
Updating Dictionary
dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

dict[‘Age’] = 8; # update existing entry
dict[‘School’] = “DPS School”; # Add new entry
Delete Dictionary Elements
#!/usr/bin/python

dict = {‘Name’: ‘Zara’, ‘Age’: 7, ‘Class’: ‘First’}

del dict[‘Name’]; # remove entry with key ‘Name’
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary

Source:

  1. https://technet.microsoft.com/en-us/library/ee692803.aspx
  2. http://www.cs.mcgill.ca/~abatko/computers/programming/perl/howto/hash/
  3. http://www.tutorialspoint.com/python/python_dictionary.htm

How to pipe grep on command line on windows and Linux

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to pipe grep on command line on Windows and Linux?

Let’s find how to pipe grep or find a specific string after running a command using shell, batch and powershell (windows and Linux)

  • On Linux via shell

    ls -al | grep filename

  • On Windows via powershell

    GetChildItem | Select-Object “filename”
    or
    GetChildItem | where-Object {$_ -match “filename”}

  • On Windows via batch

    Dir | findstr “filename”

On both Windows and Linux, you can use the grep command in combination with the | (pipe) operator to filter the output of another command. The | operator takes the output of the command on the left and passes it as input to the command on the right.

Here is an example of how to use the grep command with the | operator on both Windows and Linux:

On Linux:

# List all the files in the current directory and filter the output to show only the files that contain the word "example"
ls | grep example

On Windows:


# List all the files in the current directory and filter the output to show only the files that contain the word "example"
dir | findstr example

In this example, the ls (Linux) or dir (Windows) command lists all the files in the current directory, and the grep (Linux) or findstr (Windows) command filters the output to show only the lines that contain the word “example”.

You can use the grep command with the | operator in combination with other command-line utilities to perform various tasks. For example, you can use the grep command to filter the output of the ps command to show only the processes that contain a particular string in their command line arguments.

# Show all the processes that contain the string "python" in their command line arguments
ps -aux | grep python

I hope this helps! Let me know if you have any questions.


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

reverse a string on Linux and Windows

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to reverse a string on Linux and Windows

On Linux:

  1. Using the rev command: The rev command is a utility that reverses the lines of a file or the characters in a string. To reverse a string, you can use the echo command to pass the string to rev:
echo "string" | rev
  1. Using the sed command: The sed command is a powerful utility that can perform various text transformations. To reverse a string, you can use the sed command with the -r option and the 's/.*(.)/\1/g' expression:
echo "string" | sed -r 's/.*(.)/\1/g'
  1. Using the awk command: The awk command is a programming language that is used for text processing. To reverse a string, you can use the awk command with the {print} action:
echo "string" | awk '{print $1}'

On Windows:

  1. Using the powershell command: The powershell command is a shell that provides a command-line interface for Windows. To reverse a string, you can use the powershell command with the -C option and the '[System.Text.Encoding]::Unicode.GetString([System.Text.Encoding]::Unicode.GetBytes("string"))' expression:
powershell -C "[System.Text.Encoding]::Unicode.GetString([System.Text.Encoding]::Unicode.GetBytes("string"))"
  1. Using the cmd command: The cmd command is the command-line interpreter for Windows. To reverse a string, you can use the cmd command with the for loop:
cmd /c "for /L %i in (1,1,%len%) do @echo !string:~%len%-%i,1!"

These are some ways to reverse a string on Linux and Windows. There are other ways to achieve this, using different utilities or programming languages.

Via shell script on Linux

reverse a string on Linux and Windows

sh-3.2# vi reverse.sh
#### Start Script #####
#!/bin/bash
input_string=”$1″
reverse_string=””


input_string_length=${#input_string}
for (( i=$input_string_length-1; i>=0; i– ))
do
reverse_string=”$reverse_string${input_string:$i:1}”
done

echo “$reverse_string”
##### End Script #####

Let’s run it:


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)

sh-3.2# chmod 775 reverse.sh
sh-3.2# ./reverse.sh Etienne
enneitE

Via powershell script on Windows

#Let’s use the script reverse.ps1 below.
######
$string=”Etienne”
$string_array=$string -split “”
[array]::Reverse($string_array)
$string_array -join ”

#####Output#####
PS C:\Users\etienne_noumen\Documents\Etienne\Scripting> .\reverse.ps1

If you are looking for an all-in-one solution to help you prepare for the AWS Cloud Practitioner Certification Exam, look no further than this AWS Cloud Practitioner CCP CLF-C02 book

E t i e n n e

enneitE

Via powershell script on Windows in one line

([regex]::Matches($String,’.’,’RightToLeft’) | ForEach {$_.value}) -join ”

Via batch script on Windows

::Note: ReverseStr also calls StrLen
::and string length is not greater than 80 chars
:: but can be changed.

@echo off
SetLocal EnableDelayedExpansion
cls
set Str=Etienne
call :StrLen %Str%
echo Length=%Len%
call :ReverseStr %Str%
echo String=%Str%
echo Reverse Str=%Reverse%
exit /b

::—————-
:: Calc Var Length
::—————-
:: %*=Str to Check
:: Returns %Len%
:: —————
:StrLen %*
set Data=%*
for /L %%a in (0,1,80) do (
set Char=!Data:~%%a,1!
if not “!Char!”==”” (
set /a Len=%%a+1
) else (exit /b)
)
exit /b

::—————
:: Reverse String
::—————
:: %* Str to Reverse
:: Returns %Reverse%
::——————
:ReverseStr %*
set Data=%*
call :StrLen %Data%
for /L %%a in (!Len!,-1,0) do (
set Char=!Data:~%%a,1!
set Reverse=!Reverse!!Char!
)
exit /b

Via perl script on Windows or Linux

Via python script on Windows or Linux

def reverse_string(a_string)
return a_string[::-1]
reverse_string(“etienne”) returns “enneite”
Source:

  1. http://www.computing.net/answers/programming/reverse-a-string-in-dos/26004.html

List only regular file names in a directory

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to List only regular file names in a directory on Linux and Windows

Listing regular files in a directory without including . and .. files.


  • On Linux

    Solution 1:$ ls -p | grep -v /
    Solution 2: $ ls -F | grep -v ‘[/@=|]’
    Solution 3: $for list in `ls` ; do ls -ld $list | grep -v ^d > /dev/null && echo $list ; done ;
    Solution4:$ for list in `ls` ; do ls -ld $list | grep ^d > /dev/null || echo $list ; done ;
    Solution5 (exclude sym links):$ for list in `ls` ; do ls -ld $list | grep -v ^l > /dev/null && echo $list ; done ;


  • On Windows

    Solution 1: dir /a-d /b >..\File_List.txt

prompt and read input variables from keyboard

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

Let’s find how to prompt and read input variables from keyboard while executing a script using shell, perl, python, batch and powershell (windows and Linux)

  • On Linux via shell

    read -p “Enter your name: ” name
    echo “Hi, $name. Let’s be friend!”

  • On Windows via powershell

    $name=read-host “Enter your name:”
    write-host “Hi $name, Let’s be friend!”

  • On Windows via batch

    Set /p Name=”Enter your name:”
    echo “Hi %name%, Let’s be friend!”

  • On Windows or Linux via perl

    print “Enter your name “;
    my $name = ;
    chomp $name; # Get rid of newline character at the end
    print “Hello $name, let’s be friend”;

  • On Windows or Linux via python

    name=input(“Enter your name: “)
    print (“Hello ” + name + ” let’s be friend”)

Replace all instances of a string in a file

How to Replace all instances of a string in a file?

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to Replace all instances of a string in a file?

  1. Open the file in read mode using the open() function.
  2. Read the contents of the file into a string using the read() method.
  3. Use the replace() method to replace all instances of the target string with the new string.
  4. Open the file in write mode using the open() function.
  5. Write the modified string to the file using the write() method.
  6. Close the file using the close() method.

Here is an example code snippet:

How to Replace all instances of a string in a file?
How to Replace all instances of a string in a file?

This will replace all instances of old_string with new_string in the file file.txt.

# Open the file in read mode
with open(‘file.txt’, ‘r’) as f:
# Read the contents of the file into a string
contents = f.read()

# Replace all instances of the target string
contents = contents.replace(‘old_string’, ‘new_string’)


# Open the file in write mode
with open(‘file.txt’, ‘w’) as f:
# Write the modified string to the file
f.write(contents)

# Close the file
f.close()

Shell script to replace all instances of a string in a file on Linux & Windows.

  • On Linux via bash script

    sed “s/$stringToReplace/$replaceWith/g” $File_Name > $File_Name

  • On Windows using Powershell

    ( get-content $File_Name ) | % { $_ -replace $stringToReplace, $replaceWith } | set-content $File_Name

  • On Windows using Batch

    set str=teh cat in teh hat
    echo.%str%
    set str=%str:teh=the%
    echo.%str%

    Script Output:
    teh cat in teh hat
    the cat in the hat

  • On Windows or Linux using Perl

    perl -pi.orig -e “s///g;”

  • On Windows or Linux using Python

Source:


AI Unraveled: Demystifying Frequently Asked Questions on Artificial Intelligence (OpenAI, ChatGPT, Google Bard, Generative AI, Discriminative AI, xAI, LLMs, GPUs, Machine Learning, NLP, Promp Engineering)
  1. http://stackoverflow.com/questions/60034/how-can-you-find-and-replace-text-in-a-file-using-the-windows-command-line-envir

Search all files containing a specific string

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to search all files containing a specific string on Linux and Windows?

  • On Linux

    grep -rnw ‘directory’ -e “pattern”
    grep –include=\*.{txt,log} -rnw ‘directory’ -e “pattern”
    This will only search for files with .txt or .log extension.
    grep –exclude=*.txt -rnw ‘directory’ -e “pattern”
    This will exclude files with .txt extensions.

  • On Windows

    CD Location
    FINDSTR /L /S /I /N /C:”pattern” *.log

Browse the internet via command line

AI Dashboard is available on the Web, Apple, Google, and Microsoft, PRO version

How to browse the internet via command line on Linux and Windows?

  • On Linux

    lynx http://google.ca
    If you don’t have lynx on your linux installation, you will have to install it. On Linux Red hat, install it like this:
    yum list lynx (to check the availability of the package)
    yum -y install lynx (to install the package)
    you can also use: curl -0 http://yoursite/index.html to get the source code of a specific file.

  • On Windows

    start /max http://google.ca
    Will open the url using your default browser.

Pass the 2023 AWS Cloud Practitioner CCP CLF-C02 Certification with flying colors Ace the 2023 AWS Solutions Architect Associate SAA-C03 Exam with Confidence Pass the 2023 AWS Certified Machine Learning Specialty MLS-C01 Exam with Flying Colors

List of Freely available programming books - What is the single most influential book every Programmers should read



#BlackOwned #BlackEntrepreneurs #BlackBuniness #AWSCertified #AWSCloudPractitioner #AWSCertification #AWSCLFC02 #CloudComputing #AWSStudyGuide #AWSTraining #AWSCareer #AWSExamPrep #AWSCommunity #AWSEducation #AWSBasics #AWSCertified #AWSMachineLearning #AWSCertification #AWSSpecialty #MachineLearning #AWSStudyGuide #CloudComputing #DataScience #AWSCertified #AWSSolutionsArchitect #AWSArchitectAssociate #AWSCertification #AWSStudyGuide #CloudComputing #AWSArchitecture #AWSTraining #AWSCareer #AWSExamPrep #AWSCommunity #AWSEducation #AzureFundamentals #AZ900 #MicrosoftAzure #ITCertification #CertificationPrep #StudyMaterials #TechLearning #MicrosoftCertified #AzureCertification #TechBooks

Top 1000 Canada Quiz and trivia: CANADA CITIZENSHIP TEST- HISTORY - GEOGRAPHY - GOVERNMENT- CULTURE - PEOPLE - LANGUAGES - TRAVEL - WILDLIFE - HOCKEY - TOURISM - SCENERIES - ARTS - DATA VISUALIZATION
zCanadian Quiz and Trivia, Canadian History, Citizenship Test, Geography, Wildlife, Secenries, Banff, Tourism

Top 1000 Africa Quiz and trivia: HISTORY - GEOGRAPHY - WILDLIFE - CULTURE - PEOPLE - LANGUAGES - TRAVEL - TOURISM - SCENERIES - ARTS - DATA VISUALIZATION
Africa Quiz, Africa Trivia, Quiz, African History, Geography, Wildlife, Culture

Exploring the Pros and Cons of Visiting All Provinces and Territories in Canada.
Exploring the Pros and Cons of Visiting All Provinces and Territories in Canada

Exploring the Advantages and Disadvantages of Visiting All 50 States in the USA
Exploring the Advantages and Disadvantages of Visiting All 50 States in the USA


Health Health, a science-based community to discuss health news and the coronavirus (COVID-19) pandemic

Today I Learned (TIL) You learn something new every day; what did you learn today? Submit interesting and specific facts about something that you just found out here.

Reddit Science This community is a place to share and discuss new scientific research. Read about the latest advances in astronomy, biology, medicine, physics, social science, and more. Find and submit new publications and popular science coverage of current research.

Reddit Sports Sports News and Highlights from the NFL, NBA, NHL, MLB, MLS, and leagues around the world.

error: Content is protected !!