Snippets Collections
for /R /D %I IN (*.*) DO TRID "%I\*" ce
import 'dart:convert';
import 'package:http/http.dart' as http;

class ApiService<T> {
  final String _baseUrl;

  ApiService(this._baseUrl);

  Future<List<T>> getAll(T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse(_baseUrl));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to load data');
    }
  }

  Future<List<T>> search(String query, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.get(Uri.parse('$_baseUrl?search=$query'));
    if (response.statusCode == 200) {
      final jsonData = json.decode(response.body) as List;
      return jsonData.map((data) => fromJson(data)).toList();
    } else {
      throw Exception('Failed to search data');
    }
  }

  Future<T> create(Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.post(
      Uri.parse(_baseUrl),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 201) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to create data');
    }
  }

  Future<T> update(int id, Map<String, dynamic> data, T Function(Map<String, dynamic>) fromJson) async {
    final response = await http.put(
      Uri.parse('$_baseUrl/$id'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );
    if (response.statusCode == 200) {
      return fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to update data');
    }
  }

  Future<void> delete(int id) async {
    final response = await http.delete(Uri.parse('$_baseUrl/$id'));
    if (response.statusCode != 204) {
      throw Exception('Failed to delete data');
    }
  }
}
//=============================================
class Note {
  final int id;
  final String title;
  final String content;

  Note({required this.id, required this.title, required this.content});

  factory Note.fromJson(Map<String, dynamic> json) {
    return Note(
      id: json['id'],
      title: json['title'],
      content: json['content'],
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
    };
  }
}

final notesService = ApiService<Note>('http://10.0.2.2:8000/api/notes');

// Get all notes
final notes = await notesService.getAll(Note.fromJson);

// Search for notes
final searchResults = await notesService.search('keyword', Note.fromJson);

// Create a new note
final newNote = await notesService.create(
  {
    'title': 'New Note',
    'content': 'This is a new note',
  },
  Note.fromJson,
);

// Update a note
final updatedNote = await notesService.update(
  newNote.id,
  {
    'title': 'Updated Note',
    'content': 'This is an updated note',
  },
  Note.fromJson,
);

// Delete a note
await notesService.delete(updatedNote.id);
 For /D /R j:\test %%1 IN (*) DO c:\trid_w32\trid "%%1"\* -ae


Replace j:\test with the directory that you want to move recursively through (TrID will not run on the files in the root of this directory).

Replace c:\trid_w32\trid with the path to trid.exe.

Dump the line in a batch file and run.
<button type="button" class="btn-close" aria-label="Close"></button>
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int s=0,e=(matrix.size()*matrix[0].size())-1;
        while(s<=e){
            int n=matrix[0].size();
            int mid=s+(e-s)/2;
            int i=mid/n;
            int j=(mid%n);
            if(matrix[i][j]==target){
                return true;
            }
            else if( matrix[i][j]<target) s=mid+1;
            else e=mid-1;
        }
        return false;
    }
};
//{ Driver Code Starts
#include <bits/stdc++.h> 
using namespace std; 

// } Driver Code Ends
class Solution
{   
    public: 
    //Function to return a list of integers denoting spiral traversal of matrix.
    vector<int> spirallyTraverse(vector<vector<int> > matrix, int r, int c) 
    {   
        vector<int> v;
        int startrow=0;
        int endrow=r-1;
        int startcol=0;
        int endcol=c-1;
        while(startrow<=endrow && startcol<=endcol){
            for(int i=startcol;i<=endcol && startrow<=endrow && startcol<=endcol;i++){
                v.push_back(matrix[startrow][i]);
            }
            startrow++;
            for(int i=startrow;i<=endrow && startrow<=endrow && startcol<=endcol;i++){
                v.push_back(matrix[i][endcol]);
            }
            endcol--;
            for(int i=endcol;i>=startcol && startrow<=endrow && startcol<=endcol;i--){
                v.push_back(matrix[endrow][i]);
            }
            endrow--;
            for(int i=endrow;i>=startrow && startrow<=endrow && startcol<=endcol;i--){
                v.push_back(matrix[i][startcol]);
            }
            startcol++;
        }
        return v;
        
    }
};

//{ Driver Code Starts.
int main() {
    int t;
    cin>>t;
    
    while(t--) 
    {
        int r,c;
        cin>>r>>c;
        vector<vector<int> > matrix(r); 

        for(int i=0; i<r; i++)
        {
            matrix[i].assign(c, 0);
            for( int j=0; j<c; j++)
            {
                cin>>matrix[i][j];
            }
        }

        Solution ob;
        vector<int> result = ob.spirallyTraverse(matrix, r, c);
        for (int i = 0; i < result.size(); ++i)
                cout<<result[i]<<" ";
        cout<<endl;
    }
    return 0;
}
// } Driver Code Ends
const shaunObj = {
  name: 'gary',
  year: 1987,
  currentYear: new Date().getFullYear(),

  // solution 1 = declare a normal function as this is bound to these functions
  calcAgeOne: function () {
    const self = this;
    const yearsold = self.currentYear - self.year;
    return yearsold;
  },

  // solution 2
  calcAgeTwo: function () { // declative function again but with arrow function inside
    console.log(this);

    const calcAgeArrow = () => {
      console.log(this);
      const yearsold = this.currentYear - this.year;
      return yearsold;
    };

    return calcAgeArrow(); // return the arrow function to the parent function
  },

	// DO NOT DO THIS
  // calcAge: () => {
  //   const yearsold = this.currentYear - this.year;
  //   return yearsold;
  // },
};

console.log(shaunObj.calcAgeOne());
console.log(shaunObj.calcAgeTwo()); // works with
def is_sorted(lst):
    for i in range(len(lst) - 1):
        if lst[i] > lst[i + 1]:
            return False
    return True
my_list = [1, 2, 3, 4, 5]
print(is_sorted(my_list))
my_list = [1, 3, 2, 4, 5]
print(is_sorted(my_list))
const davidObj = {
    first: 'David',
    last: 'Mchale',
    year: 1978,
    currentYear: new Date().getFullYear(),
    age: function () {
        const yearsold = this.currentYear - this.year;
        return yearsold;
    },
};

const maryObj = {
    first: 'Mary',
    last: 'Jones',
    year: 1985, // Add this
    currentYear: new Date().getFullYear(), // Add this
};

maryObj.age = davidObj.age;

console.log(maryObj.age()); // Output should be Mary's age




// alternative cleaner way

const davidObj = {
    first: 'David',
    last: 'Mchale',
    year: 1978,
    currentYear: new Date().getFullYear(),
    age: function (year, currentYear) {
        const yearsold = currentYear - year;
        return yearsold;
    },
};

const maryObj = {
    first: 'Mary',
    last: 'Jones',
    year: 1985,
    currentYear: new Date().getFullYear(),
};

// Borrow the age method with parameters to a function outside both objects
maryObj.age = function() {
    return davidObj.age(this.year, this.currentYear);
};

console.log(maryObj.age()); // Output should be Mary's age
var dupeRecords;
dupeRecords = getMultiFieldDupes(
    'incident', //Table name
    ['short_description', 'assignment_group', 'assigned_to'], //Fields to check for duplicates
    ['short_description','assigned_to'], //Fields that must not be blank
    true //Get the sys_ids of the records with duplicates
);
//Print out the results:
gs.info(
    'Found ' + dupeRecords.length + ' duplicate types:\n' +
    JSON.stringify(dupeRecords, null, 2)
);
/**
 * Get records with duplicate values in multiple fields, and return a list of the records'
 * counts and the dupe fields' values.
 *
 * @param {string} tableName - The table to check for duplicates. Must be a string.
 *
 * @param {string|string[]} arrDupeFields - The fields to check for duplicates.
 *  Must be a string or an array of strings.
 *
 * @param {string|string[]} [nonBlankFields=[]] - This optional parameter, if specified, will
 *  be an array of strings consisting of the names of the fields which should not be allowed
 *  to be blank when checking for duplicates.
 * To put it another way, if any of the fields specified in the `nonBlankFields` array are
 *  blank, then the record should not be considered a duplicate.
 * Note that the fields specified in nonBlankFields do NOT need to also be specified in
 * arrDupeFields.
 *
 * @param {boolean} [getDupeSysIds=false] - If true, the sys_ids of the records with the
 *  duplicate values will be included in the returned object. If false, they will not be
 *  included.
 * This may have a performance impact, as it requires an additional query for each
 *  duplicate combination, so use with caution.
 * Default is false.
 *
 * @returns {{dupeCount: (*|number), fields: {}}[]} - An array of objects, each object
 *  representing a confluence of duplicate values in the specified fields - a specific
 *  combination of field values - and the number of records that have that combination of
 *  those values in the specified fields.
 */
