MIPS
Write a program that asks the user to enter an unsigned number and read it. Then swap the bits at odd positions with those at even positions and display the resulting number. For example, if the user enters the number 9, which has binary representation of 1001, then bit 0 is swapped
with bit 1, and bit 2 is swapped with bit 3, resulting in the binary number 0110. Thus, the
program should display 6.
In: Computer Science
In Python 3.6
Question 1 for strings
a) Write a function named longest_common_prefix that takes two strings and returns the longest common prefix of the two strings. For example, the longest common prefix of distance and disinfection is dis. If the two strings have no common longest common prefix, the method returns an empty string.
b) Write a function named reverse that takes a string argument and returns its reverse. For example, reverse(‘I am testing’) should return the string ‘gnitset ma I’. Use iteration for this and answers using slicing will not be accepted. Imma like... what.
c) Write a function named check_password that checks whether a string is a valid password. Return True if it is a valid password and False otherwise. The password rules are as follows:
• A password must have at least 8 characters.
• A password must consist of only letters and digits.
• A password must contain at least two digits.
In: Computer Science
Java
1. Program Specification
This will focus on strengthening your skills with manipulating Strings. The String class provides many useful methods, in which this assignment will give you further practice with. You will read in dates in a variety of different formats, parse the dates, and then print them out in a converted format. The dates will be entered in one line by the user, and they will be separated by the word “and”.
2. Date formats
Your program will parse a line of dates written in three styles: day first, month first, and all-numbers.
Day first: The day of the month is first, followed by the month, followed by the year. The month string must be at least 3 letters long, and can be a mix of upper and lowercase letters. Spaces should separate the three parts. Spaces are not allowed between numbers or month names.
ex: 8 Aug 2015
24 February 1988
Month first: The month is first, followed by the day, a comma, then the year. The month may be fully spelled out or an abbreviation at least 3 letters long and be upper or lower case. A space must separate the month and day, but there may be multiple spaces between the two.
ex: March 15, 1967
Jan 17, 1990
All numbers: Month, day, and year are entered as numbers with dashes between them. There may be many spaces around the dashes or none. Spaces are not allowed between the numbers.
ex: 12-4-2008
1-8-2003
3. Requirements
Your program must read a single line that may contain many dates in many formats separated by the word “and”. It will parse out the dates, and print them all in the correct format. The correct format is day first, a space, followed by the full name of the month with the first letter capitalized, a space, and then the year.
Your program must give an error message if a date is invalid. It should give a specific error message for the following cases:
o A month name or abbreviation is misspelled or too short (less
than three characters)
o A day or month number is incorrect. Months must be between 1 and
12. Days must be
valid for the month (ignore leap years)
o A year number is too low or high (1900 to 2019). o There are too
many dashes in All Numbers format.
It is ok if your program crashes when calling Integer.parseInt and the argument is not valid.
4. Implementation
There are some specific requirements for how you write the program.
Use the below build-in methods
o String class: substring, trim, split, toLowerCase, indexOf, or
lasIndexOf o Integer class: parseInt
In the main() method, you must prompt the user to enter the dates, read the line of dates, break the line into separate Strings based on the delimiter (“and”), and for each date print “Date : ”. You must also call the appropriate parser here.
One method for parsing each kind of date. These methods either output an error message or the corresponding standard date string.
o public static void parseDayFirst(String dateStr)
o public static void parseMonthFirst(String dateStr) o public
static void parseAllNumbers(String dateStr)
public static boolean isValidMonthDay(int day, int
month)
o returns true if the month and day numbers form a valid day of the
year (leap years
excluded)
public static int monthToNumber(String monthStr)
o Takes a string that should be the name or abbreviation of the
month name and returns
the number of the month. It returns zero if the name doesn’t match any month or is too short. This method is provided for you.
public static boolean isValidMonthAbbr(String month)
Takes a month as a String and returns boolean value. True means the
passed in month string represents a valid month string (the length
of the trimmed month string is greater than or equals 3, and the
month string abbreviation is correctly spelled!!!).
Hint: indexOf along with the provided static String array fullNameMonths declared at
the top of the class may be useful here for. public static boolean isValidYear(int year)
o returns true if the year is valid (1900 to 2018)
public static String standardDateString(int day, int month,
int year)
o takes a day, month, and year as numbers and returns a String
containing the date in the
correct format, Day Month Year. (ex. 13 March 2006)
5. Sample Output
Welcome to the Date Converter!
Enter line of dates:8 Aug 2015 and March 15, 1967 and 12-4-2008
Date 1: 8 August 2015
Date 2: 15 March 1967
Date 3: 4 December 2008
Goodbye!
Welcome to the Date Converter!
Enter line of dates:15 xyz 2000 and Date 1: ERROR: Invalid month string Date 2: ERROR: Too many dashes Date 3: ERROR: Invalid month string Date 4: ERROR: Invalid month or day number
Goodbye!
Welcome to the Date Converter!
Enter line of dates: ERROR: Empty input line
Goodbye!
Welcome to the Date Converter!
Enter line of dates:and 2-0-2222 and Jan 13, 1190 and March
12,2222 and 9 Date 1: ERROR: No date entered
Date 2: ERROR: Invalid month or day number
Date 3: ERROR: Invalid Year-too low or hi
Date 4: ERROR: Invalid Year-too low or hi Date 5: 9 September 2018
Goodbye!
2-2-22222-and J 10, 2004 andFeb 45 , 2012
- 9-2018
------------------------------------------
Code Provided
package cs251_HW2;
import java.util.Scanner;
public class DateConversion {
//Static variable you can use throughout this class
//contains the months in shorter form
private static String[] abbrMonths = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep",
"oct", "nov", "dec" };
//Another static variable you can use, except these contain the months fully spelled out
private static String[] fullNameMonths = { "january", "february", "march", "april", "may", "june", "july", "august", "september",
"october", "november", "december" };
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("Welcome to the CS251 Date Converter!\n");
System.out.print("Enter line of dates:");
String dateEntries = stdIn.nextLine();
//TODO
System.out.println("\nGoodbye!");
stdIn.close();
}
public static void parseDayFirst(String dateStr) {
//TODO
}
public static void parseMonthFirst(String dateStr) {
//TODO
}
public static void parseAllNumbers(String dateStr) {
//TODO
}
public static boolean isValidMonthDay(int day, int month) {
//TODO
}
public static int monthToNumber(String monthStr) {
String lowerCaseMonthStr = monthStr.toLowerCase().substring(0, 3);
int mNumber = 0;
for(int i = 0; i < abbrMonths.length; i++){
if(abbrMonths[i].equals(lowerCaseMonthStr)){
mNumber = i + 1;
break;
}
}
return mNumber;
}
public static boolean isValidMonthAbbr(String str) {
//TODO
}
public static boolean isValidYear(int year) {
//TODO
}
public static String standardDateString(int d, int m, int y) {
//TODO
}
}
In: Computer Science
Unit 09 Drop Box Assignment
ONLY ONE FILE may be turned in for the assignment. If you make a
mistake and need to turn
in your work again, you may do so. I will only grade the latest
file you turn in. The older ones
will be ignored. For instruction on How To do assignments and
create the file see the "How To
Do Homework" document under the "Start Here" button.
The Assignment
Create a Visual Logic flow chart with four methods. Main method
will create an array of 5
elements, then it will call a read method, a sort method and a
print method passing the array
to each. The read method will prompt the user to enter 5 numbers
that will be stored in the
array. The sort method will sort the array in ascending order
(smallest to largest). The print
method will print out the array.
A sample run might look like this:
Please enter a number: 2
Please enter a number: 7
Please enter a number: 1
Please enter a number: 10
Please enter a number: 3
Your numbers are: 1, 2, 3, 7, 10
In: Computer Science
create database shop;
use shop;
create table users(
id int null auto_increment,
firstname varchar(255),
lastname varchar(255) not null,
primary key (id)
);
create table products(
id int null auto_increment,
name varchar(255),
price float,
primary key (id)
);
create table orders(
id_users int not null,
id_items int not null,
primary key (id_users,id_items),
foreign key (id_users) references users(id),
foreign key (id_items) references items(id)
);
write three SQL queries to answer the following questions
1.- Products in the shop catalog; product name.
2.- List of products in stock (not sold); product name, code,
price.
3.- Products sold in the shop; product name, code, price and full
name of buyer.
Concepts in practice: Relational Databases, SQL.
In: Computer Science
java
declare at least five different types of arrays, one, two and three-dimension.
In: Computer Science
For this assignment, you will apply what you learned in analyzing a simple Java™ program by writing your own Java™ program. The Java™ program you write should do the following:
Complete this assignment by doing the following:
/************************************************************************************
* Program: PRG/420 Week 5
* Purpose: Week 5 Coding Assignment
* Programmer: TYPE YOUR NAME HERE
* Class: PRG/420
* Creation Date: TYPE TODAY'S DATE HERE
*************************************************************************************
* Program Summary:
* This program converts a given date to a string.
* The code includes exception handling for a
ParseException.
************************************************************************************/
package prg420week5_codingassignment;
import java.util.*; // wildcard to import all the util.
classes
import java.text.*; // wildcard to import all the text classes
public class PRG420Week5_CodingAssignment {
public static void main(String[] args){
// The getInstance() method returns a Calendar object whose
calendar fields have been initialized with the current date and
time.
Calendar calendar = Calendar.getInstance(); {
LINE 1. BEGIN THE TRY BLOCK.
String str_date="01-Nov-17"; // Declare a string that we will use
later to format a date like this: ##-XXX-##
DateFormat formatter; // Declare an object of type DateFormat so
that we can call its parse() method later
Date myFormattedDate; // Declare a variable of type Date to hold
the formatted date
formatter = new SimpleDateFormat("dd-MMM-yy"); // Assign a specific
date format to the formatter variable
// The given date is taken as a string that is converted into a
date type by using
// the parse() method
myFormattedDate = (Date)formatter.parse(str_date);
// setting up the format
System.out.println("The formatted date is " +
myFormattedDate);
System.out.println("Today is " +calendar.getTime() );
LINE 2. WRITE THE CATCH BLOCK TO CATCH EXCEPTIONS OF TYPE
ParseException (TO HANDLE EXCEPTION, SIMPLY PRINT THE
EXCEPTION)
}
}
}
In: Computer Science
1. Explain why a transaction may have many cursors. Also, how is it possible that a transaction may have more than one cursor on a given table? Support your answer with example.
2. After a DBMS has been selected, what is the DBA’s role in DBMS maintenance?
3. Do you think, splitting a table might improve performance? Why/why not.
In: Computer Science
Python Script:
Question: Please edit my script for it to get to the right directory and/or folder. How to get the right files in the folder to display under files. I don't want anymore errors. Thanks-
#Program to combine multiple excel file into one master file/spreadsheet
#import library
import os
import pandas as pd
cwd = os.path.abspath(")
files = os.listdir(cwd)
#Combine multiple excel files
#This blocks of code will loop through files in directory/folder
and append/merge .xlsx files
df = pd.DataFrame()
for file in files:
if file.endswith('.xlsx'):
df =
df.append(pd.read_excel(file),ignore_index=True
#Display first 5 rows of data/records
df.head()
#Display total columns and rows
df.shape()
df.to_excel('Output.xlsx')
In: Computer Science
Exercise 1 – Calculating factorial (n!)
Design a function calledget_factorial that takes an integer n as a parameter, and returns n!.
Note #1: 0! = 1:
Note #2: n! is calculated by the following formula: ?! = ? ∗ (? − 1)! ?? ????h?? ???? ?? ??????? ??: ?! = ? ∗ (? − 1) ∗ (? − 2) ∗ ... ∗ 3 ∗ 2 ∗ 1
Exercise 2 – Counting the number of occurrences a letter is found in a phrase
Design a function called get_occurrences that takes two strings as a parameters, and returns the number of times first string appears in the second string.
For example: get_occurrences("x","anthony") à 0 (there are no x’s in Anthony) get_occurrences("y","anthony") à 1 (there is one y in Anthony) get_occurrences("n","anthony") à 2 (there are two n’s in Anthony)
We require that you use loops in your answer. In addition to using a loop, remember the helpful string operations we learned in lecture:
name = "Anthony”
len(name) -> 7
name[3] -> "h"
Exercise 3 – Counting the number of factors of a value within a given range
Design a function called count_multiples that takes three whole positive numbers as parameters. The first two parameters return a range of values to search; the function should return how many numbers within the range are multiples of the third parameter.
For example: count_multiples(1, 9, 2) -> 4 (as 2 goes into 2, 4, 6, and 8)
count_multiples(1, 8, 2) -> 4 (as 2 goes into 2, 4, 6, and 8)
count_multiples(2, 8, 2) -> 4 (as 2 goes into 2, 4, 6, and 8)
count_multiples(20, 28, 3) -> 3 (as 3 goes into 21, 24, and 27)
count_multiples(107, 255, 7) -> 21 (7 goes into 112, 119, ..., 245, 252)
Hint: As you are solving the problem, try and print out any multiples you find as you search the range of values (given by the first and second parameters).
Exercise 4 – Printing out 10 multiples per row
Design a function called print_ten_multiples that takes an integer as a parameter. The function should print out the first 10 multiples of all numbers from 1 up to the given number.
The values printed should be formatted with "3d". Example: print(format(x, "3d"))
Examples of how the function output should look with this formatting:
print_ten_multiples(3):
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
print_ten_multiples(11):
1 2 3 4 5 6 7 8 9 10
2 4 6 8101214161820
3 6 912151821242730
4 81216202428323640
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
11 22 33 44 55 66 77 88 99 110
tests = 0
passed = 0
def main():
test_get_factorial()
#test_get_occurrences()
#test_count_multiples()
#test_print_ten_multiples()
print("Test results:", passed, "/", tests)
def test_get_factorial():
print("testing get_factorial...")
result = get_factorial(0)
#TODO: add more tests here
def test_get_occurrences():
print("testing get_occurrences...")
result = get_occurrences("x","anthony")
print_test("testing with x and anthony",
result==0)
#TODO: add more tests here
def test_count_multiples():
print("testing count_multiples...")
result = count_multiples(1, 9, 2)
print_test("testing with 1, 9, 2", result==4)
#TODO: add more tests here
def test_print_ten_multiples():
print("testing print_ten_multiples")
print("\nTesting with 3")
print_ten_multiples(3) # expects final row to be 3 -
30
#TODO: add more tests here
# TODO: Complete function design
def get_factorial(n):
...
# TODO: Complete function design
def get_occurrences(c, text):
...
# TODO: Complete function design
def count_multiples(start, end, n):
...
# TODO: Complete function design
def print_ten_multiples(max):
...
# (str, bool -> None)
# takes the name or description of a test and whether the
# test produced the expected output (True) or not (False)
# and prints out whether that test passed or failed
# NOTE: You should not have to modify this in any way.
def print_test(test_name, result_correct):
global tests
global passed
tests += 1
if(result_correct):
print(test_name + ": passed")
passed += 1
else:
print(test_name + ": failed")
# The following code will call your main function
if __name__ == '__main__':
main()
In: Computer Science
Given a 2 Gbps link with TCP applications A, B, and C.
According to TCP "fairness", during times when all connections are transmitting, how much bandwidth should Application C have? (Give answer in Mbps, rounded to one decimal place, without units. So for an answer of 1234,567,890 bps you would enter "1234.6" without the quotes.)
In: Computer Science
How would I create a network using packet tracer with these attributes?
6 workstations, 1 switch (2950T), Subnet for the is 10.10.10.0/28 , Create 2 VLANs on each switch (VLAN 10 and 20), Add 3 workstations to VLAN 10 and 3 workstations to VLAN 20, Only workstations on the same VLAN should be able to communicate with each other
In: Computer Science
Given an array of integers, implement (in Java) the moveAllNegativeOne method to
move all -1 present in the array to the end. The algorithm should maintain the relative
order of items in the array and worst-case running time complexity must be linear.
Example:
Input: [6, -1, 8, 2, 3, -1, 4, -1, 1]
Output: [6, 8, 2, 3, 4, 1, -1, -1, -1]
Important Notes:
• You must add the main method in your program in Java in order to test your
implementation.
• You can use the array of the previous example to test your program, however, I
suggest that you also use other input arrays to validate the correctness and
efficiency of your solution.
• Your program MUST be submitted only in source code form (.java file).
• A program that does not compile or does not run loses all correctness points.
In: Computer Science
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL)); // randomize
int *a; // pointer to array
int i, n;
printf("Size of array:");
scanf("%d", &n);
/* memory allocation */
a = (int*)malloc(n*sizeof(int));
/* array generating */
for (i = 0; i < n; i++) a[i] = rand()%101;
/* output */
for (i = 0; i<n; i++) printf("a[%d] = %d ", i, a[i]);
putchar('\n');
free(a);
return 0;
}
Using the above code please do it to me following
Hints:
Remember to initialize any sum variable to 0
rand() will return a random number too big for 0-99. Use modulo to reduce the range.
rand() needs to be initialized with a seed. You can use: srand(time(0));
Hints:
Make a function to deal with open/read/sum/print/close.
opendir() requires a starting directory. You want to start where in the current directory.
You need to loop over the directory entries. This is similar to walking a linked list.
You want to check every file entry to see if it starts with “numbers.”
In: Computer Science
20. Suppose we run program P in a computer system
using the Linux operating system. We use the Linux time
command
to collect some time measurements while P is running. The output
from time is,
real. 53m27
.589s
user 24m41 .850s
system 1m3 .337s
a. What was the execution time of P?
b. What was the user CPU time of P?
c. What was the system CPU time of P?
d. How much time during the execution of P did the system spend not
executing the instructions of P nor OS in-
structions on behalf of P?
e. List and describe one factor or component of the time from
exercise d, i.e., name one thing the system might have
been doing during this time period
In: Computer Science