My Tech Scrap
Flipkart.com

Translate

Share |

Tuesday, 16 September 2025

📱 Backing Up My Redmi Phone with PowerShell + ADB: A Journey

Like many of us, I rely heavily on my phone — photos, downloads, documents, and a random mix of files I probably should’ve organized months ago. One day, I decided it was time to back everything up from my Redmi 9 Prime to my PC. I thought: “Easy. Just use PowerShell and Robocopy.”

That’s when reality hit me.


❌ The First Roadblock: MTP Isn’t a Real Drive

When you plug in an Android phone over USB, Windows shows it in This PC as:

This PC\Redmi 9 Prime\Internal shared storage

Looks like a normal path, right? But try to script it and… nope.
MTP (Media Transfer Protocol) isn’t a normal file system, so neither PowerShell’s Get-ChildItem nor robocopy could see it.

I needed a different approach.


🔑 Enter ADB (Android Debug Bridge)

ADB is a developer tool from Google that lets your computer talk directly to your Android device. With it, I could copy files reliably and even automate backups.

Here’s how I set it up:

  1. Downloaded Platform Tools and extracted to C:\platform-tools.

  2. Added that folder to my PATH.

  3. Enabled Developer Options → USB Debugging on my Redmi.

  4. Ran:

adb devices

At first, it showed:

hdshdsdhshd unauthorized

The phone was waiting for me to approve the connection. A quick tap on “Allow USB debugging” fixed it, and finally:

hdshdsdhshd device

Success! 🎉


🛠️ Writing the PowerShell Script

Now I needed a script that would:

  • Copy all internal storage folders.

  • Copy external SD card storage (if present).

  • Log the status of each root folder as COMPLETE or FAILED.

Here’s the final version I came up with:

param( [string]$Destination = "E:\PhoneBackup", [string]$LogFile = "E:\PhoneBackup\BackupLog.txt" ) if (!(Test-Path $Destination)) { New-Item -ItemType Directory -Path $Destination -Force | Out-Null } "Backup started: $(Get-Date)" | Out-File -FilePath $LogFile -Encoding UTF8 # -------- INTERNAL STORAGE (/sdcard) -------- $internalFolders = adb shell "ls /sdcard/" | ForEach-Object { $_.Trim() } foreach ($folder in $internalFolders) { $src = "/sdcard/$folder" $dst = Join-Path $Destination "Internal_$folder" "Backing up [INTERNAL][$folder]..." | Tee-Object -FilePath $LogFile -Append adb pull $src $dst | Out-Null if ($LASTEXITCODE -eq 0) { Add-Content $LogFile "STATUS: [INTERNAL][$folder] COMPLETE at $(Get-Date)" } else { Add-Content $LogFile "STATUS: [INTERNAL][$folder] FAILED (exit code $LASTEXITCODE) at $(Get-Date)" } } # -------- EXTERNAL STORAGE (/storage/XXXX-XXXX) -------- $externalMounts = adb shell "ls /storage" | ForEach-Object { $_.Trim() } | Where-Object { $_ -match '^[0-9A-Fa-f-]+$' } foreach ($mount in $externalMounts) { $basePath = "/storage/$mount" $externalFolders = adb shell "ls $basePath" | ForEach-Object { $_.Trim() } foreach ($folder in $externalFolders) { $src = "$basePath/$folder" $dst = Join-Path $Destination "External_${mount}_$folder" "Backing up [EXTERNAL][$mount][$folder]..." | Tee-Object -FilePath $LogFile -Append adb pull $src $dst | Out-Null if ($LASTEXITCODE -eq 0) { Add-Content $LogFile "STATUS: [EXTERNAL][$mount][$folder] COMPLETE at $(Get-Date)" } else { Add-Content $LogFile "STATUS: [EXTERNAL][$mount][$folder] FAILED (exit code $LASTEXITCODE) at $(Get-Date)" } } } "Backup finished: $(Get-Date)" | Add-Content $LogFile

📋 Example Log Output

After running the script, the log looked like this:

Backup started: 09/17/2025 12:00:12 Backing up [INTERNAL][DCIM]... STATUS: [INTERNAL][DCIM] COMPLETE at 09/17/2025 12:05:10 Backing up [INTERNAL][Download]... STATUS: [INTERNAL][Download] COMPLETE at 09/17/2025 12:07:02 Backing up [EXTERNAL][1234-5678][Music]... STATUS: [EXTERNAL][1234-5678][Music] COMPLETE at 09/17/2025 12:09:15 Backup finished: 09/17/2025 12:10:00

That was exactly what I needed: a per-folder backup status I could trust.


🎯 Final Thoughts

Backing up an Android phone via USB isn’t as straightforward as copying from a hard drive, but with ADB and a bit of PowerShell, it’s totally doable.

This setup now gives me peace of mind - my Redmi’s internal and external storage are mirrored onto my PC with logs to prove it. 