function getMultiFieldDupes(tableName, arrDupeFields, nonBlankFields, getDupeSysIds) {
    var gaMyTableDuplicate, grDupe, iNonBlankField, iDupeField, objDupeRecord;
    var arrDupeRecords = [];
    var dupeCount = 0;
    
    /***** INPUT VALIDATION *****/
    
    getDupeSysIds = (typeof getDupeSysIds === 'boolean') ? getDupeSysIds : false;
    
    if (typeof tableName !== 'string' || !tableName) {
        throw new Error(
            'getMultiFieldDupes(): tableName must be a string consisting of a valid ' +
            'table name in the ServiceNow database.'
        );
    }
    
    if ( //If arrDupeFields is not an array or a string, or if it's an array but it's empty
        typeof arrDupeFields === 'undefined' ||
        !arrDupeFields ||
        (!Array.isArray(arrDupeFields)  && typeof arrDupeFields !== 'string') ||
        !arrDupeFields.length
    ) {
        throw new Error(
            'getMultiFieldDupes(): arrDupeFields must be a string with a single ' +
            'field name, or an array of strings - each string representing a ' +
            'field name in the ' + tableName + ' table.'
        );
    }
    
    //If arrDupeFields is a string, convert it to an array.
    if (typeof arrDupeFields === 'string') {
        arrDupeFields = arrDupeFields.split(',');
    }
    
    //If nonBlankFields is undefined, null, or an empty string, set it to an empty array.
    //If it's a string, convert it to an array.
    if (typeof nonBlankFields === 'undefined' || !nonBlankFields) {
        nonBlankFields = [];
    } else if (typeof nonBlankFields === 'string') {
        //Splitting just in case the input data is a comma-separated string - which it
        // shouldn't be, but I don't trust anyone who calls this code. They seem sus.
        nonBlankFields = nonBlankFields.split(',');
    } else if (!Array.isArray(nonBlankFields)) {
        //If it's not a string or an array or undefined, throw an error because wth am I s'posed to do with that
        throw new Error(
            'getMultiFieldDupes(): nonBlankFields must be a string with a single ' +
            'field name, or an array of strings - each string representing a ' +
            'field name in the ' + tableName + ' table.'
        );
    }
    
    /***** ACTUALLY DOING THE THING *****/
    gaMyTableDuplicate = new GlideAggregate(tableName);
    gaMyTableDuplicate.addAggregate('COUNT');
    
    //Group by each field in the arrDupeFields array
    for (
        iDupeField = 0;
        iDupeField < arrDupeFields.length;
        iDupeField++
    ) {
        gaMyTableDuplicate.groupBy(arrDupeFields[iDupeField]);
    }
    
    //If any nonBlankFields were specified, add a query to exclude records where
    // any of those fields are blank.
    for (
        iNonBlankField = 0;
        iNonBlankField < nonBlankFields.length;
        iNonBlankField++
    ) {
        gaMyTableDuplicate.addNotNullQuery(nonBlankFields[iNonBlankField]);
    }
    
    //Only show records with more than one match (duplicates)
    gaMyTableDuplicate.addHaving('COUNT', '>', 1);
    gaMyTableDuplicate.query();
    
    while (gaMyTableDuplicate.next()) {
        dupeCount = gaMyTableDuplicate.getAggregate('COUNT');
        
        //Populate the arrDupeRecords array with some info about the records that have duplicates
        objDupeRecord = {
            "dupeCount": dupeCount,
            "fields": {}
        };
        
        //For each field in the arrDupeFields array, add that field's value to
        // the objDupeRecord.fields object.
        for (
            iDupeField = 0;
            iDupeField < arrDupeFields.length;
            iDupeField++
        ) {
            objDupeRecord.fields[arrDupeFields[iDupeField]] = gaMyTableDuplicate.getValue(arrDupeFields[iDupeField]);
        }
        
        if (getDupeSysIds) {
            objDupeRecord.dupe_sys_ids = [];
            //Add the sys_ids of all the records that have this combination of dupe fields in objDupeRecord.dupe_sys_ids:
            grDupe = new GlideRecord(tableName);
            
            for (
                iDupeField = 0;
                iDupeField < arrDupeFields.length;
                iDupeField++
            ) {
                grDupe.addQuery(arrDupeFields[iDupeField], objDupeRecord.fields[arrDupeFields[iDupeField]]);
            }
            
            grDupe.query();
            while (grDupe.next()) {
                objDupeRecord.dupe_sys_ids.push(grDupe.getUniqueValue());
            }
        }
        
        arrDupeRecords.push(objDupeRecord);
    }
    
    return arrDupeRecords;
}
import classes.*;

public class Main {
    public static void main(String[] args) {
        Mygeneric mygen = new Mygeneric<String>("Dodi");
        generate(mygen);

        Mygeneric<Object> gen = new Mygeneric<Object>("Jamal");
        process(gen);
        
    }

    public static void doodle(Mygeneric<String> mygen) {
        System.out.println(mygen.getData());
    }

    /*
     * Saya akan menerima parameter apapun hasil instance dari 
     * kelas Mygeneric yang tipe genericnya adalah turunan dari Object
     */
    public static void generate(Mygeneric<? extends Object> data) {
        System.out.println(data.getData());

    }

    /*
     * Saya akan menerima parameter apapun hasil instance dari
     * kelas Mygeneric yang bertipe data String ATAU super class dari
     * String
     */
    public static void process(Mygeneric<? super String> data) {
        String value = (String) data.getData();
        System.out.println(value);
        data.setData("Umar");
        System.out.println(value);
    }
}
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix
from deep_translator import GoogleTranslator
from pymongo import MongoClient
from sklearn.metrics import ConfusionMatrixDisplay
import matplotlib.pyplot as plt
import numpy as np
from nltk.stem import WordNetLemmatizer

# Initialize MongoDB client and collection
mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"
collection_name = "final"
client = MongoClient(mongo_uri, serverSelectionTimeoutMS=5000)
db = client[database_name]
collection = db[collection_name]

# Initialize sentiment analyzer
analyzer = SentimentIntensityAnalyzer()

# Initialize WordNet Lemmatizer
lemmatizer = WordNetLemmatizer()

# Function to translate text to English
def translate_to_english(text, lang):
    translated_text = GoogleTranslator(source='auto', target='en').translate(text)
    return translated_text

# Function to clean text by lemmatizing
def clean_text(text):
    lemmatized_text = ' '.join([lemmatizer.lemmatize(word) for word in text.split()])
    return lemmatized_text.strip()

# Function to analyze sentiment
def analyze_sentiment(text):
    lemmatized_text = clean_text(text)
    sentiment = analyzer.polarity_scores(lemmatized_text)
    compound_score = sentiment['compound']
    if compound_score > 0:
        return 1  # Positive
    elif compound_score <= 0:
        return 0  # Negative

# Initialize lists to store true labels and predicted sentiments
true_labels = [1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0]
predicted_sentiments = []

# Iterate through tweets in MongoDB collection
cursor = collection.find().limit(100)

for doc in cursor:
    lang = doc.get("json_data.lang")
    tweet_text = doc.get('json_data.text')
    
    text_to_use = tweet_text
    
    if lang != 'en':
        translated_text = translate_to_english(text_to_use, lang)
    else:
        translated_text = text_to_use
    
    # Clean and lemmatize text
    cleaned_text = clean_text(translated_text)
    
    # Perform sentiment analysis
    sentiment = analyze_sentiment(cleaned_text)
    predicted_sentiments.append(sentiment)

# Convert lists to numpy arrays for confusion matrix calculation
true_labels = np.array(true_labels)
predicted_sentiments = np.array(predicted_sentiments)

# Compute confusion matrix
cm = confusion_matrix(true_labels, predicted_sentiments)

plt.figure(figsize=(10, 8))
labels = ['Negative', 'Positive']
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=labels)
disp.plot(cmap='Blues', ax=plt.gca())  # Use plt.gca() to get current axes for proper positioning

# Add metrics as annotations

plt.title('Confusion Matrix')
plt.tight_layout()  # Adjust layout for better spacing
plt.show()

#import the module
import asyncio

#define asynchronous tasks
async def task1():
    #prints even numbers from 0 to 9
    for i in range(10):
       if i%2 ==0:
           print(i)
           await asyncio.sleep(0.0001)#cause a small delay

async def task2():
     #prints odd numbers from 0 to 9
     for i in range(10):
         if i%2 == 1:
             print(i)
             await asyncio.sleep(0.0001) # cause a small delay

async def main():
    print('Started:')
    await asyncio.gather(task1(), task2())
    print('Finished!')

asyncio.run(main())
from pymongo import MongoClient
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import statistics
from deep_translator import GoogleTranslator
from nltk.stem import WordNetLemmatizer
import matplotlib.pyplot as plt

# Initialize MongoDB client and collection
mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"
collection_name = "tweet_cleaned"
client = MongoClient(mongo_uri, serverSelectionTimeoutMS=5000)
db = client[database_name]
collection = db[collection_name]

# Initialize sentiment analyzer
analyzer = SentimentIntensityAnalyzer()

# Initialize WordNet Lemmatizer
lemmatizer = WordNetLemmatizer()

# Function to clean text by lemmatizing
def clean_text(text):
    # Lemmatize the entire text
    lemmatized_text = lemmatizer.lemmatize(text)
    return lemmatized_text.strip()

# Function to translate text to English
def translate_to_english(text, lang):
    translated_text = GoogleTranslator(source='auto', target='en').translate(text)
    return translated_text

# Function to analyze sentiment
def analyze_sentiment(text):
    sentiment = analyzer.polarity_scores(text)
    compound_score = sentiment['compound']
    return compound_score

