Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

Mar 15, 2024

AI means everyone can now be a programmer(?)

Is it that easy?

Assuming you are not a developer and want to create an app to take screenshots on macOS.

You started to ask questions to AI and installed developer tools. Now you are ready for development.

  1. Gemini
  2. How to take a screenshot on macos xcode using swift?

    You paste the code to XCode and see an error!

    Ask Gemini to provide another solution.
    The code you provided in swift didn't work. Suggest another swift way to capture a screenshot.

    Gemini gives an apology and suggests another solution.

    Let's see in XCode.

    Can you see a strange code that contains Arabic letters?

    guard let contentFilter = SCC محتوى الشاشة(sharingMode: .none) else { return nil }

    You want to switch to ChatGPT to accomplish this easy task with the same prompt. 👇

  3. ChatGPT
  4. You paste the code provided by ChatGPT. Again, there is a problem in the code!

    context.makeCurrent() didn't work. Is there any other way?

    You pasted this code, and it worked! After a few trials, now think you are a programmer.

    What will you do if you see CGDisplayCreateImage(_:) is deprecated?

    So you keep asking for alternative ways, and you learn that there is a shiny framework named ScreenCaptureKit.

    I recommend trying to ask both Gemini and ChatGPT to take a screenshot using ScreenCaptureKit. I tried, on several attempts, AI suggested wrong code each time.

    Then you will decide how easy programming is!

Nov 14, 2018

Web Api Post Types (C#)

You can find some implementations of Web Api Post types here.
Model

public class Model
{
 public string Name { get; set; }
 public string Id { get; set; }

 public string Save()
 {
  return "Saved";
 }
}

1. Post Raw

Web Api

[HttpPost]
public async Task PostRaw()
{
 string json = await Request.Content.ReadAsStringAsync();

 Model model = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

 return model.Save();
}
Request
POST http://localhost:63693/api/test/PostRaw HTTP/1.1
Content-Type: application/json

{"Id":"1","Name":"Model1"}

2. FromBody

Web Api

[HttpPost]
public string PostFromBody([FromBody]string body)
{
 Model model = Newtonsoft.Json.JsonConvert.DeserializeObject(body);

 return model.Save();
}
Request
Escape json: "{\"Id\":\"1\",\"Name\":\"Model1\"}"
POST http://localhost:63693/api/test/PostModel HTTP/1.1
Content-Type: application/json

"{\"Id\":\"1\",\"Name\":\"Model1\"}"
or
POST http://localhost:63693/api/test/PostFromBody HTTP/1.1
Content-Type: application/x-www-form-urlencoded

%7B%22body%22=%7B%22Id%22%3A%221%22%2C%22Name%22%3A%22Model1%22%7D%7D

3. Class parameter

Web Api

[HttpPost]
public string PostModel(Model model)
{
 return model.Save();
}
Request
POST http://localhost:63693/api/test/PostModel HTTP/1.1
Content-Type: application/json

{"Id":"1","Name":"Model1"}

4. String parameter + Request.Content

Web Api

[HttpPost]
public string PostModelJson(string key)
{
 //You may check key here...

 var contentType = Request.Content.Headers.ContentType.MediaType;
 var body = Request.Content.ReadAsStringAsync().Result;

 Model model = null;

 if (contentType == "application/json")
 {
  model = Newtonsoft.Json.JsonConvert.DeserializeObject(body);

  return model.Save();
 }
 else
  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
Request
POST http://localhost:63693/api/test/PostModelJson?key=1 HTTP/1.1
Content-Type: application/json

{"Id":"1","Name":"Model1"}

5. Post uri parameter

Web Api

[HttpPost]
public string PostModelFromUri([FromUri]Model model)
{
 return model.Save();
}
Request
POST http://localhost:63693/api/test/PostModelFromUri?id=1&name=Model1 HTTP/1.1

6. Multipart Form Data

Web Api

[HttpPost]
public string PostMultipart()
{
 var contentType = Request.Content.Headers.ContentType.MediaType;

 if (contentType == "multipart/form-data")
 {
  var parts = Request.Content.ReadAsMultipartAsync().Result;

  var contents = parts.Contents;
  Model model = new Model();

  foreach (StreamContent item in contents)
  {
   if (item.Headers.ContentDisposition.Name.Trim('"') == "Id")
    model.Id = item.ReadAsStringAsync().Result;
   else if (item.Headers.ContentDisposition.Name.Trim('"') == "Name")
    model.Name = item.ReadAsStringAsync().Result;
  }

  return model.Save();
 }
 else
  throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);            
}
Request
POST http://localhost:63693/api/test/PostMultipart HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryrKvJKnAHtuVvEERM

------WebKitFormBoundaryrKvJKnAHtuVvEERM
Content-Disposition: form-data; name="Id"

1
------WebKitFormBoundaryrKvJKnAHtuVvEERM
Content-Disposition: form-data; name="Name"

Model1
------WebKitFormBoundaryrKvJKnAHtuVvEERM--

Oct 15, 2018

Encryption function (dotnet & nodejs)

Following functions give same result on dotnet and nodejs platforms.
Nodejs uses "crypto-js" package.
Dotnet uses "System.Security.Cryptography" namespace.

Dotnet


void Main()  
 {  
     string clearText = "oktay";  
     Console.WriteLine("clearText: " + clearText);  
     string encrypted = Crypto.EncryptToBase64(clearText);  
     Console.WriteLine("encrypted: " + encrypted);  
 }  
 public static class Crypto  
 {  
   public static string EncryptToBase64(string decryptedText)  
   {  
     byte[] rawSecretKey = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 };  
     string PassPhrase = "passPhrase";  
     MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();  
     byte[] data = Encoding.UTF8.GetBytes(PassPhrase);  
         byte[] passwordKey = x.ComputeHash(data);  
         Console.WriteLine("key: " + BitConverter.ToString(passwordKey).Replace("-", ""));  
         Console.WriteLine("iv : " + BitConverter.ToString(rawSecretKey).Replace("-", ""));  
         RijndaelManaged rijndael = new RijndaelManaged();  
     ICryptoTransform rijndaelEncryptor = rijndael.CreateEncryptor(passwordKey, rawSecretKey);  
     try  
     {  
       byte[] decryptedData = Encoding.UTF8.GetBytes(decryptedText);  
       byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(decryptedData, 0, decryptedData.Length);  
       return Convert.ToBase64String(newClearData, 0, newClearData.Length);  
     }  
     catch (Exception ex)  
     {  
       throw ex;  
     }  
   }  
 }  