Friday, 25 April 2025

In Microsoft SQL Server, if you see a user under Database > Security > Users, but not under Server > Security > Logins, it means the database user exists, but its corresponding server-level login is missing.

 

This typically happens when a database is restored on a different server, and the associated login wasn't recreated on the new server.

🔧 Fixing the Issue: Create Login & Map to Existing User

You can't reset a password for a database user directly. Instead, you need to:

✅ Step 1: Create a new login at the server level

Use this T-SQL to create a server-level login that matches the database user:

CREATE LOGIN [UserName] WITH PASSWORD = 'YourNewPassword';

Replace UserName with the name shown under Database > Security > Users.

✅ Step 2: Map the login to the existing user in the database

Now, map the newly created login to the existing user:

USE [YourDatabaseName];
ALTER USER [UserName] WITH LOGIN = [UserName];

Friday, 17 January 2025

Python - Extract emails using regex

Here's a simple python script to extract and format the emails:

Script

import re

input_text = "hj sdsd <jkkl.kll.o.v@blbla.com>; jsdsl lassd <jskdsd.uioo@blbla.com>;"

emails = re.findall(r'<([^>]+)>', input_text)

output = ','.join(f'"{email}"' for email in emails)

print(output)


Output

"jkkl.kll.o.v@blbla.com","jskdsd.uioo@blbla.com"

This script uses a regular expression to find all email addresses enclosed in angle brackets < > and formats them as requested.

Thursday, 25 May 2023

Python how to call ctype in safest way to avoid garbage collector to prevent segmentation fault

 To call Ctypes in a safe way to avoid issues with the garbage collector and prevent segmentation faults in Python, you can follow these guidelines:

  1. Declare argument and return types explicitly: When defining your C function prototypes using Ctypes, explicitly declare the argument types and return type for each function. This helps Ctypes handle the memory management correctly.

    For example, if you have a C function called my_function that takes an int argument and returns a float, you can define it in Python using Ctypes as follows:

    python
    from ctypes import CDLL, c_int, c_float my_library = CDLL('path/to/my_library.so') my_function = my_library.my_function my_function.argtypes = [c_int] my_function.restype = c_float
  2. Prevent Python garbage collector from collecting Ctypes objects prematurely: The garbage collector in Python may attempt to collect Ctypes objects if they are not referenced strongly. To prevent premature garbage collection, ensure that you keep references to any Ctypes objects as long as they are needed.

    For example, if you're using a Ctypes structure as an argument or return value, make sure to store it in a Python variable and keep that variable in scope as long as you need to access the structure's data.

  3. Use byref for passing Ctypes structures: When passing Ctypes structures as arguments to C functions, use the byref function to pass a reference instead of passing the structure directly. This ensures that the memory for the structure is correctly managed by Ctypes.

    For example, if you have a C function called process_data that takes a pointer to a structure as an argument, and you have a Ctypes structure called MyStruct, you can pass it using byref as follows:

    python
    from ctypes import Structure, byref class MyStruct(Structure): # Define the structure fields here my_library.process_data(byref(MyStruct()))

    Note that you should ensure the lifetime of the structure is managed properly outside the C function.

  4. Use c_void_p for opaque pointers: If you're working with opaque pointers in your C code, use the c_void_p type in Ctypes. This type represents a generic pointer and allows you to pass and receive opaque pointers safely.

    For example, if you have a C function that returns an opaque pointer, you can declare its return type as c_void_p in Python:

    python
    from ctypes import CDLL, c_void_p my_library = CDLL('path/to/my_library.so') my_function = my_library.my_function my_function.restype = c_void_p result = my_function()

    Make sure you handle the returned pointer carefully and avoid any invalid dereferences.

By following these guidelines, you can minimize the chances of encountering segmentation faults when calling C code using Ctypes in Python and ensure proper memory management.

Centos Python Segmentation Fault while running Ctype

To analyze a core dump in CentOS, you can follow these steps:


Enable core dumps: By default, core dumps may be disabled in CentOS. To enable them, run the following command:


ulimit -c unlimited

This command allows unlimited core file size.


Trigger the segmentation fault: Reproduce the issue that caused the segmentation fault. Run your Python script or program that resulted in the core dump.


Locate the core dump file: After the segmentation fault occurs, a core dump file is generated. By default, the file is named core and is created in the current working directory. If the file is not named core, it may have a name like core.<PID>, where <PID> represents the process ID of the crashed application.


Analyze the core dump using GDB: The GNU Debugger (GDB) is a powerful tool for analyzing core dump files. Start GDB and specify the executable and core dump file as arguments:



gdb <path_to_executable> <path_to_core_dump_file>

For example, if you're analyzing a Python script called script.py with a core dump file named core, the command would be:



gdb python core

Examine the stack trace: Once inside GDB, you can examine the stack trace to identify the location of the crash. Use the bt (backtrace) command to display the stack trace:



(gdb) bt