# Initialize lists for sentiment scores
positive_scores = []
negative_scores = []

# Iterate through tweets in MongoDB collection
cursor = collection.find().limit(100)

for doc in cursor:
    lang = doc.get("json_data.lang")
    tweet_text = doc.get('json_data.text')

    if lang != 'en':
        translated_text = translate_to_english(tweet_text, lang)
    else:
        translated_text = tweet_text
   
    # Clean and lemmatize text
    cleaned_text = clean_text(translated_text)
   
    # Perform sentiment analysis
    sentiment = analyze_sentiment(cleaned_text)
    
    # Categorize sentiment scores
    if sentiment > 0:
        positive_scores.append(sentiment)
    else:
        negative_scores.append(sentiment)

# Close MongoDB client
client.close()

plt.figure(figsize=(10, 6))

# Box plot for positive scores
plt.boxplot(positive_scores, positions=[1], widths=0.6, patch_artist=True, boxprops=dict(facecolor='lightgreen'), medianprops=dict(color='darkgreen'), showfliers=True)

# Box plot for negative scores
plt.boxplot(negative_scores, positions=[2], widths=0.6, patch_artist=True, boxprops=dict(facecolor='lightcoral'), medianprops=dict(color='darkred'), showfliers=True)

# Plot details
plt.title('Sentiment Analysis of Tweets')
plt.ylabel('Compound Sentiment Score')
plt.xticks([1, 2], ['Positive', 'Negative'])
plt.grid(True)
plt.tight_layout()

# Show plot
plt.show()
#if, else and if else

x = 5
if(x==10){
   print("X is equal to 10")
}else if(x == 12){
   print("X is 12")
}else{
   print("x is not any of the above")
}

temp = 80

if (temp > 80){
   print("It is hot")
}else{
   print("print is not hot outside")
}

votes = 10

if(votes > 50){
   print("You won")

}else if(votes < 50 & votes > 40){
   print("No winner")
}else{
   print("You all failed")
}
from pymongo import MongoClient
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import statistics
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import string
from deep_translator import GoogleTranslator
import re






# Initialize MongoDB client and collection
mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"
collection_name = "tweet_cleaned"
client = MongoClient(mongo_uri, serverSelectionTimeoutMS=5000)
db = client[database_name]
collection = db[collection_name]


# Initialize sentiment analyzer
analyzer = SentimentIntensityAnalyzer()


# Initialize WordNet Lemmatizer
lemmatizer = WordNetLemmatizer()


# Function to clean text by lemmatizing
def clean_text(text):
    # Lemmatize the entire text
    lemmatized_text = lemmatizer.lemmatize(text)
    return lemmatized_text.strip()


# Function to translate text to English
def translate_to_english(text, lang):
    if lang != 'en':
        translated_text = GoogleTranslator(source='auto', target='en').translate(text)
    else:
        translated_text = text
    return translated_text


# Function to analyze sentiment
def analyze_sentiment(text):
    sentiment = analyzer.polarity_scores(text)
    compound_score = sentiment['compound']
    return compound_score


# Initialize counters
positive_count = 0
negative_count = 0
compound_scores = []


# Iterate through tweets in MongoDB collection
cursor = collection.find().limit(100)


for doc in cursor:
    lang = doc.get("json_data.lang")
    tweet_text = doc.get('json_data.text')



    if lang != 'en':
        translated_text = translate_to_english(tweet_text, lang)
    else:
        translated_text = tweet_text
   
    # Clean and lemmatize text
    cleaned_text = clean_text(translated_text)
   
    # Perform sentiment analysis
    sentiment = analyze_sentiment(cleaned_text)
    compound_scores.append(sentiment)
   
    # Update sentiment counts
    if sentiment > 0 :
        positive_count += 1
    else :
        negative_count += 1
    


# Calculate mean compound score
mean_score = statistics.mean(compound_scores)


# Print results
print("Positive:", positive_count)
print("Negative:", negative_count)
print("Mean compound score:", mean_score)


# Close MongoDB client
client.close()



from deep_translator import GoogleTranslator
from pymongo import MongoClient
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import string

# MongoDB connection details
mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"
collection_name = "final"

# Connect to MongoDB
client = MongoClient(mongo_uri)
db = client[database_name]
collection = db[collection_name]

# Function to translate text to English
def translate_to_english(text, lang):
    if lang != 'en':
        translated_text = GoogleTranslator(source='auto', target='en').translate(text)
    else:
        translated_text = text
    return translated_text

# Fetch text data from MongoDB
texts = []
cursor = collection.find().limit(100)

# Initialize stopwords
stop_words = set(stopwords.words('english'))

# Process each document fetched from MongoDB
all_text = ""
for doc in cursor:
    text = doc.get("json_data.text")
    lang = doc.get("json_data.lang")
    text = translate_to_english(text, lang)
    
    # Tokenize the text
    tokens = word_tokenize(text)
    
    # Remove punctuation and stopwords
    tokens = [word.lower() for word in tokens if word.isalpha() and word.lower() not in stop_words]
    
    # Join tokens into a single string
    processed_text = " ".join(tokens)
    
    # Accumulate all text for generating word cloud
    all_text += processed_text + " "

# Generate the word cloud
wordcloud = WordCloud(width=800, height=400, background_color='white').generate(all_text)

# Plotting the word cloud
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('Word Cloud of Text Field in Tweets')
plt.show()
#if, else and if else

x = 5
if(x==10) {
   print("X is equal to 10")
}else if(x == 12){
   print("X is 12")
}else{
   print("x is not any of the above")
}
#if, else and if else

x = 5
if (x==10) {
   print("X is equal to 10")
}else if (x == 12){
   print("X is 12")
}else{
   print("x is not any of the above")
}
from pymongo import MongoClient
import matplotlib.pyplot as plt

# MongoDB connection details
mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"
collection_name = "tweets"

# Connect to MongoDB
client = MongoClient(mongo_uri)
db = client[database_name]
collection = db[collection_name]

# Initialize counters
null_count = 0
not_null_count = 0

cursor = collection.find()
for doc in cursor:
    if doc.get("json_data", {}).get("place") is None:
        null_count += 1
    else:
        not_null_count += 1

# Data for the bar chart
categories = ['Null', 'Not Null']
counts = [null_count, not_null_count]

# Plotting the bar chart
plt.bar(categories, counts, color=['blue', 'orange'])

plt.xlabel('Place Value')
plt.ylabel('Count')
plt.title('Count of Null vs Not Null values in json_data.place')
plt.show()
import json
from deep_translator import GoogleTranslator
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
# Initialize sentiment analyzer
analyzer = SentimentIntensityAnalyzer()


# Initialize WordNet Lemmatizer
lemmatizer = WordNetLemmatizer()
def clean_text(text):
    lemmatized_text = lemmatizer.lemmatize(text)
    return lemmatized_text.strip()


# Function to translate text to English
def translate_to_english(text, lang):
    if lang != 'en':
        translated_text = GoogleTranslator(source='auto', target='en').translate(text)
    else:
        translated_text = text
    return translated_text


# Function to analyze sentiment
def analyze_sentiment(text):
    sentiment = analyzer.polarity_scores(text)
    compound_score = sentiment['compound']
    return compound_score


# Recursive function to process replies
def process_replies(reply_data):
    reply_text = reply_data.get("text", "")
    reply_lang = reply_data.get("lang", "en")
    
    if reply_lang != "en":
        reply_text = translate_to_english(reply_text, reply_lang)
        
    reply_text = clean_text(reply_text)
    sentiment_score_reply = analyze_sentiment(reply_text)
    reply_data["sentiment_score"] = sentiment_score_reply
    
    for reply in reply_data.get("replies", []):
        process_replies(reply)

file_path = r'C:\Users\User\Desktop\DBL Data Challenge\lala.json'
updated_data = []

with open(file_path, 'r', encoding='utf-8') as file:
    for line in file:
        try:
            data = json.loads(line.strip())
            lang = data.get("lang", "en")
            text = data.get("text", "")
            replies = data.get("replies", [])
            
            if lang != "en":
                text = translate_to_english(text, lang)
            
            text = clean_text(text)
            sentiment_score_main_text = analyze_sentiment(text)
            data["sentiment_score"] = sentiment_score_main_text  # Add sentiment score to main tweet object
            
            for reply_data in replies:
                process_replies(reply_data)
            
            updated_data.append(data)
            
        except json.JSONDecodeError:
            print("Error: Invalid JSON format")
            continue

# Write the updated data back to the JSON file
with open(file_path, 'w', encoding='utf-8') as file:
    for item in updated_data:
        json.dump(item, file)
        file.write('\n')

print("Sentiment scores added to the JSON file.")
import os
import json
import pymongo
from pymongo import MongoClient
 
# Configure MongoDB connection
client = MongoClient('mongodb://localhost:27017/')
db = client['twitter_db']
collection = db['tweets']
 
# Directory containing the JSON files
directory_path = 'C:/Users/User/Desktop/DBL Data Challenge/data'
 