Node.js

 
 var CryptoJS = require("crypto-js");  
 function byteArrayToHexString(byteArray) {  
  return Array.prototype.map  
   .call(byteArray, function(byte) {  
    return ("0" + (byte & 0xff).toString(16)).slice(-2);  
   })  
   .join("");  
 }  

 function EncryptToBase64(password) {
  console.log("clearText: " + password); 
  var PassPhrase = "passPhrase";  
  var rawSecretKey = [ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 ];
  
  var myRijndaelKeyBytes = CryptoJS.enc.Utf8.parse(PassPhrase);  
  var myRijndaelKey = CryptoJS.MD5(CryptoJS.enc.Utf8.parse(PassPhrase));  
  console.log("key: " + myRijndaelKey);  
  var myRijndaelIV = byteArrayToHexString(rawSecretKey);  
  var ivCodeWords = CryptoJS.enc.Hex.parse(myRijndaelIV);  
  console.log("iv: " + ivCodeWords);  
  var encrypted = CryptoJS.AES.encrypt(  
   CryptoJS.enc.Utf8.parse(password),  
   myRijndaelKey,  
   {  
    iv: ivCodeWords,  
    mode: CryptoJS.mode.CBC,  
    padding: CryptoJS.pad.Pkcs7  
   }  
  );  
  var base64 = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);  
  console.log("encrypted: " + base64);  
 }  
 EncryptToBase64("oktay");  
 return;  

Result

clearText: oktay
key: C6CEC8C6CAA9A579644664F0575DB2F5
iv : 01010101010101010101010101010101
encrypted: S+6CSoMM6no9atihmfyayQ==

Feb 5, 2018

Python code to exe (Windows)

PyInstaller helps you convert your python code to executable software package.

Our test environment: Windows 7, Python 3.6

Create your python code file (hello.py)
print("Hello World!")
Download PyInstaller via pip
pip install pyinstaller
Run PyInstaller with python code file parameter on console
"C:\Program Files\Python36\Scripts\pyinstaller.exe" hello.py
You will see some commands on the screen. A few seconds later it will finish building. Build time is dependent your code (referenced packages).

Check dist folder for distribution copy of your application (hello.exe)

Size of the folder for hello.py is around 11mb.

I tried also py file with reference of cv2 library. Build time is around 30seconds and folder size becomes 157mb.

Oct 16, 2017

Install opencv package in Python

Opencv is very popular library on all platforms. This article explains how to install opencv package for Python. This will give you a general idea about installing any library in Python environment.

In code samples you will see cv2 library is imported.
import cv2
If you run sample code without installing opencv you will get following error.
Traceback (most recent call last):
  File "pythonface.py", line 2, in
    import cv2
ImportError: No module named cv2

Installing python package from online repository is very easy in python. You can search for a package in PyPI (Python Package Index) interface.

Type opencv to search box in pypi webpage (https://pypi.python.org/pypi)

This will give you a long list which contains your keyword.
List cropped for blog post.

Finding right package may be hard in this list. You can find package names from original sources of specific libraries.

If you click "opencv-python 3.3.0.10" from the list (https://pypi.python.org/pypi/opencv-python/3.3.0.10) you will see installation and usage guide.

On docs.opencv.org you can see library name as opencv-python:
OpenCV-Python is the Python API for OpenCV, combining the best qualities of the OpenCV C++ API and the Python language.
Use following command to install opencv library to your computer from PyPI.
pip install opencv-python
Now you are ready to use opencv functions.

If you can't find opencv-python package in your installation you can download source codes and run commands according to your environment. This link will give you an idea about sequence of this work.