This will provide a list of function calls and their corresponding source code locations at the time of the crash.


Analyze variables and memory: GDB allows you to inspect variables, examine memory, and gather additional information about the state of the program when the crash occurred. You can set breakpoints, examine values, and step through the code to investigate the issue further.


Quit GDB: Once you have finished analyzing the core dump, you can quit GDB by entering the quit command.


Remember, analyzing core dump files can be complex, especially if you're dealing with a large codebase or unfamiliar code. It may require a good understanding of debugging techniques and familiarity with the code involved. 

Thursday, 6 April 2023

Windows - Get local user's last login

 To get the last login of a local user on a Windows machine, you can use the following steps:

  1. Open the Command Prompt or PowerShell as an administrator.
  2. Type the command net user [username] and press Enter, replacing "[username]" with the name of the user you want to check.
  3. Look for the line that says "Last logon," which will show the date and time of the user's last login.

Alternatively, you can use the following command in PowerShell to get the last logon time for all local users:


Get-LocalUser | Select-Object Name, LastLogonTime

This will display the names and last logon times of all local users on the machine.

Friday, 3 March 2023

How can I publish an AI based story ebook in amazon?

To publish an AI-based story ebook on Amazon, you can follow these steps:

  1. Create an Amazon Kindle Direct Publishing (KDP) account: Go to the KDP website and create an account. You will need to provide some personal information, including your name, email address, and payment information.

  2. Format your ebook: Amazon provides guidelines for formatting ebooks, so make sure to follow these guidelines carefully to ensure that your ebook is properly formatted for publication. You can also use a third-party formatting tool or hire a professional formatter to do this for you.

  3. Upload your ebook: Once your ebook is properly formatted, you can upload it to your KDP account. You will need to provide some basic information about your ebook, including the title, author name, description, and cover image.

  4. Set the price: You can set the price for your ebook based on Amazon's pricing guidelines. You can also choose to enroll in Kindle Select, which gives you access to additional promotional tools and allows you to earn royalties based on the number of pages read by Kindle Unlimited subscribers.

  5. Publish your ebook: Once you have completed all the required steps, you can publish your ebook on Amazon. It will typically take a few hours for your ebook to become available for purchase.

Remember that publishing an ebook on Amazon is just the first step. You will also need to promote your ebook through various channels to reach potential readers and generate sales. This may include using social media, email marketing, and other promotional tools to reach your target audience.

Is AI a threat to mankind ?

 AI can potentially be a threat to mankind if it is not developed and used responsibly. Here are some potential risks associated with AI:

  1. Autonomous weapons: There is a risk that AI-powered weapons could be developed and used in warfare, without human oversight or intervention. This could lead to unintended harm and loss of life.

  2. Job displacement: As AI becomes more advanced and capable of performing a wide range of tasks, there is a risk that it could displace human workers in many industries. This could lead to significant economic and social disruption.

  3. Biased decision-making: AI systems are only as unbiased as the data they are trained on. If AI is trained on biased or incomplete data, it could perpetuate and even amplify existing biases in society.

  4. Privacy concerns: As AI systems become more advanced, they may be able to collect and analyze vast amounts of personal data without individuals' consent or knowledge. This could lead to significant privacy violations and risks to personal security.

  5. Unintended consequences: There is always a risk that AI systems could have unintended consequences or unforeseen side effects that could harm society or individuals.

To mitigate these risks, it is important for AI development to be guided by ethical principles and for AI to be used in a responsible and transparent manner. This will require collaboration and cooperation among researchers, policymakers, and other stakeholders to ensure that AI is developed and used for the benefit of society as a whole.

Future of AI

It's difficult to predict the future of AI with certainty, but here are some potential developments that could occur by 2050:

  1. General AI: We may see the development of artificial general intelligence (AGI), which is an AI system capable of performing any intellectual task that a human can do. AGI would require a significant breakthrough in AI research and development, but could have far-reaching implications for society.

  2. More advanced natural language processing: AI may become much more adept at understanding and processing natural language, allowing for more seamless communication between humans and machines. This could lead to advances in fields such as healthcare, education, and customer service.

  3. Increased automation: AI-powered automation could lead to significant changes in the job market, with many routine and repetitive tasks being automated. This could result in job displacement and the need for retraining and education programs.

  4. Advancements in robotics: AI-powered robots could become more prevalent in a wide range of industries, including manufacturing, transportation, and healthcare. This could lead to improvements in efficiency and safety, but also raise ethical concerns about the role of robots in society.

  5. Ethical considerations: As AI becomes more advanced and integrated into society, there will be a growing need for ethical guidelines and regulations to ensure that AI is developed and used in a responsible and ethical manner.

Overall, the future of AI is likely to be shaped by a combination of technological breakthroughs, social and economic factors, and ethical considerations. While there are certainly risks and challenges associated with the continued development of AI, there is also significant potential for AI to benefit society in numerous ways.