# Function to insert JSON objects from a file into MongoDB
def insert_file(file_path):
    try:
        with open(file_path, 'r') as file:
            for line_number, line in enumerate(file, start=1):
                if line.strip():  # Skip empty lines
                    try:
                        json_object = json.loads(line)
                        document = {
                            'file_name': os.path.basename(file_path),
                            'json_data': json_object
                        }
                        collection.insert_one(document)
                    except json.JSONDecodeError as e:
                        print(f"JSONDecodeError: Error reading JSON data from file {file_path}, line {line_number}: {e}")
    except IOError as e:
        print(f"IOError: Error reading file {file_path}: {e}")
    except pymongo.errors.PyMongoError as e:
        print(f"PyMongoError: Error uploading data from file {file_path} to MongoDB: {e}")
    except Exception as e:
        print(f"Unexpected error with file {file_path}: {e}")
 
# Iterate over files in the directory and insert them into MongoDB
file_count = 0
error_count = 0
for filename in os.listdir(directory_path):
    file_path = os.path.join(directory_path, filename)
    if os.path.isfile(file_path) and filename.endswith('.json'):
        try:
            insert_file(file_path)
            file_count += 1
        except Exception as e:
            print(f"Unexpected error while processing file {file_path}: {e}")
            error_count += 1
 
print(f"All {file_count} files have been processed.")
if error_count > 0:
    print(f"There were {error_count} files that encountered errors.")
from pymongo import MongoClient, errors

mongo_uri = "mongodb://localhost:27017/"
database_name = "twitter_database"
source_collection_name = "tweets"
target_collection_name = "final"

fields_to_extract = [
    "json_data.id",
    "json_data.user.id",
    "json_data.created_at",
    "json_data.in_reply_to_status_id",
    "json_data.in_reply_to_user_id",
    "json_data.entities.user_mentions",
    "json_data.lang",
    "json_data.user.location",
]
airline_id_wanted =[56377143, 106062176, 124476322, 18332190, 22536055,20626359]


def get_nested_field(data, field_path):
    keys = field_path.split('.')
    for key in keys:
        if isinstance(data, list):
            try:
                key = int(key)
                data = data[key]
            except (ValueError, IndexError):
                return None
        elif isinstance(data, dict):
            data = data.get(key)
        else:
            return None
        if data is None:
            return None
    return data

try:
    client = MongoClient(mongo_uri, serverSelectionTimeoutMS=5000)
    db = client[database_name]
    source_collection = db[source_collection_name]
    target_collection = db[target_collection_name]

    cursor = source_collection.find()

    for doc in cursor:
        new_doc = {field: get_nested_field(doc, field) for field in fields_to_extract}
        new_doc["_id"] = doc["_id"]

        # Check if extended_tweet.full_text is present, if not use json_data.text
        full_text = get_nested_field(doc, "json_data.extended_tweet.full_text")
        if full_text:
            new_doc["json_data.text"] = full_text
        else:
            new_doc["json_data.text"] = get_nested_field(doc, "json_data.text")

        # Insert the new document into the target collection
        target_collection.insert_one(new_doc)

    print("Data successfully transferred to new collections.")

except errors.ServerSelectionTimeoutError as err:
    print("Failed to connect to MongoDB server:", err)
except errors.PyMongoError as err:
    print("An error occurred while working with MongoDB:", err)
finally:
    client.close()
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class ListViewExample extends StatefulWidget {
  const ListViewExample({Key? key}) : super(key: key);

  @override
  _ListViewExampleState createState() => _ListViewExampleState();
}

class _ListViewExampleState extends State<ListViewExample> {
  List<Map<String, dynamic>> items = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    fetchDataFromServer();
  }

  Future<void> fetchDataFromServer() async {
    final String apiUrl = 'https://aina.company/DIT/KN/getAllReq.php';
    final Map<String, dynamic> queryParams = {
      'apk': 'sdkjq1234wda4dfadf315rFDfhagfgfg',
      'userid': '1',
    };

    final Dio dio = Dio();

    try {
      print('Making request to $apiUrl with $queryParams');
      final response = await dio.post(
        apiUrl,
        options: Options(
          headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        ),
        data: queryParams,
      );

      print('Response status: ${response.statusCode}');
      print('Response body: ${response.data}');

      if (response.statusCode == 200) {
        final List<dynamic> data = response.data;
        setState(() {
          items = List<Map<String, dynamic>>.from(data);
          isLoading = false;
        });
      } else {
        print(
            'Error: Failed to load data from server with status code ${response.statusCode}');
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {
      print('Error: $e');
      setState(() {
        isLoading = false;
      });
    }
  }

  void _onItemTap(Map<String, dynamic> item) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
            'REQUEST ID: ${item['requests_id']}, REQUEST STATUS: ${item['requests_status']}, REQUEST STATUS TEXT: ${item['texts_requests']}'),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Server JSON ListView'),
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : items.isEmpty
              ? Center(child: Text('No data available'))
              : ListView.separated(
                  itemCount: items.length,
                  itemBuilder: (context, index) {
                    final item = items[index];
                    return Card(
                      child: ListTile(
                        title: Text('REQUEST ID: ${item['requests_id']}'),
                        subtitle: Text(
                            'REQUEST STATUS: ${item['requests_status']}\nREQUEST STATUS TEXT: ${item['texts_requests']}'),
                        trailing: Icon(Icons.arrow_forward),
                        onTap: () => _onItemTap(item),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => const Divider(),
                ),
    );
  }
}

void main() {
  runApp(const MaterialApp(
    home: ListViewExample(),
  ));
}
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';

class ListViewExample extends StatefulWidget {
  const ListViewExample({Key? key}) : super(key: key);

  @override
  _ListViewExampleState createState() => _ListViewExampleState();
}

class _ListViewExampleState extends State<ListViewExample> {
  List<Map<String, dynamic>> items = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    fetchDataFromServer();
  }

  Future<void> fetchDataFromServer() async {
    final String apiUrl = 'https://aina.company/DIT/KN/getAllReq.php';
    final Map<String, String> queryParams = {
      'apk': 'sdkjq1234wda4dfadf315rFDfhagfgfg',
      'userid': '1',
    };

    try {
      final Uri uri = Uri.parse(apiUrl);
      print('Making request to $uri');
      
      final response = await http.post(
        uri,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: queryParams,
      );

      print('Response status: ${response.statusCode}');
      print('Response body: ${response.body}');

      if (response.statusCode == 200) {
        final List<dynamic> data = json.decode(response.body);
        setState(() {
          items = List<Map<String, dynamic>>.from(data);
          isLoading = false;
        });
      } else {
        print(
            'Error: Failed to load data from server with status code ${response.statusCode}');
        setState(() {
          isLoading = false;
        });
      }
    } catch (e) {
      print('Error: $e');
      setState(() {
        isLoading = false;
      });
    }
  }

  void _onItemTap(Map<String, dynamic> item) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
            'REQUEST ID: ${item['requests_id']}, REQUEST STATUS: ${item['requests_status']}, REQUEST STATUS TEXT: ${item['texts_requests']}'),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Server JSON ListView'),
      ),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : items.isEmpty
              ? Center(child: Text('No data available'))
              : ListView.separated(
                  itemCount: items.length,
                  itemBuilder: (context, index) {
                    final item = items[index];
                    return Card(
                      child: ListTile(
                        title: Text('REQUEST ID: ${item['requests_id']}'),
                        subtitle: Text(
                            'REQUEST STATUS: ${item['requests_status']}\nREQUEST STATUS TEXT: ${item['texts_requests']}'),
                        trailing: Icon(Icons.arrow_forward),
                        onTap: () => _onItemTap(item),
                      ),
                    );
                  },
                  separatorBuilder: (context, index) => const Divider(),
                ),
    );
  }
}

void main() {
  runApp(const MaterialApp(
    home: ListViewExample(),
  ));
}
for a in range(1,151):
    for b in range(a,151):
        for c in range(b,151):
            for d in range(c,151):
                for e in range(d,151):
                    if a**5+b**5+c**5+d**5==e**5:
                        print(a+b+c+d+e)
for a in range(1,151):
    for b in range(a,151):
        for c in range(b,151):
            for d in range(c,151):
                for e in range(d,151):
                    if a**5+b**5+c**5+d**5==e**5:
                        print(a+b+c+d+e)
#import the sqlite3 module
import sqlite3

#create a tble
with sqlite3.connect(':memory:') as conn:
  #create a table
  conn.execute('''
    CREATE TABLE point(
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      x INTEGER,
      y INTEGER
      )
    ''')

  #populate table
  conn.executescript('''
    INSERT INTO point (x, y) VALUES (3, 4);
    INSERT INTO point (x, y) VALUES (2, 3);
    INSERT INTO point (x, y) VALUES (-2, 5);
    ''')

  #retrieve data
  cursor = conn.cursor()
  cursor.execute('SELECT x, y FROM point;')

  print(cursor.fetchall())
  cursor.close()
#import the namedtuple factory method
from collections import namedtuple

#create a namedtuple to represent a Point
Point = namedtuple('Point', ['x', 'y'])

#Create objects from the namedtuple 'Point' 
p = Point(3, 4)

#Access the elements using the numeric indices
print(p[0], p[1])

