https://note.iqubit.xyz/
Copyright © 2022
2022-12-29T20:48:00Z
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/ml/pytorch-getting-started-with-cuda
Getting Started with PyTorch and NVidia CUDA
2022-09-30T00:00:00Z
<h3 id="installing-pytorch">Installing PyTorch</h3>
<p>Official <a href="https://pytorch.org/get-started/locally">pytorch.org install instructions</a> offers stable version version of pyTorch with slightly older version of CUDA which is 11.6 instead of latest (11.7)</p>
<p>We wanna show here how to install it with CUDA 11.7 SDK Toolkit support.</p>
<p>Start a shell (powershell/command prompt with python added to path),</p>
<pre><code>pip3 install --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu117 --upgrade
</code></pre>
<p><strong>refs</strong></p>
<ul>
<li><p>Official install instructions: <a href="https://pytorch.org/get-started/locally">https://pytorch.org/get-started/locally</a></p>
</li>
<li><p>CUDA 11.7 on pytroch official site doesn't exist yet, <a href="https://download.pytorch.org/whl/cu117">https://download.pytorch.org/whl/cu117</a></p>
</li>
<li><p>CloudCasts - Alan Smith - PyTorch & CUDA Setup - Windows 10 <a href="https://www.youtube.com/watch?v=GMSjDTU8Zlc">https://www.youtube.com/watch?v=GMSjDTU8Zlc</a></p>
</li>
<li><p>Platform nvidia refs</p>
</li>
<li><p><a href="https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64">Linux x64 build</a></p>
</li>
<li><p><a href="https://developer.nvidia.com/cuda-downloads?target_os=Windows&target_arch=x86_64&target_version=11">Windows x64 build</a></p>
</li>
<li><p><a href="https://developer.nvidia.com/cuda-toolkit">https://developer.nvidia.com/cuda-toolkit</a></p>
</li>
</ul>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/startup/typeahead-survey-2022-01
TypeAhead Product Survey
2022-02-01T00:00:00Z
<h3 id="what-is-typeahead">What is TypeAhead?</h3>
<p>By Typeahead we are referring to auto complete suggestion products.</p>
<p>A nice high level introduction and general guidelines of predictive search ca be found at
<a href="https://www.algolia.com/blog/ux/what-are-predictive-search-and-autocomplete">algolia blog - What is predictive search? What is autocomplete?</a></p>
<h3 id="system-design-examples">System Design Examples</h3>
<p>Here are some examples of system Design,</p>
<ul>
<li><a href="https://medium.com/@iftimiealexandru/learning-to-build-an-autocomplete-system-2c2e9f423537">Pedro Lopes blog - Learning to build an Autocomplete System</a> and <a href="https://github.com/lopespm/autocomplete">his github repository</a> demos an implemention</li>
<li><a href="https://dingdingsherrywang.medium.com/system-design-autocomplete-62420021adb0">https://dingdingsherrywang.medium.com/system-design-autocomplete-62420021adb0</a></li>
<li><a href="https://www.educative.io/courses/grokking-the-system-design-interview/mE2XkgGRnmp#div-stylecolorblack-background-colore2f4c7-border-radius5px-padding5px11-personalizationdiv">https://www.educative.io/courses/grokking-the-system-design-interview/mE2XkgGRnmp#div-stylecolorblack-background-colore2f4c7-border-radius5px-padding5px11-personalizationdiv</a></li>
<li>From an algorithmic perspective, how to scale TRIE Data Structure
<a href="https://www.youtube.com/watch?v=jFOR1LBEUgM">https://www.youtube.com/watch?v=jFOR1LBEUgM</a></li>
</ul>
<h3 id="autocomplete-apis">Autocomplete APIs</h3>
<p>Some existing Autocomplete APIs,</p>
<ul>
<li>Bing Autosuggest API, (MS Bing](<a href="https://www.microsoft.com/en-us/bing/apis/bing-autosuggest-api">https://www.microsoft.com/en-us/bing/apis/bing-autosuggest-api</a>)</li>
<li>Opera autocomplete in custom search engine, ref
<a href="https://superuser.com/questions/606778/opera-autocomplete-in-custome-search-engine">https://superuser.com/questions/606778/opera-autocomplete-in-custome-search-engine</a></li>
<li>clearbit Autocomplete API, <a href="https://clearbit.com/docs#autocomplete-api">https://clearbit.com/docs#autocomplete-api</a>
<blockquote>
<p>Company Autocomplete is an API that lets you auto-complete company names and retreive logo and domain information.</p>
</blockquote>
</li>
</ul>
<p>Google TypeAhead team provides a high level overview in their blog posts,
<a href="https://blog.google/products/search/how-google-autocomplete-works-search">google blog - How Google autocomplete works in Search</a></p>
<blockquote>
<p>You'll notice we call these autocomplete "predictions" rather than "suggestions" and there's a good reason for that. Autocomplete is designed to help people complete a search they were intending to do, not to suggest new types of searches to be performed. These are our best predictions of the query you were likely to continue entering.</p>
</blockquote>
<p>They identifies areas of integrity as well.</p>
<p>google query autocomplete api related references</p>
<ul>
<li><a href="https://simplestepscode.com/autocomplete-data-tutorial">https://simplestepscode.com/autocomplete-data-tutorial</a></li>
<li>Google Maps placce autocomplete api: <a href="https://developers.google.com/maps/documentation/places/web-service/query">https://developers.google.com/maps/documentation/places/web-service/query</a></li>
<li><a href="https://stackoverflow.com/questions/6428502/google-search-autocomplete-api">https://stackoverflow.com/questions/6428502/google-search-autocomplete-api</a></li>
<li><a href="https://developers.google.com/custom-search/v1/overview">https://developers.google.com/custom-search/v1/overview</a></li>
<li><a href="https://developers.google.com/custom-search/v1/site_restricted_api">https://developers.google.com/custom-search/v1/site_restricted_api</a></li>
</ul>
<p>Google Cloud Platform Autocomplete Products</p>
<ul>
<li>GCP Retail Search has auto complete features. ref, <a href="https://cloud.google.com/retail/docs/completion-overview">https://cloud.google.com/retail/docs/completion-overview</a></li>
<li>GCP Talent Autocomplete: <a href="https://cloud.google.com/talent-solution/job-search/docs/autocomplete">https://cloud.google.com/talent-solution/job-search/docs/autocomplete</a></li>
</ul>
<p>On the frontend side, we got following examples,</p>
<ul>
<li><a href="https://twitter.github.io/typeahead.js/examples">https://twitter.github.io/typeahead.js/examples</a></li>
<li>Google places autocomplete implementation using Twitter bootstrap typeahead and Google's autocomplete and geocoding services <a href="https://gist.github.com/badsyntax/4330899">https://gist.github.com/badsyntax/4330899</a></li>
<li><a href="https://stackoverflow.com/questions/18385148/typeahead-js-populate-dataset">https://stackoverflow.com/questions/18385148/typeahead-js-populate-dataset</a></li>
<li><a href="https://github.com/walmartlabs/typeahead.js-legacy">https://github.com/walmartlabs/typeahead.js-legacy</a></li>
</ul>
<h3 id="summary">Summary</h3>
<p>Twitter's typeahead works as nice example on frontent side: static typeahead prediction.</p>
<p>We can start with a bootstrap and then gradually build a dataset from people's interactions. It is an interesting problem find good quality dataset to cover some category of predictions.</p>
<p><em>NOTE</em>: this article might seem highly technical, let us know in comments if you have any question or have specific questions.</p>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/coin/alt-coins
Alt Coins
2021-12-02T00:00:00Z
<h3 id="what-are-alt-coins">What are Alt Coins?</h3>
<p>By Alt Coins I refer to the coins that are,</p>
<ul>
<li>not main stream</li>
<li>might still be in early stage</li>
<li>has potential as it brings someting new to the table</li>
</ul>
<p>For example, ETH, ADA, DOGE etc are not alt coins. These are already well known coins.</p>
<h3 id="sources">Sources</h3>
<p><strong>Popular Exchanges</strong></p>
<p>Tentatively, most stable alt coins can be found at,</p>
<ul>
<li>coinbase</li>
<li>binance.us *</li>
<li>kraken</li>
<li>venmo</li>
<li>crypto app</li>
</ul>
<p>*<em>Coin Trackers</em></p>
<ul>
<li>coinmarketcap</li>
<li>reddit - crypto moonshot</li>
<li>telegram - numerous crypto groups</li>
</ul>
<p><strong>news source</strong>
yet to draft..</p>
<p><strong>Coinbase</strong>
We surf <a href="https://www.coinbase.com/trade">coinbase.com/trade</a> and sort them in ascending order of Market Cap. That gives us list of established alt coins. Here's a screenshot from today,</p>
<p><img src="https://note.iqubit.xyz/img/alt-coins-cb.png" alt="Coinbase Assets sorted Market Cap"></p>
<p>There's your potential alt coins. Please note that, coinbase is more toward mainstream, more stable. You find less risky alt coins here and hence less growth, mostly.</p>
<p><strong>Binance US</strong>
Similarly, we surf <a href="https://www.binance.us/en/markets">binance.us/en/markets</a> and sort them in ascending order of Market Cap. That gives us list of established alt coins. Here's a screenshot today,</p>
<p><img src="https://note.iqubit.xyz/img/alt-coins-bn-us.png" alt="Binance US Assets sorted Market Cap"></p>
<p>* <em>I don't have access to international binance, hence, I mention US product</em></p>
<p><strong>coinmarketcap</strong>
Trending crypto: <a href="https://coinmarketcap.com/trending-cryptocurrencies">coinmarketcap.com/trending-cryptocurrencies</a>
Surfing <a href="https://coinmarketcap.com/new">coinmarketcap.com/new</a> we are able to find even riskier, potential trendy coins. Reserach and invest on your own risk.</p>
<h3 id="references">References</h3>
<p><em>Not an investment advice. Opions are personal, don't represent my employer.</em></p>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/linux/fedora
Fedora Linux Motley
2021-10-24T00:00:00Z
<p><em>this is still a draft, sections need to be organized, divided into separate posts for certain topics</em></p>
<p>First section is for Fedora 25.</p>
<p>New fedora uses in memory swap, swap partitions are no more required.</p>
<p>To find devices,</p>
<pre><code>lsblk
</code></pre>
<p>How to find unallocated disk partition with parted or another tool?</p>
<p>parted /dev/sdb free</p>
<p>Creating bootable USB fedora</p>
<pre><code>clean
conver gpt
</code></pre>
<p>Create .ssh dir to connect using ssh key,</p>
<pre><code>sudo su - atiq
mkdir .ssh
chmod 700 .ssh
touch .ssh/authorized_keys
chmod 600 .ssh/authorized_keys
</code></pre>
<p>Fedora Media Writer,</p>
<p><strong>refs</strong></p>
<ul>
<li><a href="https://docs.fedoraproject.org/en-US/quick-docs/installing-chromium-or-google-chrome-browsers">https://docs.fedoraproject.org/en-US/quick-docs/installing-chromium-or-google-chrome-browsers</a></li>
<li><a href="https://note.iqubit.xyz/posts/google-chrome-linux">https://note.iqubit.xyz/posts/google-chrome-linux</a></li>
</ul>
<p><strong>How to install manual pages for C/C++</strong></p>
<pre><code>dnf install man-pages libstdc++-docs
</code></pre>
<p><strong>Install TP Link Wireless Driver packages in fedora</strong>
(probably from 10 years ago, however, principle still might apply)</p>
<p>Our WIFI adapter model is TL-WN722N
info for linux driver at <a href="https://help.ubuntu.com/community/HardwareSupportComponentsWirelessNetworkCardsTP-Link#USB">ubunut.com</a></p>
<p><code>lsusb</code> command says it has ar9271 chip. Fedora supports it by following <code>ar9271.fw</code>,</p>
<pre><code># rpm -q --whatprovides /usr/lib/firmware/ar9271.fw
linux-firmware-20120206-0.3.git06c8f81.fc17.noarch
</code></pre>
<p>It has the AR9170 chipset as forum says.</p>
<ul>
<li><p>list loaded modules</p>
<pre><code>less /proc/modules
</code></pre>
</li>
<li><p>see module info</p>
<pre><code>ath9k_htc
ath9k_common
ath9k_hw
provides
firmware: htc_9271.fw
firmware: htc_7010.fw
ath
</code></pre>
</li>
</ul>
<p>current fedora driver & firmware: <code>ar9170-firmware-2009.05.28-4.fc17.noarch</code></p>
<p>When a problem occurs update following packages</p>
<ul>
<li>wireless-tools</li>
<li>ar9170-firmware-2009.05.28-4.fc17.noarch (most probably it is working for tp link tl-wn722n)</li>
<li>ath_info (provides information)</li>
</ul>
<p>install cmd,</p>
<pre><code>dnf -y update ar9170-firmware wireless-tools linux-firmware
</code></pre>
<p>listing firmware packages,</p>
<pre><code># rpm -qa | grep firmware
ar9170-firmware-2009.05.28-4.fc17.noarch
iwl6000g2b-firmware-17.168.5.2-2.fc17.noarch
iwl5000-firmware-8.83.5.1_1-2.fc17.noarch
atmel-firmware-1.3-9.fc17.noarch
linux-firmware-20120206-0.3.git06c8f81.fc17.noarch
alsa-firmware-1.0.25-1.fc17.noarch
iwl1000-firmware-39.31.5.1-2.fc17.noarch
iwl100-firmware-39.31.5.1-3.fc17.noarch
ql2500-firmware-5.06.05-1.fc17.noarch
iwl4965-firmware-228.61.2.24-4.fc17.noarch
rt73usb-firmware-1.8-9.fc17.noarch
netxen-firmware-4.0.534-5.fc17.noarch
iwl6000-firmware-9.221.4.1-3.fc17.noarch
iwl6050-firmware-41.28.5.1-4.fc17.noarch
iwl6000g2a-firmware-17.168.5.3-2.fc17.noarch
ivtv-firmware-20080701-22.noarch
rt61pci-firmware-1.2-9.fc17.noarch
iwl3945-firmware-15.32.2.9-6.fc17.noarch
libertas-usb8388-firmware-5.110.22.p23-6.fc17.noarch
aic94xx-firmware-30-3.fc17.noarch
ipw2100-firmware-1.3-13.fc17.noarch
ipw2200-firmware-3.1-6.fc17.noarch
alsa-tools-firmware-1.0.25-2.fc17.x86_64
iwl5150-firmware-8.24.2.2-3.fc17.noarch
zd1211-firmware-1.4-6.fc17.noarch
</code></pre>
<p><strong>How to install avro-keyboard in fedora</strong>
(from 2016 or earlier)</p>
<p>Install scim and development files. We need devel files for compiling scim-avro
Run following commands as root
yum -y install scim-devel scim</p>
<p>clone scim-avro latest version.</p>
<pre><code>git clone https://github.com/mominul/scim-avro
cd scim-avro/
chmod a+x configure
./configure
make
sudo make install
</code></pre>
<p>As a regular run following command <code>im-chooser</code></p>
<p>some cmds from online,</p>
<pre><code>cd
chmod a+x configure
./configure
cd po
msginit --input=scim-avro.pot --output-file=ja.po --locale=ja
</code></pre>
<p>In old times, we used to <code>groupinstall bengali-support</code> for Bangla lang support. ref, <a href="https://github.com/mominul/scim-avro">scim-avro</a></p>
<p><strong>install video players in fedora core</strong>
adding codecs/ plugins for totemplayer,</p>
<pre><code> dnf -y install gstreamer-plugins-good gstreamer-plugins-good-extras gstreamer-plugins-ugly
</code></pre>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/google-chrome-linux
Google Chrome on Linux
2021-10-24T00:00:00Z
<p>In new system, i.e, fedora 34/35 etc this is the way,</p>
<pre><code>sudo dnf config-manager --set-enabled google-chrome
sudo dnf install google-chrome-stable
</code></pre>
<p>If you want to install a beta release of google-chrome apply this command,</p>
<pre><code>$ sudo dnf install google-chrome-beta
</code></pre>
<p>To install the latest development release apply following,</p>
<pre><code>$ sudo dnf install google-chrome
</code></pre>
<p>If you are using other operating systems continue reading.</p>
<p>Generally, there are 3 ways of installing Google Chrome:</p>
<ul>
<li>Using dnf (<code>apt-get</code> on Ubuntu), setting up with google's repository in dnf configuration file or ubuntu's aptitude source.lst</li>
<li>Locally download chrome rpm or debian package and apply dnf localinstall command</li>
<li>last option: Download all dependencies manually and install them one by one, then install google-chrome package.</li>
</ul>
<h3 id="earlier-systems-fedora-core-rhel-cent-os-etc">Earlier Systems (Fedora Core, RHEL, Cent-OS etc)</h3>
<p>To enable google's dnf repository add a repo file inside directory <code>/etc/dnf.repos.d/</code> named google-chrome.repo For 64 bit systems contents should look like this,</p>
<pre><code>[google-chrome]
name=google-chrome - \$basearch
baseurl=http://dl.google.com/linux/chrome/rpm/stable/\$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
</code></pre>
<p>Afterwards, if you want to install a stable release of google-chrome apply this command,</p>
<pre><code>$ sudo dnf install google-chrome-stable
</code></pre>
<p>If you have trouble accessing https URLs substitute https using http on the gpgkey field. This is useful when you hit errors like this,</p>
<pre><code>Error: failure: No more mirrors to try.
</code></pre>
<p>Or error such as this,</p>
<pre><code>GPG key retrieval failed: [Errno 14] problem making ssl connection
</code></pre>
<p>Previously, we used to manually substitute the base url like this (not required anymore),</p>
<pre><code>[google-chrome]
name=google-chrome - 64-bit
baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=http://dl-ssl.google.com/linux/linux_signing_key.pub
</code></pre>
<p>For 32 bit systems contents should be like this,</p>
<pre><code>[google-chrome]
name=google-chrome - 32-bit
baseurl=http://dl.google.com/linux/chrome/rpm/stable/i386
enabled=1
gpgcheck=1
gpgkey=http://dl-ssl.google.com/linux/linux_signing_key.pub
</code></pre>
<p>Beaware that, google stopped updating 32 bit builds for Linux. If you install those versions you won't receive updates.</p>
<h3 id="rhelcent-os-7">RHEL/Cent-OS 7</h3>
<p>RHEL/CentOS 7 have all required packages available for Google Chrome. Hence, a simple,</p>
<pre><code>dnf install google-chrome-stable
</code></pre>
<p>command dies the job. However, if you don't have redhat subscription you might get following error,</p>
<pre><code>libxss.so.1()(64bit) is needed by google-chrome-stable
</code></pre>
<p>If you enable local repository following instruction at <a href="https://fftsys.azurewebsites.net/tech/how-to-setup-rhel-fedora-cent-os-dvd-or-iso-as-local-repository-to-install-packages">fftsys - Setup-RHEL-DVD-ISO-as-local-repository-to-install-packages</a> the same previous dnf command completes without any error.</p>
<h3 id="using-apt-get-on-debian-system-ubuntu-etc">Using apt-get on debian system (ubuntu etc)</h3>
<p>Add signing key</p>
<pre><code>wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
</code></pre>
<p>Add google repository to the sources list,</p>
<pre><code>sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list'
</code></pre>
<p>Update and install chrome,</p>
<pre><code>sudo apt-get update
sudo apt-get install google-chrome-stable
</code></pre>
<p>For Ubuntu's new release 13.04 if you face following error "Error: Dependency is not satisfiable: libudev0(>=147)" use the beta version of chrome which has already resolved it.</p>
<pre><code>sudo apt-get install google-chrome-beta
</code></pre>
<p>Chromium project has details on the issue <a href="https://code.google.com/p/chromium/issues/detail?id=226002">here</a>.</p>
<h3 id="chrome-on-rhel-6-or-earlier">Chrome on RHEL 6 or Earlier</h3>
<p>With RHEL 6 you will run into issues while installing google-chrome. Officially, Google Chrome is not supported on RHEL 6 or earlier since Google Chrome 28. If you are okay with experimental third party script to install google chrome you can follow <a href="http://tecadmin.net/install-google-chrome-in-centos-rhel-and-fedora/#">tecadmin's article</a>. You can install chromium as an alternative. <a href="http://www.if-not-true-then-false.com/">If Not True Then False</a> provides instructions <a href="http://www.if-not-true-then-false.com/2013/install-chromium-on-centos-red-hat-rhel/">if-not-true-then-false's blog - how to install chromium on rhel</a>. If an updated firefox does the job for you in RHEL old OSs in that case you can try <a href="http://rpms.famillecollet.com/">remi repository</a> to update firefox. Check <a href="http://blog.famillecollet.com/pages/Config-en">remi famillecollet's site</a> for info, tecmint also has an article <a href="http://www.tecmint.com/install-firefox-in-rhelcentos-6-3-fedora-17-16/">Installing or Updating Firefox 30 using Remi</a>. If you hate 3rd parties you can simply download the archive from firefox's site, extract it and run (possibly add few links such as in /usr/bin for convenience)</p>
<h3 id="installing-using-direct-full-package">Installing using direct full package</h3>
<p>Download google chrome linux package first from <a href="https://www.google.com/intl/en/chrome/browser/">Chrome's page</a>. Apply this command in the directory where you downloaded <a href="https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm">the file</a>,</p>
<pre><code>sudo dnf localinstall google-chrome-stable_current_x86_64.rpm
</code></pre>
<p>If you want to install the package manually the command will be like this:</p>
<pre><code>sudo dpkg -i google-chrome-stable_current_x86_64.deb
</code></pre>
<h4 id="references">References</h4>
<ol>
<li><a href="https://www.if-not-true-then-false.com/2010/install-google-chrome-with-dnf-on-fedora-red-hat-rhel/">Install Google Chrome on Fedora 17/16, CentOS/Red Hat (RHEL) 6.3</a></li>
</ol>
<p><strong>Commit history</strong></p>
<ol>
<li>update fedora 34-35 - Oct 26, 2021</li>
<li>update fedora section - Dec 19, 2016</li>
<li>update - June 29, 2014</li>
</ol>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/solana-cli
Creating Token, NFT using Solana
2021-10-24T00:00:00Z
<p>Using the Token Program we are able to create fungible and non-fungible tokens.</p>
<h3 id="pre-requisites">Pre-requisites</h3>
<p>We need the token program to be able to accomplish those. We follow official documentation: <a href="https://spl.solana.com/token">SPL Solana Token</a>. We need a Linux Machine or VM with about 16GB or more main memory. Free tier aws linux vm doesn't work.</p>
<ul>
<li><p>Install Rust</p>
<pre><code>curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
</code></pre>
</li>
<li><p>Install Solana CLI</p>
</li>
</ul>
<p>As per <a href="https://docs.solana.com/cli/install-solana-cli-tools">solana docs - install-solana-cli-tools</a> we install solana cli and export its installation location into <code>PATH</code> variable.</p>
<pre><code>sh -c "$(curl -sSfL https://release.solana.com/v1.8.1/install)"
export PATH="/home/atiq/.local/share/solana/install/active_release/bin:$PATH"
</code></pre>
<p>Install required packages for building <code>spl-token-cli</code>,</p>
<pre><code>sudo dnf install openssl-devel --assumeyes
sudo dnf install libudev-devel --assumeyes
</code></pre>
<p>Finally, we install the token library program,</p>
<pre><code>cargo install spl-token-cli
</code></pre>
<p>aws free tier linux VM usually hit following OOM error,</p>
<pre><code>could not compile libsecp256k1 signal: 9, SIGKILL: kill
</code></pre>
<p>Once the build is successful, we check config,</p>
<pre><code>$ solana config get
Config File: /home/atiq/.config/solana/cli/config.yml
RPC URL: https://api.mainnet-beta.solana.com
WebSocket URL: wss://api.mainnet-beta.solana.com/ (computed)
Keypair Path: /home/atiq/.config/solana/id.json
Commitment: confirmed
</code></pre>
<p>By default, RPC is set to mainnet. Let's change it to dev so that we can do some interesting experiments.</p>
<pre><code>$ solana config set --url https://api.devnet.solana.com
Config File: /home/atiq/.config/solana/cli/config.yml
RPC URL: https://api.devnet.solana.com
WebSocket URL: wss://api.devnet.solana.com/ (computed)
Keypair Path: /home/atiq/.config/solana/id.json
Commitment: confirmed
</code></pre>
<p>To get keypair let's create a FileSystem Wallet.</p>
<h2 id="creating-file-system-wallet">Creating File System Wallet</h2>
<p>main reference: <a href="https://docs.solana.com/wallet-guide/file-system-wallet">https://docs.solana.com/wallet-guide/file-system-wallet</a></p>
<p>It is insecure because the keypair files are unencrypted.</p>
<p>Let's create key pair,</p>
<pre><code>$ mkdir ~/solana-wallet
$ solana-keygen new --outfile ~/solana-wallet/keypair.json
Generating a new keypair
For added security, enter a BIP39 passphrase
NOTE! This passphrase improves security of the recovery seed phrase NOT the
keypair file itself, which is stored as insecure plain text
BIP39 Passphrase (empty for none):
Wrote new keypair to /home/atiq/solana-wallet/keypair.json
==============================================================================
pubkey: 5cESBj8D4d6heCiYTKxJSs5Adtbf9rsFedVoZJnRRM7c
==============================================================================
Save this seed phrase and your BIP39 passphrase to recover your new keypair:
key battle mystery control bonus manual thought jazz kidney slam plastic token
==============================================================================
</code></pre>
<p>Verify, just in case,</p>
<pre><code>solana-keygen verify 5cESBj8D4d6heCiYTKxJSs5Adtbf9rsFedVoZJnRRM7c ~/solana-wallet/keypair.json
</code></pre>
<h2 id="creating-tokens">Creating Tokens</h2>
<p>If we have successfully previous sections we can create Tokens now.</p>
<p>Let's set keypair in solana config that we got from file system wallet (previous section),</p>
<pre><code>$ solana config set --keypair $HOME/solana-wallet/keypair.json
Config File: /home/atiq/.config/solana/cli/config.yml
RPC URL: https://api.devnet.solana.com
WebSocket URL: wss://api.devnet.solana.com/ (computed)
Keypair Path: /home/atiq/solana-wallet/keypair.json
Commitment: confirmed
</code></pre>
<p>We need some SOL to perform our next actions.</p>
<pre><code>$ solana airdrop 1
Requesting airdrop of 1 SOL
Signature: 6GVKHvFdBrTC93i4m7Jp2o12VLVsSyJFYHHBvcXBMwSsa8MBz83TCnfDgcijrUHBcuZrsyud4d5oUrBFMfUyt1tM
1 SOL
</code></pre>
<h3 id="creating-fungible-token">Creating Fungible Token</h3>
<p>Let's create token,</p>
<pre><code>spl-token create-token
Creating token GjvWk83m1vKQjmQU2dPnLTRvAKjtAKsAmKKNu7Gyk93
Signature: 2ivgjD3N7xpj2vhDg4YoF3gYMAwkytmbydYeyWVRLzFuUYusUZ4oko6eLTMAws4NKW9YtUuFTcMfEQHYiwgceaCD
</code></pre>
<p>Mint 100 new tokens,</p>
<pre><code>spl-token mint GjvWk83m1vKQjmQU2dPnLTRvAKjtAKsAmKKNu7Gyk93 100
Minting 100 tokens
Token: GjvWk83m1vKQjmQU2dPnLTRvAKjtAKsAmKKNu7Gyk93
Recipient: F8xUCvGx19sZJVy1cMkZgFRMmU7DWCyXTzDebDzDPnwv
Signature: 5i2y9eBAYipJVGsqU6fLR8q61CgJpX1B9iU6BdHh5iPcE9JtefsGPJ7nKQuEjGSqVxqXKHAPC5hPFp7uSzXJpJMn
</code></pre>
<p>Check token supply,</p>
<pre><code>$ spl-token supply GjvWk83m1vKQjmQU2dPnLTRvAKjtAKsAmKKNu7Gyk93
100
</code></pre>
<p>Check token balance,</p>
<pre><code>$ spl-token balance GjvWk83m1vKQjmQU2dPnLTRvAKjtAKsAmKKNu7Gyk93
100
</code></pre>
<p>Accounts,</p>
<pre><code>$ spl-token accounts
Token Balance
---------------------------------------------------------------
GjvWk83m1vKQjmQU2dPnLTRvAKjtAKsAmKKNu7Gyk93 100
</code></pre>
<h3 id="creating-nft">Creating NFT</h3>
<p>[TODO]
will post after fixing AWS RHEL instance..</p>
<h3 id="notes-on-ubuntu-build">Notes on Ubuntu Build</h3>
<p>Requires following,</p>
<pre><code>sudo apt install pkg-config libssl-dev libudev-dev
</code></pre>
<p>Otherwise it complains,</p>
<pre><code>Package openssl was not found in the pkg-config search path.
Perhaps you should add the directory containing `openssl.pc' to the PKG_CONFIG_PATH environment variable
No package 'openssl' found
</code></pre>
<p>A successful build looks like this,</p>
<pre><code>$ tail ~/logs/solana_log.txt
Compiling zstd v0.5.4+zstd.1.4.7
Compiling solana-account-decoder v1.7.11
Compiling solana-transaction-status v1.7.11
Compiling solana-client v1.7.11
Compiling solana-cli-output v1.7.11
Compiling spl-token-cli v2.0.15
Finished release [optimized] target(s) in 6m 47s
Installing /home/atiq/.cargo/bin/spl-token
Installed package `spl-token-cli v2.0.15` (executable `spl-token`)
warning: be sure to add `/home/atiq/.cargo/bin` to your PATH to be able to run the installed binaries
</code></pre>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/net-core-mvchello-entity-framework2021-08
dotnet core Hello World with Entity Framework and Database
2021-08-12T00:00:00Z
<h2 id="razor-pages-app">Razor Pages App</h2>
<p>We follow this primary reference documentation, <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro">MS Docs - aspnet/core/data/ef-rp/intro</a></p>
<pre><code>dotnet new webapp -n P03_ContosoUniversity_RP
cd P03_ContosoUniversity_RP
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design
dotnet add package Microsoft.EntityFrameworkCore.SQLite
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
dotnet aspnet-codegenerator razorpage -m Student -dc ContosoUniversity.Data.SchoolContext `
-udl -outDir Pages\Students --referenceScriptLibraries
</code></pre>
<p>If we are using SQLite database,</p>
<pre><code>dotnet aspnet-codegenerator razorpage -m Student -dc ContosoUniversity.Data.SchoolContext `
-udl -outDir Pages\Students --referenceScriptLibraries -sqlite
</code></pre>
<p>We refactor all <code>P03_ContosoUniversity_RP</code> with <code>ContosoUniversity</code>.</p>
<p>Scaffolding source files have <code>context.Student</code> which is not correct. We update those with <code>context.Students</code>.</p>
<pre><code>dotnet tool update --global dotnet-ef
dotnet ef database update
</code></pre>
<p>EF supports dev environment as well,</p>
<pre><code>dotnet ef database update -- --environment Development
</code></pre>
<p>Finally, we run it,</p>
<pre><code>$Env:ASPNETCORE_ENVIRONMENT = "Development"
dotnet run
</code></pre>
<p>There's some differences with the cu50 sample.</p>
<ul>
<li><p><code>Pages\Students\Index.cshtml.cs</code> is much larger not just one line,</p>
<p>Student = await _context.Students.ToListAsync();</p>
</li>
<li><p>Indentations under <code>Data</code> folder</p>
</li>
<li><p>Code for Error messages, logger etc in a number of files</p>
</li>
<li><p>they have some region definitions with snippet names</p>
</li>
</ul>
<p>In summary, the actual cu50 sample is much more complete than the one we create by following the tutorial.</p>
<p>Some observations,</p>
<ul>
<li>localdb mdf files are usually stored at <code>$HOME</code> (for example, <code>C:\Users\YOUR_NAME</code>)</li>
</ul>
<h3 id="references">References</h3>
<p><strong>Refs on Razor Pages</strong></p>
<ul>
<li><a href="https://docs.microsoft.com/en-us/aspnet/core/razor-pages">Razor Pages</a></li>
<li><a href="https://www.learnrazorpages.com/razor-pages/handler-methods">learnrazorpages - Handler Methods in Razor Pages</a></li>
</ul>
<p><strong>Refs on Entity Framework Performance</strong></p>
<ul>
<li><a href="https://medium.com/swlh/entity-framework-common-performance-mistakes-cdb8861cf0e7">Common performance mistakes</a></li>
</ul>
<p><strong>Example to connect from Visual Studio Server Explorer</strong></p>
<pre><code>Server Name: (LocalDb)\MSSQLLocalDB
DB: CU-1
</code></pre>
<p>ref: 1. <a href="https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string">connection strings example</a>, 2. <a href="https://stackoverflow.com/questions/21563940/how-to-connect-to-localdb-in-visual-studio-server-explorer">how to connect database in visual studio data explorer</a></p>
<h2 id="mvc-app">MVC App</h2>
<p>Steps</p>
<pre><code>dotnet new mvc -n P03_ContosoUniversity
</code></pre>
<p>Replace <code>P03_ContosoUniversity</code> with 'Contoso University'.</p>
<pre><code>dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
</code></pre>
<p>Primary reference documentation, <a href="https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/intro">MS Docs - aspnet/core/data/ef-mvc/intro</a></p>
<p>We add default connection in <code>appsettings.Development.json</code>. We pretty much follow the steps in tutorial and able to produce working version. Only, using VS Code instead of Visual Studio Pro is bit of work since all CLI commands are not provided and we need to repro them, especially scaffolding ones.</p>
<h2 id="razor-pages-app-net-core">Razor Pages App (net core)</h2>
<p>This is an experiment to run the EF Core Razor App with .net core,</p>
<p>We update net framework target in <code>.csproj</code> file.</p>
<p>We add following nuget packages,</p>
<pre><code>dotnet new webapp -n P03_ContosoUniversity_netcore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SQLite
</code></pre>
<p>We add all the scaffolding files from previous project (above) that targets .net6</p>
<p>We end up finding that the following method calls:</p>
<pre><code>// in ConfigureServices
// services.AddDatabaseDeveloperPageExceptionFilter();
// in Configure
// app.UseMigrationsEndPoint();
</code></pre>
<p>require <code>Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore</code> package,</p>
<pre><code>dotnet add package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
Determining projects to restore...
Writing C:\Users\atiq\AppData\Local\Temp\tmp6CF5.tmp
info : Adding PackageReference for package 'Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore' into project 'D:\Code\CS\P03_ContosoUniversity_netcore\P03_ContosoUniversity_netcore.csproj'.
info : GET https://api.nuget.org/v3/registration5-gz-semver2/microsoft.aspnetcore.diagnostics.entityframeworkcore/index.json
info : OK https://api.nuget.org/v3/registration5-gz-semver2/microsoft.aspnetcore.diagnostics.entityframeworkcore/index.json 419ms
info : Restoring packages for D:\Code\CS\P03_ContosoUniversity_netcore\P03_ContosoUniversity_netcore.csproj...
error: NU1202: Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 5.0.9 is not compatible with netcoreapp3.1 (.NETCoreApp,Version=v3.1). Package Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore 5.0.9 supports: net5.0 (.NETCoreApp,Version=v5.0)
error: Package 'Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore' is incompatible with 'all' frameworks in project 'D:\Code\CS\P03_ContosoUniversity_netcore\P03_ContosoUniversity_netcore.csproj'
</code></pre>
<p>Also, the old version (3.1.18 supports .net core) of <code>Diagnostics.EntityFrameworkCore</code> doesn't have the definitions mentioned above.</p>
<p>Conclusion: since some of the packages i.e., <code>Diagnostics.EntityFrameworkCore</code> don't target .net core and only targets newer versions of net framework, for example, .net 6. We cannot run the examples from official tutorial that uses EF Core or Diagnostics (may be Logging package as well).</p>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/shells/powershell
Powershell Useful Commands
2021-03-19T00:00:00Z
<p><em>This article mostly applies to Powershell version 6 or later (formerly known as Powershell Core). Check edition via Powershell variable: <code>$PSEdition</code> (should show core for modern powershell)</em></p>
<p>More cmdlets are on the other article: <code>powershell-cmdlets</code></p>
<h3 id="initialization-of-shell">Initialization of Shell</h3>
<p><em>This section is for my personalized shell; please feel free to skip it.</em></p>
<p>Initiate a shell using a specified init script,</p>
<pre><code>pwsh -NoExit D:\pwsh\Init.ps1
</code></pre>
<p>For shells with specialized purposes, we have,</p>
<pre><code>New-Shell.ps1 -Type Python
</code></pre>
<p>to support Machine Learning and Data Science stack.</p>
<p>Or, for frontend stack,</p>
<pre><code>New-Shell.ps1 -Type Node
</code></pre>
<h3 id="new-to-powershell">New to Powershell?</h3>
<ul>
<li><code>Clear-Host</code> is equivalent to cls</li>
<li><code>Get-Location</code> is alias to <code>pwd</code></li>
</ul>
<p>ls, cat, popd, pushd etc are supported through aliases.</p>
<p>Write-Host is equivalent to echo. For example,</p>
<pre><code>echo 'hello'
</code></pre>
<p><code>ps</code> is equivalent to Get-Process or to List processes or doing <code>tasklist</code>.
Stop-Proccess instead of taskkill</p>
<p>Example of starting Powershell with an initiazation script or calling a script with an arg,</p>
<pre><code>Start-Process pwsh -ArgumentList '-NoExit', 'Init-App.ps1 foo' -ErrorAction 'stop'
</code></pre>
<p>above, <code>foo</code> is argument.</p>
<p>Split string based on delimeter,</p>
<pre><code>$Env:Path –Split ';'
</code></pre>
<p>Access current user's Path variable on the system,</p>
<pre><code class="language-powershell">(Get-ItemPropertyValue -Path HKCU:\Environment -Name Path) -Split(';')
</code></pre>
<h3 id="file-system-management">File System Management</h3>
<p>Filter files containing name pattern,</p>
<pre><code>Get-ChildItem -Filter '*word*'
</code></pre>
<p>Create directory,</p>
<pre><code>New-Item D:\work\git -Type Directory
</code></pre>
<p>Create file (alternative of Unix cmd, <code>touch</code>),</p>
<pre><code>New-Item C:\scripts\new_file.txt -Type File
</code></pre>
<p>Show files in order of modified time,</p>
<pre><code>$ Get-ChildItem -Path C:\windows\CPE\Chef\outputs | Where-Object { -not $_.PsIsContainer } |
Sort-Object LastWriteTime -Descending | Select-Object -first 10
</code></pre>
<p>List files in order of size,</p>
<pre><code>$ gci 'D:\Movies\pq\movies' | Sort-Object Length -Descending
</code></pre>
<p>List items in order of last modified time</p>
<pre><code>$ gci E:\Media\upload | Sort-Object LastWriteTime -Descending
</code></pre>
<h3 id="network-connections">Network Connections</h3>
<p>Ping hosts,</p>
<pre><code>Test-Connection -Count 64 google.com
Test-Connection -Count 1024 google.com
</code></pre>
<p>host <code>bing.com</code> does not reply to ICMP requests anymore, hence it's not worth trying <code>Test-Connection bing.com</code>.</p>
<p>if help modules are outdated this updates it,</p>
<pre><code>Update-Help
</code></pre>
<p>More network related cmdlets or commands are at <a href="https://note.iqubit.xyz/network-wifi-cmd">wifi cmd article</a></p>
<h3 id="miscellaneous">Miscellaneous</h3>
<p><strong>Processes</strong></p>
<p>Get list of running processes (unique), show full path,</p>
<pre><code>Get-Process | Select-Object -Unique Path
</code></pre>
<p>When Windows Explorer or taskbar has trouble,</p>
<pre><code>Stop-Process -Name Explorer
</code></pre>
<p>Find difference between 2 text files,</p>
<pre><code>Compare-Object (get-content one.txt) (get-content two.txt)
</code></pre>
<p><strong>Scheduled Tasks</strong></p>
<pre><code>Get-ScheduledTask -TaskName *chef*
Get-ScheduledTask -TaskPath \
Get-ScheduledTask -TaskPath \MSIT\
</code></pre>
<p>Rename Machine,</p>
<pre><code>Rename-Computer -NewName JohnPC -Restart
</code></pre>
<p>Event Log,</p>
<pre><code>Show-EventLog
</code></pre>
<p>Show console host info,</p>
<pre><code>$ Get-Host
Name : ConsoleHost
Version : 6.2.3
InstanceId : cddce532-924c-4a66-a671-bbea53caf430
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
</code></pre>
<p>How to uninstall store application i.e., skype</p>
<pre><code>Get-AppxPackage Microsoft.SkypeApp | Remove-AppxPackage
</code></pre>
<p><code>WmiObject</code> example can be found on post: <a href="https://note.iqubit.xyz/powershell-legacy">powershell-legacy</a></p>
<h3 id="type-conversion">Type Conversion</h3>
<p>This part also demonstrates how to use some datatype libraries in commands.</p>
<p>Example 1, how do we find ascii number of a bunch of characters?</p>
<pre><code>$ [int[]][char[]] 'abcd'
97
98
99
100
</code></pre>
<p>Additionally, to find ascii number of single char,</p>
<pre><code class="language-powershell">$ [int][char] 'z'
122
</code></pre>
<p>Moroever we can call <code>Array.Sort</code> in following way,</p>
<pre><code class="language-powershell">$a = [int[]] @(9,5)
[Array]::Sort($a)
</code></pre>
<p>Because these literatls i.e., 'xxx' in powershell is considered as string literal like python.</p>
<pre><code>$ 'z'.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
</code></pre>
<h4 id="mathematics-library">Mathematics Library</h4>
<p>Example usage of .net math library, using old friend the <code>power</code> method,</p>
<pre><code class="language-powershell">[Math]::Pow(2,13)
</code></pre>
<p>Or finding a square root,</p>
<pre><code class="language-powershell">[Math]::Sqrt(9)
</code></pre>
<h4 id="string-helpers">String Helpers</h4>
<p>String Split,</p>
<pre><code class="language-powershell">$Env:Path –split ';'
</code></pre>
<p><code>Null</code> or empty string related examples, where <code>$ConfigName</code> is an example variable,</p>
<pre><code class="language-powershell">[string]::IsNullOrEmpty($ConfigName)
[string]::IsEmpty($ConfigName)
[string]::Empty($ConfigName)
</code></pre>
<p>Substring example,</p>
<pre><code class="language-powershell">if ($loc.EndsWith("\")) {
return $loc.Substring(0, $loc.Length-1)
}
</code></pre>
<p>which is fine to be replaced with,</p>
<pre><code class="language-powershell">if (($lastindex = [int] $loc.lastindexof('\')) -ne -1) {
return $loc.Substring(0, $lastindex)
}
</code></pre>
<h3 id="show-os-version">Show OS Version</h3>
<p>Using Net Framework Library,</p>
<pre><code>$ [Environment]::OSVersion
Platform ServicePack Version VersionString
-------- ----------- ------- -------------
Win32NT 10.0.22621.0 Microsoft Windows NT 10.0.22621.0
$ [Environment]::OSVersion.Version
Major Minor Build Revision
----- ----- ----- --------
10 0 22621 0
</code></pre>
<p>Additionally, we can do this inspecting <code>hal.dll</code>,</p>
<pre><code>$ [Version](Get-ItemProperty -Path "$($Env:Windir)\System32\hal.dll" -ErrorAction SilentlyContinue).`
VersionInfo.FileVersion.Split()[0]
Major Minor Build Revision
----- ----- ----- --------
10 0 22621 819
</code></pre>
<h3 id="shell-variables">Shell Variables</h3>
<p>To delete all contents of USB drive (this is dangerous as it deletea all contents and files/dirs from a drive),</p>
<pre><code>Remove-Item -force l:\*
</code></pre>
<p>On Powershell,</p>
<pre><code>$ $Profile
DocumentsDir\PowerShell\Microsoft.PowerShell_profile.ps1
</code></pre>
<p>On Legacy Powershell (the classic one that comes with Windows),</p>
<pre><code>$ $Profile
DocumentsDir\\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
</code></pre>
<p>Access history file,</p>
<pre><code>$ (Get-PSReadlineOption).HistorySavePath
</code></pre>
<h3 id="invoking-legacy-powershell-features-from-powershell">Invoking Legacy Powershell Features from Powershell</h3>
<p>Say you have a script named <code>Bluetooth.ps1</code> that uses Windows features i.e., COM. We invoke old Powershell to execute those.</p>
<pre><code>Powershell -NoProfile -File Bluetooth.ps1 On
</code></pre>
<h3 id="setting-permission-for-running-powershell-on-a-new-machine">Setting permission for running Powershell on a new machine</h3>
<p>By default, there are lot of warnings and requests for permission. To make things easier, we relax the permission by setting execution policy.
Set execution policy for current user. <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy">ref, MSFT - Security Set Execution Policy</a>,</p>
<pre><code>Set-Executionpolicy Unrestricted -scope CurrentUser
</code></pre>
<p>In old days, that used to be enough. If you get following,</p>
<pre><code>PowerShell 7.3.0 https://aka.ms/pscore6-docs
Security warning
Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. If you trust this script, use the Unblock-File cmdlet to allow the script to run without this warning
message. Do you want to run D:\Doc\PowerShell\Microsoft.PowerShell_profile.ps1?
[D] Do not run [R] Run once [S] Suspend [?] Help (default is "D"): R
Loading personal and system profiles took 4862ms.
</code></pre>
<p>Try unblocking,</p>
<pre><code>Unblock-File D:\Doc\PowerShell\Microsoft.PowerShell_profile.ps1
</code></pre>
<p>In worst situation, in corporate environments if that still does not work,</p>
<pre><code>File D:\Doc\PowerShell\Microsoft.PowerShell_profile.ps1 cannot be loaded. The file D:\Doc\PowerShell\Microsoft.PowerShell_profile.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:3
+ . 'D:\Doc\PowerShell\Microsoft.PowerShell_profile.ps1'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (:) [], PSSecurityException
+ FullyQualifiedErrorId : UnauthorizedAccess
</code></pre>
<p>we can apply bypass changing Registry,</p>
<pre><code>Set-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell -Name ExecutionPolicy -Value ByPass
</code></pre>
<p>In environments like school computers that are running SINC Site, bypassing in Process scope can be useful,</p>
<pre><code>Set-ExecutionPolicy Bypass -Scope Process
</code></pre>
<h3 id="variables-powershell-vs-legacy-powershell">Variables Powershell vs Legacy Powershell</h3>
<p>Following are new Powershell variables,</p>
<pre><code>EnabledExperimentalFeatures {}
IsCoreCLR True
IsLinux False
IsMacOS False
isSinglePS True
IsWindows True
LASTEXITCODE 0
psConsoleType
</code></pre>
<p>The shell modified following previously known Powershell variables,</p>
<pre><code>OutputEncoding
PROFILE
PSCommandPath
PSEdition
PSHOME
</code></pre>
<p><em>TODO: check pwsh 7</em></p>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/dennis-ritchie-c
Dennis Ritchie - The C Programming Language
2021-03-19T00:00:00Z
<h3 id="format-specifiers">Format Specifiers</h3>
<p>Right justification example,</p>
<pre><code>printf("%3d %6d\n", fahr, celsius);
</code></pre>
<h3 id="automatic-type-casting">Automatic Type Casting</h3>
<p>If an arithmetic operator has integer operands, an integer operation is performed. If an arithmetic operator has one floating-point operand and one integer operand, however, the integer will be converted to floating point before the operation is done. If we had written (fahr-32), the 32 would be automatically converted to floating point. Nevertheless, writing floating-point constants with explicit decimal points even when they have integral values emphasizes their floating-point nature for human readers.</p>
<p>Among others, <code>printf</code> recognizes,</p>
<ul>
<li>%o for octal</li>
<li>%x for hexadecimal</li>
<li>%c for character</li>
<li>%s for character string and,</li>
<li>%% for itself</li>
</ul>
<h3 id="getchar-and-putchar">getchar and putchar</h3>
<p>The problem is distinguishing the end of input from valid data. The solution is that getchar returns a distinctive value when there is no more input, a value that cannot be confused with any real character. This value is called EOF, for "end of file". We must declare c to be a type big enough to hold any value that getchar returns. We can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we use int.</p>
<p>EOF is an integer defined in <code><stdio.h></code>, but the specific numeric value doesn't matter as long as it is not the same as any char value. By using the symbolic constant, we are assured that nothing in the program depends on the specific numeric value.</p>
<pre><code>#include <stdio.h>
/* copy input to output; 2nd version */
main() {
int c;
while ((c = getchar()) != EOF)
putchar(c);
}
</code></pre>
<h3 id="in-and-out-modifiers">IN and OUT Modifiers</h3>
<p>We prefer the symbolic constants <code>IN</code> and <code>OUT</code> to the literal values 1 and 0 because they make the program more readable.</p>
<pre><code>#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
main() {
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
</code></pre>
<p>In a program as tiny as this, it makes little difference, but in larger programs, the increase in clarity is well worth the modest extra effort to write it this way from the beginning. You'll also find that it's easier to make extensive changes in programs where magic numbers appear only as symbolic constants.</p>
<h3 id="arguments-and-parameters">Arguments and parameters</h3>
<p>The function power is called twice by main, in the line</p>
<pre><code>printf("%d %d %d\n", i, power(2,i), power(-3,i));
</code></pre>
<p>Each call passes two arguments to power, which each time returns an integer to be formatted and printed. In an expression, power(2,i) is an integer just as 2 and i are. (Not all functions produce an integer value; we will take this up in Chapter 4.)</p>
<p>The first line of power itself,</p>
<pre><code>int power(int base, int n)
</code></pre>
<p>declares the parameter types and names, and the type of the result that the function returns. The names used by power for its parameters are local to power, and are not visible to any other function: other routines can use the same names without conflict. This is also true of the variables i and p: the i in power is unrelated to the i in main.</p>
<p><em>We will generally use <code>parameter</code> for a variable named in the parenthesized list in a function.</em></p>
<h3 id="argument-passing-call-by-value">Argument Passing: Call by Value</h3>
<p>In C, all function arguments are passed "by value". This means that the called function is given the values of its arguments in temporary variables rather than the originals. This leads to some different properties than are seen with "call by reference" languages like Fortran or with var parameters in Pascal, in which the called routine has access to the original argument, not a local copy.</p>
<h3 id="constant-expressions">Constant Expressions</h3>
<p>A <em>constant expression</em> is an expression that involves only constants. Such expressions may be evaluated at during compilation rather than run-time, and accordingly may be used in any place that a constant can occur, as in</p>
<pre><code>#define MAXLINE 1000
char line[MAXLINE+1];
</code></pre>
<p>Or,</p>
<pre><code>#define LEAP 1 /* in leap years */
int days[31+28+LEAP+31+30+31+30+31+31+30+31+30+31];
</code></pre>
<h3 id="string-constants">String Constants</h3>
<p>String constants can be concatenated at compile time:</p>
<pre><code>"hello, " "world"
</code></pre>
<p>is equivalent to</p>
<pre><code>"hello, world"
</code></pre>
<p>This is useful for splitting up long strings across several source lines.</p>
<h3 id="enumeration">Enumeration</h3>
<p>An enumeration is a list of constant integer values, as in</p>
<pre><code>enum boolean { NO, YES };
</code></pre>
<p>The first name in an enum has value 0, the next 1, and so on, unless explicit values are specified. If not all values are specified, unspecified values continue the progression from the last specified value, as the second of these examples:</p>
<pre><code>enum escapes { BELL = '\a', BACKSPACE = '\b', TAB = '\t',
NEWLINE = '\n', VTAB = '\v', RETURN = '\r' };
enum months { JAN = 1, FEB, MAR, APR, MAY, JUN,
JUL, AUG, SEP, OCT, NOV, DEC }; /* FEB = 2, MAR = 3, etc. */
</code></pre>
<p>Names in different enumerations must be distinct.</p>
<p><em>Values need not be distinct in the same enumeration.</em></p>
<h3 id="variable-initialization">Variable Initialization</h3>
<p>External and static variables are initialized to zero by default. Automatic variables for which is no explicit initializer have undefined (i.e., garbage) values.</p>
<h3 id="precedence">Precedence</h3>
<p>The precedence of <code>&&</code> is higher than that of ||, and both are lower than relational and equality operators, so expressions like</p>
<pre><code>i < lim-1 && (c=getchar()) != '\n' && c != EOF
</code></pre>
<p>need no extra parentheses. But since the precedence of != is higher than assignment, parentheses are needed in</p>
<pre><code>(c=getchar()) != '\n'
</code></pre>
<p>to achieve the desired result of assignment to c and then comparison with '\n'.</p>
<p>By definition, the numeric value of a relational or logical expression is 1 if the relation is true, and 0 if the relation is false.</p>
<h3 id="type-conversions">Type Conversions</h3>
<p>Expressions that might lose information, like assigning a longer integer type to a shorter, or a floating-point type to an integer, may draw a warning, but they are not illegal.</p>
<h3 id="bitwise-operators">Bitwise Operators</h3>
<p>The bitwise AND operator & is often used to mask off some set of bits, for example</p>
<pre><code>n = n & 0177;
</code></pre>
<p>sets to zero all but the low-order 7 bits of n.</p>
<p>The bitwise OR operator | is used to turn bits on:</p>
<pre><code>x = x | SET\_ON;
</code></pre>
<p>sets to one in x the bits that are set to one in SET_ON.</p>
<p>The bitwise exclusive OR operator ^ sets a one in each bit position where its operands have different bits, and zero where they are the same.</p>
<p>The unary operator ~ yields the one's complement of an integer; that is, it converts each 1-bit into a 0-bit and vice versa. For example</p>
<pre><code>x = x & ~077
</code></pre>
<p>sets the last six bits of x to zero. Note that <code>x & ~077</code> is independent of word length, and is thus preferable to, for example, <code>x & 0177700</code>, which assumes that x is a 16-bit quantity. The portable form involves no extra cost, since <code>~077</code> is a constant expression that can be evaluated at compile time.</p>
<h3 id="precedence-of-bitwise-operators">Precedence of bitwise operators</h3>
<p>Note that the precedence of the bitwise operators &, ^, and | falls below == and !=. This implies that bit-testing expressions like</p>
<pre><code>if ((x & MASK) == 0) ...
</code></pre>
<p>must be fully parenthesized to give proper results.</p>
<h3 id="switch-statement">Switch Statement</h3>
<p><em>Each case is labeled by one or more integer-valued constants or constant expressions.</em> If a case matches the expression value, execution starts at that case. All case expressions must be different. The case labeled default is executed if none of the other cases are satisfied. A default is optional; if it isn't there and if none of the cases match, no action at all takes place. Cases and the default clause can occur in any order.</p>
<pre><code>switch (expression) {
case const-expr: statements
case const-expr: statements
default: statements
}
</code></pre>
<p>The break statement causes an immediate exit from the switch. Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape. break and return are the most common ways to leave a switch.</p>
<p><em>The commas that separate function arguments, variables in declarations, etc., are not comma operators, and do not guarantee left to right evaluation.</em></p>
<p>Because the else part of an if-else is optional, there is an ambiguity when an else if omitted from a nested if sequence. This is resolved by associating the else with the closest previous else-less if. For example, in</p>
<pre><code>if (n > 0)
if (a > b)
z = a;
else
z = b;
</code></pre>
<p>The else goes to the inner if, as we have shown by indentation. If that isn't what you want, braces must be used to force the proper association:</p>
<pre><code>if (n > 0) {
if (a > b)
z = a;
}
else
z = b;
</code></pre>
<h3 id="reverse-number-example">Reverse Number Example</h3>
<p>I tried a usual implementation of reverse number as I was learning,</p>
<pre><code>#include <stdio.h>
main() {
int n;
printf("Enter number to reverse: ");
scanf("%d", &n);
printf("Reverse of that number is %d\n", ReverseNum(n));
}
int ReverseNum(int a) {
int res = 0;
while (a) {
res = res * 10 + a % 10;
a /= 10;
}
return res;
}
</code></pre>
<p><em>Recursive version</em></p>
<pre><code>#include <stdio.h>
main() {
int n;
printf("Enter number to reverse: ");
scanf("%d", &n);
printf("Reverse of that number is %d\n", ReverseNum(n, 0));
}
int ReverseNum(int a, int res) {
if (a == 0)
return res;
res = ReverseNum(a/10, res) * 10 + a % 10;
return res;
}
</code></pre>
Head's in the cloud, a Qubit blog
https://note.iqubit.xyz/posts/shells/powershell-cmdlets
Powershell Cmdlets
2020-12-10T00:00:00Z
<p><em>This article applies to Powershell version 6 or later (formerly also known as Powershell Core).</em></p>
<h3 id="start-process">Start-Process</h3>
<p>Here are some handy cmds (Application Run Examples),</p>
<p><code>Start</code> is an alias of <code>Start-Process</code></p>
<pre><code>Start Code --diff, a.md, b.md
Start Signal
</code></pre>
<p>Syntax for AppEx/ MS Store Apps,</p>
<pre><code>Start Microsoft-Edge:https://google.com
Start MS-Paint:
</code></pre>
<p>For passing arguments to an application we can either add it right after the app name with a seperating space,</p>
<pre><code>Start Notepad++ file_path
</code></pre>
<p>Or, specify it in <code>ArgumentList</code>,</p>
<pre><code>Start Notepad++ -ArgumentList file_path
</code></pre>
<p>However, it's tricky if passed argument for example, <code>file_path</code> above contains a space character.</p>
<p>To make it work, we need to double quote them <a href="https://stackoverflow.com/questions/22840882/powershell-opening-file-path-with-spaces">ref, SO - pwsh opening file path with spaces</a>,</p>
<pre><code>Start Notepad++ -ArgumentList "`"D:\Cool Soft\my awesome file.txt`""
</code></pre>
<h3 id="process-management">Process Management</h3>
<p>A simple run gives a technical summary of the process</p>
<pre><code>$ Get-Process pwsh
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
80 117.16 170.47 25.61 21628 1 pwsh
</code></pre>
<ul>
<li>annoying what the powershell team chose by default on the implementation</li>
</ul>
<p>To get number of instances of a process</p>
<pre><code>function GetProcessInstanceNumber([string] $process) {
@(Get-Process $process -ErrorAction 0).Count
}
</code></pre>
<p>Get top 30 processes sorted by CPU usage,</p>
<pre><code>Get-Process | Sort-Object CPU -Descending | Select -First 30 -Property ID,ProcessName,CPU,WorkingSet64 | Format-table -autosize
</code></pre>
<p>Same thing with default columns,</p>
<pre><code>Get-Process | Sort-Object -Property cpu -Descending | Select -First 30
</code></pre>
<h3 id="service-management">Service Management</h3>
<p>Get list of services currently running,</p>
<pre><code>Get-Service | Where-Object {$_.Status -eq "Running"}
</code></pre>
<p>Start a service,</p>
<pre><code>Start-Service -Name VPNAgent
</code></pre>
<p>Stop one,</p>
<pre><code>Stop-Service -Name VPNAgent
</code></pre>
<p>Useful for bluetooth service,</p>
<pre><code>Start-Service bthserv
Stop-Service -Force bthserv
</code></pre>
<h3 id="network-administration">Network Administration</h3>
<p><em>To view information on the currently connect WiFi network</em></p>
<pre><code>$ Get-NetConnectionProfile
Name : @Coffeebar Guest WiFi
InterfaceAlias : Wi-Fi
InterfaceIndex : 16
NetworkCategory : Public
DomainAuthenticationKind : None
IPv4Connectivity : Internet
IPv6Connectivity : NoTraffic
</code></pre>
<p><strong>Show Network Interfaces Information</strong>
Using powershell cmdlet, we can view information on all network interfaces in the system,</p>
<pre><code>$ Get-NetAdapter
Name InterfaceDescription ifIndex Status MacAddress LinkSpeed
---- -------------------- ------- ------ ---------- ---------
Ethernet 2 Cisco AnyConnect Secure Mobility Clien… 14 Not Present 00-05-9A-3C-7A-00 0 bps
Wi-Fi Intel(R) Wi-Fi 6 AX200 160MHz 10 Up 04-ED-33-4C-9E-1F 400 Mbps
vEthernet (Default Switc… Hyper-V Virtual Ethernet Adapter 23 Up 00-15-5D-5F-1A-CB 10 Gbps
</code></pre>
<p>To view information on the WiFi network interface,</p>
<pre><code>$ Get-NetAdapter -Name Wi-Fi
Name InterfaceDescription ifIndex Status MacAddress LinkSpeed
---- -------------------- ------- ------ ---------- ---------
Wi-Fi Intel(R) Wi-Fi 6 AX200 160MHz 10 Up 04-ED-33-4C-9E-1F 400 Mbps
</code></pre>
<p>Show cmdlets related to net adapter,</p>
<pre><code>$ gcm -Noun netadapter | select name, modulename
Name ModuleName
---- ----------
Disable-NetAdapter NetAdapter
Enable-NetAdapter NetAdapter
Get-NetAdapter NetAdapter
Rename-NetAdapter NetAdapter
Restart-NetAdapter NetAdapter
Set-NetAdapter NetAdapter
</code></pre>
<p>Additionally, now, we have cmdlet to show IP Address info without sing <code>netsh</code>,</p>
<pre><code>$ Get-NetIPAddress
IPAddress : fe80::f384:25fc:f7ba:30b%7
InterfaceIndex : 7
InterfaceAlias : Bluetooth Network Connection
AddressFamily : IPv6
Type : Unicast
PrefixLength : 64
PrefixOrigin : WellKnown
SuffixOrigin : Link
AddressState : Deprecated
ValidLifetime : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource : False
PolicyStore : ActiveStore
IPAddress : fe80::99c3:e3a9:7b86:99fe%11
InterfaceIndex : 11
InterfaceAlias : Local Area Connection* 10
AddressFamily : IPv6
Type : Unicast
PrefixLength : 64
PrefixOrigin : WellKnown
SuffixOrigin : Link
AddressState : Deprecated
ValidLifetime : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource : False
PolicyStore : ActiveStore
IPAddress : fe80::604:e257:2351:2768%17
InterfaceIndex : 17
InterfaceAlias : Local Area Connection* 9
AddressFamily : IPv6
Type : Unicast
PrefixLength : 64
PrefixOrigin : WellKnown
SuffixOrigin : Link
AddressState : Deprecated
ValidLifetime : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource : False
PolicyStore : ActiveStore
... ...
... ...
IPAddress : 10.55.200.98
InterfaceIndex : 16
InterfaceAlias : Wi-Fi
AddressFamily : IPv4
Type : Unicast
PrefixLength : 8
PrefixOrigin : Dhcp
SuffixOrigin : Dhcp
AddressState : Preferred
ValidLifetime : 20:23:37
PreferredLifetime : 20:23:37
SkipAsSource : False
PolicyStore : ActiveStore
IPAddress : 127.0.0.1
InterfaceIndex : 1
InterfaceAlias : Loopback Pseudo-Interface 1
AddressFamily : IPv4
Type : Unicast
PrefixLength : 8
PrefixOrigin : WellKnown
SuffixOrigin : WellKnown
AddressState : Preferred
ValidLifetime : Infinite ([TimeSpan]::MaxValue)
PreferredLifetime : Infinite ([TimeSpan]::MaxValue)
SkipAsSource : False
PolicyStore : ActiveStore
</code></pre>
Head's in the cloud, a Qubit blog