#Access the elements using their names
print(p.x, p.y)
#a list of strings
mylist = ['Python', 'Java', 'C++', 'Ruby']

#remove all elements from the list
mylist.clear()

#the list is now empty
print(mylist)
<script>
	;(function(){

    let chck_if_gsap_loaded = setInterval(function(){
      const eleBuilder = document.querySelector('body').classList.contains("elementor-editor-active");
       if(window.gsap && window.ScrollTrigger && !eleBuilder){
            gsap.registerPlugin(ScrollTrigger);

            hover_card()

            clearInterval(chck_if_gsap_loaded);
        }
    }, 500);

function hover_card() {
  const cardContainers = document.querySelectorAll(".card-container");

  cardContainers.forEach((cardContainer) => {
    let tl = gsap.timeline({ paused: true, timeScale: 0.9 });
    tl.to(cardContainer.querySelector(".card-overlay"), { backgroundColor: "rgba(12, 34, 91, 1)", duration: 0.5 })
      .fromTo(cardContainer.querySelector(".card-headline"), { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.4 }, "-=0.4")
      .fromTo(cardContainer.querySelector(".elementor-divider-separator"),  { width: "100%" }, { width: "100%", opacity: 0, y: 0, duration: 0.2 }, "<")
      .fromTo(cardContainer.querySelector(".card-des"), { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.4 }, "-=0.4")
			.fromTo(cardContainer.querySelector(".card-cat"), { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.4 }, "-=0.4")
      .fromTo(cardContainer.querySelector(".card-btn"), { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.4 });

    cardContainer.addEventListener("mouseenter", () => {
      tl.play();
    });

    cardContainer.addEventListener("mouseleave", () => {
      tl.reverse();
    });
  });
}




})();

</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.0/ScrollTrigger.min.js"></script>
 
nums = [1, 2, 3, 4, 5]
print('before: ')
print(nums)

#call the reverse method()
nums.reverse()

print("after: ")
print(nums)
 
class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(3, 4)
print(f'x: {p.x}')
print(f'y: {p.y}')
 
countries = ['Japan', 'Russia', 'Canada', 'Russsia']

countries.remove('Russia')

print(countries)
 
A = {'a', 'b', 'c', 'd', 'e', 'f'}
B = {'b', 'c', 'd'}

#get the difference
diff = A.difference(B)
print(diff)
#Define the sets
A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
B = {2, 3, 5, 7}

#get the difference using the - operator
diff = A - B
print(diff)
//HTML
<div class="container" *ngIf="messages.length > 0">
  <table class="table table-striped table-hover align-middle">
    <thead class="table-dark">
      <tr>
        <th>#</th>
        <th>Type</th>
        <th>Message</th>
        <th>TimeStamp</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let item of messages; let i = index">
        <td>
          {{i + 1}}
        </td>
        <td>
          {{ item.type }}
        </td>
        <td>
          {{ item.message }}
        </td>
        <td>
          {{ item.dateTimeStamp }}
        </td>
      </tr>
    </tbody>
  </table>
</div>

<!-- Add your code above this point -->

<div id="assistant">
  <button id="assistant-popup-button" (click)="openSupportPopup()">
    Chat Support?
  </button>
  <div id="assistant-popup" [style.display]="isOpen ? 'block' : 'none'">
    <div id="assistant-popup-header">
      Your friendly Assistant
      <button id="assistant-popup-close-button" (click)="openSupportPopup()">
       X
      </button>
    </div>
    <div id="assistant-popup-body">
      <div class="messages" #scrollMe>
        <div *ngFor="let message of messages" class="message">
          <div [class]="message.type">
            {{ message.message }}
          </div>
        </div>
        <div
          *ngIf="loading"
          class="message"
          style="width: 100%; display: block"
        >
          <div [class]="'client'">...</div>
        </div>
      </div>
    </div>
    <form id="assistant-popup-footer" [formGroup]="chatForm">
      <input
        formControlName="message"
        type="text"
        id="assistant-popup-input"
        placeholder="Type your message here..."
      />
      <button
        id="assistant-popup-submit-button"
        [disabled]="!chatForm.valid"
        (click)="sendMessage()">
        Submit
      </button>
    </form>
  </div>
</div>

//TS
import { Component, ViewChild } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { MessageService } from '../service/api.service';
import { DatePipe } from '@angular/common';


export interface Message {
  //Type of the message (e.g., 'user' or 'client')
  type: string;
  //Content of the message
  message: string;
  //Timestamp of when the message was created
  dateTimeStamp: string;
}

@Component({
  selector: 'app-chat-support',       
  templateUrl: './chat-support.component.html',
  styleUrls: ['./chat-support.component.scss'],
})
export class ChatSupportComponent {
  // Indicates if the chat support popup is open
  isOpen = false;
  // Indicates if a message is being sent
  loading = false;
  // Holds the current date and time
  currentDateTime: any
  // Array to hold the chat messages
  messages: Message[] = [];
  chatForm = new FormGroup({
    // Form control for the message input with validation
    message: new FormControl('', [Validators.required]),
  });
  // Reference to the scroll container element
  @ViewChild('scrollMe') private myScrollContainer: any; 

  constructor(private messageService: MessageService, public datepipe: DatePipe) {
    // Constructor to inject necessary services
  }

  openSupportPopup() {
    // Toggles the chat support popup open or closed
    this.isOpen = !this.isOpen;
  }

  sendMessage() {
//Sends the user message and handles response from server
    this.currentDateTime = this.getDateTimeStamp(); // Get the current timestamp
    const sentMessage = this.chatForm.value.message!; // Get the message from the form
    this.loading = true; // Set loading to true while sending the message
    this.messages.push({
      type: 'user', // Mark the message as from the user
      message: sentMessage, // The message content
      dateTimeStamp: this.currentDateTime // Timestamp of the message
    });
    this.chatForm.reset(); // Reset the chat form
    this.scrollToBottom(); // Scroll to the bottom of the chat
    this.messageService.sendMessage(sentMessage).subscribe((response: any) => {
      // Subscribe to the response from the message service
      for (const obj of response) {
        let value;
        if (obj.hasOwnProperty('text')) {
          // Handle text messages
          value = obj['text'];
          this.pushMessage(value);
        }
        if (obj.hasOwnProperty('image')) {
          // Handle image messages
          value = obj['image'];
          this.pushMessage(value);
        }
      }
    });
  }

  pushMessage(message: string) {
    // Adds a client message to the messages array
    this.currentDateTime = this.getDateTimeStamp(); // Get the current timestamp
    this.messages.push({
      type: 'client', // Mark the message as from the client
      message: message, // The message content
      dateTimeStamp: this.currentDateTime // Timestamp of the message
    });
    this.scrollToBottom(); // Scroll to the bottom of the chat
  }

  getDateTimeStamp() {
// Returns current date and time as 'dd/MM/yyyy h:mm:ss'
    return this.datepipe.transform(new Date(), 'dd/MM/yyyy h:mm:ss');
  }

  scrollToBottom() {
    // Scrolls the chat to the bottom
    setTimeout(() => {
      try {
        this.myScrollContainer.nativeElement.scrollTop =
          this.myScrollContainer.nativeElement.scrollHeight + 500;
      } catch (err) {}
    }, 150);
  }
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;

class Listview extends StatefulWidget {
  const Listview({Key? key}) : super(key: key);

  @override
  State<Listview> createState() => _ListviewState();
}

class _ListviewState extends State<Listview> {
  List<Map<String, dynamic>> items = [];

  @override
  void initState() {
    super.initState();
    loadJsonData();
  }

  Future<void> loadJsonData() async {
    final String response = await rootBundle.loadString('assets/Response.json');
    final List<dynamic> data = json.decode(response);
    setState(() {
      items = List<Map<String, dynamic>>.from(data);
    });
  }

  void _onItemTap(Map<String, dynamic> item) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
            'REQUEST STATUS: ${item['REQUEST STATUS']}, RESULT: ${item['RESULT']}'),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('JSON ListView'),
      ),
      body: ListView.separated(
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];
          return Card(
            child: ListTile(
              title: Text(item['REQUEST STATUS']),
              subtitle: Text(item['RESULT']),
              trailing: Icon(Icons.last_page_rounded),
              onTap: () => _onItemTap(item),
            ),
          );
        },
        separatorBuilder: (context, index) => const Divider(),
      ),
    );
  }
}

void main() {
  runApp(const MaterialApp(
    home: Listview(),
  ));
}
//Service
// Service for handling Hero-related API calls
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { map, Observable, Subject } from 'rxjs';
import { Hero } from '../shared/hero';

@Injectable({
  providedIn: 'root'
})
export class HeroService {

  // Base URL for the API
  apiUrl = 'http://localhost:5116/api/'

  // HTTP options with headers
  httpOptions = {
    headers: new HttpHeaders({
      ContentType: 'application/json'
    })
  }

  constructor(private _httpClient: HttpClient) { }

  // Method to get all heroes from the API
  getHeroes(): Observable<Hero[]> {
    return this._httpClient.get<Hero[]>(`${this.apiUrl}Hero/GetAllHeroes`)
    .pipe(map(result => result))
  }

  // Method to get a specific hero by ID from the API
  getHero(heroId: number) {
    return this._httpClient.get(`${this.apiUrl}Hero/GetHero` + "/" + heroId)
    .pipe(map(result => result))
  }
}


//Home page
//HTML
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Home
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  //Display skeleton loading cards if Heroes data is not available -->
  <div *ngIf="!Heroes">
    <ion-card>
      <ion-skeleton-text style="height:200px;" animated></ion-skeleton-text>
      <ion-card-header></ion-card-header>
    </ion-card>

    //Repeated skeleton cards for loading state -->
    <ion-card>
      <ion-skeleton-text style="height:200px;" animated></ion-skeleton-text>
      <ion-card-header></ion-card-header>
    </ion-card>

    <ion-card>
      <ion-skeleton-text style="height:200px;" animated></ion-skeleton-text>
      <ion-card-header></ion-card-header>
    </ion-card>

    <ion-card>
      <ion-skeleton-text style="height:200px;" animated></ion-skeleton-text>
      <ion-card-header>
        
      </ion-card-header>
    </ion-card>
  </div>

  //Pull-to-refresh functionality -->
  <ion-refresher slot="fixed" (ionRefresh)="refreshHeroes($event)">
    <ion-refresher-content refreshingText="Loading Heroes..."></ion-refresher-content>
  </ion-refresher>
  
  //Display hero cards when Heroes data is available -->
  <ion-card button *ngFor="let hero of (Heroes | async)" [routerLink]="['hero-detail', hero.heroId]">
    <ion-img [src]="hero.imageBase64"></ion-img>
  </ion-card>
</ion-content>

//TS
import { Component } from '@angular/core';
import { IonicModule, ToastController } from '@ionic/angular';
import { ExploreContainerComponent } from '../explore-container/explore-container.component';
import { Hero } from '../shared/hero';
import { HeroService } from '../services/hero.service';
import { AppModule } from '../app.module';
import { CommonModule } from '@angular/common';
import { Observable } from 'rxjs';
import { RouterLink } from '@angular/router';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss'],
  standalone: true,
  imports: [IonicModule, ExploreContainerComponent, AppModule, CommonModule, RouterLink],
})
export class Tab1Page {
  // Observable to hold the list of heroes
  Heroes: Observable<Hero[]>;

  constructor(private _toastController: ToastController, private _heroService: HeroService) {
    // Fetching heroes from the service
    this.Heroes = this._heroService.getHeroes();
  }

  ngOnInit() { }

  // Method to refresh the list of heroes
  refreshHeroes(event:any){
    this.Heroes = this._heroService.getHeroes();

    // Complete the refresh event
    event.target.complete();
    
    // Show a toast notification
    const toast = this._toastController.create({
      message: "Heroes are refreshed",
      duration: 3000,
      position: "bottom"
    })

    toast.then((toastMessage) => {
      toastMessage.present();
    })
  }
}



//hero detail page
//HTML
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-buttons slot="start">
      <ion-back-button></ion-back-button>
    </ion-buttons>
    <ion-title></ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  //Display hero image -->
  <ion-img src={{heroDetail?.imageBase64}}></ion-img>
  
  //Hero details card -->
  <ion-card no-margin>
    <ion-card-header>
      <ion-card-title>
        {{heroDetail?.name}}
      </ion-card-title>
    </ion-card-header>
  </ion-card>

  <ion-card>
    <ion-list lines="none">

      //Display hero's age -->
      <ion-item>
        <ion-label>Age</ion-label>
        <ion-chip color="primary">{{heroDetail?.age}}</ion-chip>
      </ion-item>

      //Display hero's height -->
      <ion-item>
        <ion-label>Height</ion-label>
        <ion-chip color="secondary">{{heroDetail?.height}}</ion-chip>
      </ion-item>

      //Display hero's birthday -->
      <ion-item>
        <ion-label>Birthday</ion-label>
        <ion-chip>{{heroDetail?.birthday}}</ion-chip>
      </ion-item>

    </ion-list>
  </ion-card>

  //Floating action button to open modal for hero status -->
  <ion-fab vertical="top" horizontal="end" slot="fixed">
    <ion-fab-button (click)="openModal(heroDetail?.isAlive)">
      <ion-icon name="eye"></ion-icon>
    </ion-fab-button>
  </ion-fab>
</ion-content>

//TS
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule, ModalController, ToastController } from '@ionic/angular';
import { HeroService } from '../services/hero.service';
import { ActivatedRoute } from '@angular/router';
import { HerostatusPage } from '../herostatus/herostatus.page';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.page.html',
  styleUrls: ['./hero-detail.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule]
})
export class HeroDetailPage implements OnInit {
  // Variable to hold the hero details
  heroDetail: any;

  constructor(
    private _toastController: ToastController, 
    private _heroService: HeroService, 
    private _modal: ModalController, 
    private route: ActivatedRoute
  ) {
    // Fetch the hero details based on the hero ID from the route parameters
    this._heroService.getHero(+this.route.snapshot.params['heroId']).subscribe(result => {
      this.heroDetail = result 
      
      // Show a toast notification
      const toast = this._toastController.create({
        message: "Hero " + this.heroDetail.name + " is viewable",
        duration: 3000,
        position: "bottom"
      })

      toast.then((toastMessage) => {
        toastMessage.present();
      })
    })
  }

  ngOnInit(): void { }

  // Method to open a modal showing the hero's status (alive or dead)
  async openModal(status: boolean) {
    const statusModal = await this._modal.create({
      component: HerostatusPage,
      componentProps: {
        value: status
      }
    })

    return await statusModal.present()
  }
}

//Hero status page
//HTML
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>Hero Status</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-fab vertical="center" horizontal="center">
    <ion-fab-button *ngIf="value"> 
      <ion-icon name="happy-outline" *ngIf="value"> </ion-icon>
      Alive
    </ion-fab-button>
    <ion-fab-button *ngIf="!value"> 
      <ion-icon name="sad-outline" *ngIf="!value"></ion-icon>
      Dead
    </ion-fab-button>
  </ion-fab>

 <ion-button (click)="closeModal()" class="container" color="danger">
  <ion-icon name="close-circle-outline" size="large"></ion-icon>
 </ion-button>
</ion-content>

//TS
import { Component, Input, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule, ModalController } from '@ionic/angular';

@Component({
  selector: 'app-herostatus',
  templateUrl: './herostatus.page.html',
  styleUrls: ['./herostatus.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule]
})
export class HerostatusPage implements OnInit {
  // Input property to receive the hero's status (alive or dead)
  @Input() value: any;

  constructor(private _modal: ModalController) { }

  ngOnInit() { }

  // Method to close the modal
  closeModal() {
    this._modal.dismiss()
  }
}
//HTML
<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title mode="md"> 
      <!-- md=material design -->
     <span>Home</span> 
     <ion-icon name="chevron-down-outline"></ion-icon>
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="borderBottom">
  <swiper-container [modules]="swiperModules"
  [slidesPerView]="1.2"
  [CenteredSlides]="true"
  [autoplay]="true"
  [pagination]="{clickable:true, dynamicBullets: true}"
  [spaceBetween]="20">
    
    <swiper-slide>
      <img src="assets/jollof1.jpeg"></swiper-slide>
    <swiper-slide>
      <img src="assets/Shisayanma.jpg">
    </swiper-slide>
    <swiper-slide>
      <img src="assets/Briyani.jpeg">
    </swiper-slide>
    
  </swiper-container>
</div>

<ion-list>
  <ion-list-header class="ion-margin-bottom">
    <ion-label>
      <h4>Restaurants Nearby</h4>
      <p>Explore exclusive flavors available near you</p>
    </ion-label>
  </ion-list-header>
  <ion-item lines="none">
    <ion-thumbnail slot="start">
      <img src="assets/jollof1.jpeg" />
    </ion-thumbnail>
    <ion-label>
      <h4>Jollof of Africa</h4>
      <ion-text color="medium">
        <p class="pStyle">
         African Cuisine
        </p>
      </ion-text>
      <span>
        5
        <ion-icon name="star"></ion-icon>
        .
      </span>
      25 mins . R100 for two
      <ion-text color="tertiary">
        <p class="distance">
          2.59 kms away
        </p>
      </ion-text>
    </ion-label>
  </ion-item>

  <ion-item lines="none">
    <ion-thumbnail slot="start">
      <img src="assets/Shisayanma.jpg" />
    </ion-thumbnail>
    <ion-label>
      <h4>Ayoba Cafe Shisanyama</h4>
      <ion-text color="medium">
        <p class="pStyle">
         African Cuisine
        </p>
      </ion-text>
      <span>
        4.4
        <ion-icon name="star"></ion-icon>
        .
      </span>
      15 mins . R120 
      <ion-text color="tertiary">
        <p class="distance">
          1.83 kms away
        </p>
      </ion-text>
    </ion-label>
  </ion-item>

  <ion-item lines="none">
    <ion-thumbnail slot="start">
      <img src="assets/Briyani.jpeg" />
    </ion-thumbnail>
    <ion-label>
      <h4>Spice-The Indian Kitchen</h4>
      <ion-text color="medium">
        <p class="pStyle">
         Asian Cuisine
        </p>
      </ion-text>
      <span>
        4.1
        <ion-icon name="star"></ion-icon>
        .
      </span>
      5 mins . R80 
      <ion-text color="tertiary">
        <p class="distance">
          0.9 km away
        </p>
      </ion-text>
    </ion-label>
  </ion-item>
</ion-list>
</ion-content>

//TS
import { Component, OnInit } from '@angular/core';
import { IonicSlides } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
  
  swiperModules = [IonicSlides];
  constructor() { }

  ngOnInit() {
  }
}
//Services
//FakeSubscriptionDataService
import { Injectable } from "@angular/core";
import { Subscription } from "../tabs/Model/subscriptionModel";


@Injectable({
    providedIn: 'root'
})
export class FakeSubscriptionDataService {
    subscriptions : Subscription[];

    constructor () {
        this.subscriptions = [
            {
              id: 1,
              name: "Netflix",
              description:  "At Netflix, we want to entertain the world. Whatever your taste, and no matter where you live, we give you access to best-in-class TV series, documentaries, feature films and mobile games.",
              price : 199
            },
            {
              id: 2,
              name: "Showmax",
              description: "Showmax is an internet TV service. What sets Showmax apart is a unique combination of hit African content, first and exclusive international series, movies, the best kids’ shows, and live sport.",
              price : 349
            },
            {
              id: 3,
              name: "Amazon Prime Video",
              description: "Amazon Prime Video, or simply Prime Video, is an American subscription video on-demand over-the-top streaming and rental service of Amazon offered as a standalone service or as part of Amazon's Prime subscription.",
              price : 79
            },
            {
              id: 4,
              name: "Hulu",
              description: "Hulu is an American subscription streaming service majority-owned by The Walt Disney Company, with Comcast's NBCUniversal holding a minority stake that is pending sale to Disney; which will make Hulu into a wholly owned subsidiary of Disney.",
              price : 225
            },
            {
              id: 5,
              name: "Disney+",
              description: "Disney+ is an American subscription video on-demand over-the-top streaming service owned and operated by the Disney Entertainment division of The Walt Disney Company.",
              price : 119
            },
          ];
    }

    getOfferedSubscriptions () {
        return this.subscriptions;
    }
}
//SubscriptionCartOrganiserService
import { Injectable } from "@angular/core";
import { Subject } from "rxjs";
import { Subscription } from "../tabs/Model/subscriptionModel";
import { CartSubScription } from "../tabs/Model/cartSubscription";


@Injectable({
    providedIn: 'root'
})
export class SubscriptionCartOrganiserService {
    static tmpSubscriptionsCartName : string = "ls-cart-subscriptions";
    cartProductsNumberDS = new Subject<number>();
    cartItemsOrderName : string = "Subs Order @ ";

    notifyOnNewItemInCart() {
        this.cartProductsNumberDS.next(this.getNumberOfItemsInCart());
    }

    getLocalStorageSubscriptions(): Subscription[] {
        let storedSubString = localStorage.getItem(SubscriptionCartOrganiserService.tmpSubscriptionsCartName)
        let cartSubscriptions = [];
        if (storedSubString) {
          cartSubscriptions = JSON.parse(storedSubString)
        }
        return cartSubscriptions;
    }
    getNumberOfItemsInCart() : number {
        return this.getLocalStorageSubscriptions().length
    }

    getSubscriptionsInCart() : CartSubScription[] {
        let localStorageSubs = this.getLocalStorageSubscriptions();
        let cartSubscriptions : CartSubScription[] = [];

        let subCounts = new Map<Number, Number>(); //temporary storage
        localStorageSubs.forEach(sub => {
            if (!subCounts.has(sub.id)) {
                let count = localStorageSubs.filter(currSub => currSub.id == sub.id).length;
                subCounts.set(sub.id, count)
                let cartSub = new CartSubScription(sub, count);
                cartSubscriptions.push(cartSub);
            }
        });
        return cartSubscriptions;
    }

    getTotalCostOfSubcriptionsInCart() : number {
        let totalCost = 0;
        
        let cartSubs = this.getSubscriptionsInCart();
        cartSubs.forEach(cartSub => {
            totalCost += (cartSub.subscription.price * cartSub.quantity);
        });

        return totalCost;
    }

    getCartOrderName() {
        return this.cartItemsOrderName + Date.now();
    }

    addSubscriptionToCart(product : Subscription) {
        let storedSubString = localStorage.getItem(SubscriptionCartOrganiserService.tmpSubscriptionsCartName)
    
        let cartSubscriptions = [];
        if (storedSubString) {
          cartSubscriptions = JSON.parse(storedSubString)
        }
        cartSubscriptions.push(product);
        localStorage.setItem(SubscriptionCartOrganiserService.tmpSubscriptionsCartName, JSON.stringify(cartSubscriptions))
    
        this.notifyOnNewItemInCart();
      }
    

    removeProdFromCart(subscr : Subscription) {
        let storedSubString = localStorage.getItem(SubscriptionCartOrganiserService.tmpSubscriptionsCartName)
    
        let cartSubscriptions = [];
        if (storedSubString) {
          cartSubscriptions = JSON.parse(storedSubString)
        }
        for (var idx = 0; idx < cartSubscriptions.length; idx++) {
            if (cartSubscriptions[idx].id == subscr.id) {
                cartSubscriptions.splice(idx, 1);
                break;
            }
        }

        localStorage.setItem(SubscriptionCartOrganiserService.tmpSubscriptionsCartName, JSON.stringify(cartSubscriptions))

        this.notifyOnNewItemInCart();
    }

    addProdFromCart(subscr : Subscription) {
        this.addSubscriptionToCart(subscr);
        this.notifyOnNewItemInCart();   
    }

    clearCart () {
        localStorage.removeItem(SubscriptionCartOrganiserService.tmpSubscriptionsCartName);
        this.notifyOnNewItemInCart();
    }
}
//HTML
<ion-header>
  <ion-toolbar>
    <ion-searchbar
      #searchInput      
      placeholder="Search Resturant Name" 
      (ionInput)="onSearchChange($event)" 
      [(ngModel)]="query"
      ></ion-searchbar>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-list>
    <ion-list-header *ngIf="!isLoading && query && restaurants.length > 0">
      <ion-label>
        <h4>Search results for "{{query}}"</h4>
      </ion-label>
    </ion-list-header>
    <ion-item lines="none" *ngFor="let restaurant of restaurants" 
    [routerLink]="['/', 'tabs', 'restaurants', restaurant.uid]">
      <ion-thumbnail slot="start">
        <img [src]="restaurant?.cover ? restaurant.cover : 'assets/imgs/1.jpeg'" />
      </ion-thumbnail>
      <ion-label>
        <h4>{{restaurant?.name}}</h4>
        <ion-text color="medium">
          <p class="pStyle">
            {{getCuisine(restaurant?.cuisines)}}
          </p>
        </ion-text>
        <span>
          <ion-icon name="star"></ion-icon>
          {{restaurant?.rating}} .
        </span>
        {{restaurant?.delivery_time}} mins . R{{restaurant?.price}}
        <ion-text color="tertiary" *ngIf="restaurant?.distance && restaurant?.distance != 0">
          <p class="distance">
            {{restaurant?.distance | number: '0.0-2'}} kms away
          </p>
        </ion-text>
      </ion-label>
    </ion-item>
  </ion-list>
</ion-content>

//TS
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { Restaurant } from 'src/app/models/restaurant.model';
import { DataService } from 'src/app/services/data/data.service';

@Component({
  selector: 'app-search',
  templateUrl: './search.page.html',
  styleUrls: ['./search.page.scss'],
})
export class SearchPage implements OnInit {

  @Input() restaurant: Restaurant
  @ViewChild('searchInput') Input;
  isLoading: boolean;
  query: any;
  allPlaces: Restaurant[] = [];
  restaurants: Restaurant[] = [];

  constructor(private data: DataService) { }

  ngOnInit() {
    this.allPlaces = this.data.allPlaces;
    this.restaurants = this.allPlaces;
  }

  getCuisine(cuisine) {
    return cuisine.join(', ');
  }

  async onSearchChange(event) {
    this.query = event.detail.value.toLowerCase();
    this.restaurants = [];
    if(this.query.length > 0) {
      this.restaurants = await this.allPlaces.filter((element: any) => {
        return element.name.toLowerCase().includes(this.query);
      });
    }
    else{
      this.restaurants = this.allPlaces;
    };
  }
}
//HTML
<ion-header>
  <ion-toolbar mode="md">
    <ion-title>
      <span>Home</span>
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  
  <div class="borderBottom">
    <swiper-container [modules]="swiperModules"
    [slidesPerView]="1.2"
    [CenteredSlides]="true"
    [autoplay]="true"
    [pagination]="{clickable:true, dynamicBullets: true}"
    [spaceBetween]="20">
      
      <swiper-slide>
        <img src="assets/imgs/1.jpeg" style="width: 100%; height: 100%;">
      </swiper-slide>
      <swiper-slide>
        <img src="assets/imgs/2.jpeg" style="width: 100%; height: 100%;">
      </swiper-slide>
      <swiper-slide>
        <img src="assets/imgs/3.jpeg" style="width: 100%; height: 100%;">
      </swiper-slide>
      <swiper-slide>
        <img src="assets/imgs/4.jpeg" style="width: 100%; height: 100%;">
      </swiper-slide>
    </swiper-container>
  </div>

  <ion-list>
    <ion-list-header class="ion-margin-bottom">
      <ion-label>
        <h4>Restaurants Nearby</h4>
        <p>Explore distinctive flavors in your vicinity</p>
      </ion-label>
    </ion-list-header>
    <ion-item-group>
      <ion-item lines="none" *ngFor="let restaurant of restaurants" 
      [routerLink]="['/', 'tabs', 'restaurants', restaurant.uid]">
        <ion-thumbnail slot="start">
          <img [src]="restaurant?.cover ? restaurant.cover : 'assets/imgs/1.jpeg'" />
        </ion-thumbnail>
        <ion-label>
          <h4>{{restaurant?.name}}</h4>
          <ion-text color="medium">
            <p class="pStyle">
              {{getCuisine(restaurant?.cuisines)}}
            </p>
          </ion-text>
          <span>
            <ion-icon name="star"></ion-icon>
            {{restaurant?.rating}} .
          </span>
          {{restaurant?.delivery_time}} mins . R{{restaurant?.price}}
          <ion-text color="tertiary" *ngIf="restaurant?.distance && restaurant?.distance != 0">
            <p class="distance">
              {{restaurant?.distance | number: '0.0-2'}} kms away
            </p>
          </ion-text>
        </ion-label>
      </ion-item>
    </ion-item-group>
  </ion-list>
</ion-content>

//TS
import { Component, Input, OnInit } from '@angular/core';
import { IonicSlides } from '@ionic/angular';
import { Restaurant } from 'src/app/models/restaurant.model';
import { DataService } from 'src/app/services/data/data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.page.html',
  styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {

  swiperModules = [IonicSlides];
  @Input() restaurant: Restaurant
  restaurants: Restaurant[] = [];

  constructor(
    private data: DataService
  ) { }

  ngOnInit() {
      this.restaurants = this.data.restaurants;
  }

  getCuisine(cuisine) {
    return cuisine.join(', ');
  }
}
//HTML
<ion-tabs>
  <ion-tab-bar slot="bottom">
    <ion-tab-button tab="home">
      <ion-icon name="home-outline"></ion-icon>
      <ion-label>Home</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="search">
      <ion-icon name="search-outline"></ion-icon>
      <ion-label>Search</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="cart">
      <ion-icon name="cart-outline"></ion-icon>
      <ion-label>Cart</ion-label>
    </ion-tab-button>

    <ion-tab-button tab="account">
      <ion-icon name="person-outline"></ion-icon>
      <ion-label>Account</ion-label>
    </ion-tab-button>
  </ion-tab-bar>
</ion-tabs>

//TS
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { TabsPage } from './tabs.page';

const routes: Routes = [
  {
    path: '',
    component: TabsPage,
    children: [
      {
        path: 'home',
        loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
      },
      {
        path: 'search',
        loadChildren: () => import('./search/search.module').then( m => m.SearchPageModule)
      },
      {
        path: 'cart',
        loadChildren: () => import('./cart/cart.module').then( m => m.CartPageModule)
      },
      {
        path: 'account',
        loadChildren: () => import('./account/account.module').then( m => m.AccountPageModule)
      },
      {
        path: '',
        redirectTo: '/tabs/home',
        pathMatch: 'full'
      }
    ]
  },
  {
    path: 'restaurants/:restaurantId',
    loadChildren: () => import('./items/items.module').then( m => m.ItemsPageModule)
  },
  {
    path: 'profile',
    loadChildren: () => import('./profile/profile.module').then( m => m.ProfilePageModule)
  },
  
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class TabsPageRoutingModule {}
star

Wed Jun 19 2024 08:09:21 GMT+0000 (Coordinated Universal Time) https://www.reddit.com/r/commandline/comments/17beywz/parse_through_all_subdirectories_and_run_a_exe_on/?rdt

@baamn #batch #file #trid

star

Wed Jun 19 2024 08:07:51 GMT+0000 (Coordinated Universal Time)

@mebean #flutter #laravel #api #http

star

Wed Jun 19 2024 08:05:14 GMT+0000 (Coordinated Universal Time) https://mark0.net/forum/index.php?topic

@baamn #trid #batch #windows #files #extention

star

Wed Jun 19 2024 07:08:07 GMT+0000 (Coordinated Universal Time) https://mdbootstrap.com/docs/standard/utilities/close-button/

@ravinyse #html

star

Wed Jun 19 2024 06:32:24 GMT+0000 (Coordinated Universal Time)

@Xeno_SSY #c++

star

Wed Jun 19 2024 03:05:02 GMT+0000 (Coordinated Universal Time)

@Xeno_SSY #c++

star

Wed Jun 19 2024 02:54:51 GMT+0000 (Coordinated Universal Time)

@davidmchale #this #arrow #functions

star

Wed Jun 19 2024 01:28:07 GMT+0000 (Coordinated Universal Time)

@pvignesh

star

Wed Jun 19 2024 01:06:04 GMT+0000 (Coordinated Universal Time)

@davidmchale #this #object #method #borrowing

star

Tue Jun 18 2024 23:15:03 GMT+0000 (Coordinated Universal Time) https://snprotips.com/blog/2024/how-to-identify-a-duplicate-record-by-multiple-fields-in-servicenow

@RahmanM

star

Tue Jun 18 2024 23:14:51 GMT+0000 (Coordinated Universal Time) https://snprotips.com/blog/2024/how-to-identify-a-duplicate-record-by-multiple-fields-in-servicenow

@RahmanM

star

Tue Jun 18 2024 22:53:59 GMT+0000 (Coordinated Universal Time)

@iyan #java

star

Tue Jun 18 2024 22:39:08 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 22:34:57 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/how-to-use-asyncio-in-python/

@pynerds #python

star

Tue Jun 18 2024 22:01:31 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 21:50:19 GMT+0000 (Coordinated Universal Time) https://rdrr.io/snippets/

@jkirangw

star

Tue Jun 18 2024 21:41:43 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 21:36:14 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 21:35:16 GMT+0000 (Coordinated Universal Time) https://rdrr.io/snippets/

@jkirangw

star

Tue Jun 18 2024 21:32:38 GMT+0000 (Coordinated Universal Time) https://rdrr.io/snippets/

@jkirangw

star

Tue Jun 18 2024 20:35:44 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 20:14:43 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 20:13:34 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 20:13:01 GMT+0000 (Coordinated Universal Time)

@madgakantara

star

Tue Jun 18 2024 19:20:48 GMT+0000 (Coordinated Universal Time)

@mehran

star

Tue Jun 18 2024 19:05:00 GMT+0000 (Coordinated Universal Time)

@mehran

star

Tue Jun 18 2024 17:34:05 GMT+0000 (Coordinated Universal Time) https://www.cyberforum.ru/python-tasks/thread2934310.html

@qwdixq

star

Tue Jun 18 2024 17:33:36 GMT+0000 (Coordinated Universal Time) https://www.cyberforum.ru/python-tasks/thread2934310.html

@qwdixq

star

Tue Jun 18 2024 16:58:47 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/sqlite3-in-memory-databases-python/

@pynerds #python

star

Tue Jun 18 2024 16:57:24 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/python-collections-namedtuple/

@pynerds #python

star

Tue Jun 18 2024 16:56:13 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/list-clear-method-in-python/

@pynerds #python

star

Tue Jun 18 2024 16:55:24 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=VuQtX0Iu-Cw

@Fudgiebars

star

Tue Jun 18 2024 16:47:43 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/reverse-a-list-in-python/

@pynerds #python

star

Tue Jun 18 2024 16:44:52 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/slots-variable-in-python-classes/

@pynerds #python

star

Tue Jun 18 2024 16:42:37 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/remove-element-from-a-list-in-python/

@pynerds #python

star

Tue Jun 18 2024 16:41:39 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/set-difference-method-in-python/

@pynerds #python

star

Tue Jun 18 2024 16:40:55 GMT+0000 (Coordinated Universal Time) https://www.pynerds.com/set-difference-method-in-python/

@pynerds #python

star

Tue Jun 18 2024 15:58:49 GMT+0000 (Coordinated Universal Time) https://github.com/fandogh/nuxt-helpers

@icarolordes

star

Tue Jun 18 2024 15:58:24 GMT+0000 (Coordinated Universal Time) https://github.com/DerianAndre/Nuxt.js-Bootstrap-5-Boilerplate

@icarolordes #nuxt.js-bootstrap5

star

Tue Jun 18 2024 15:14:24 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jun 18 2024 15:09:56 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=1OEhIpBIZXM

@mehran

star

Tue Jun 18 2024 13:33:03 GMT+0000 (Coordinated Universal Time) https://maticz.com/hospital-management-software

@carolinemax

star

Tue Jun 18 2024 11:43:37 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jun 18 2024 11:22:00 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jun 18 2024 11:13:05 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jun 18 2024 11:02:44 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jun 18 2024 10:48:59 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jun 18 2024 10:46:45 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension