File encryption. [32] Write a program which accepts a filename as a command-line argument [-
32]. It should then ask for a password via stdin (but it should not visible when entered; use
getpass for this) [4]. The program should encrypt the file using a block-cipher algorithm (see
encryption.rst for details) [12] if it was not already encrypted by the program, and rename it with
a .enc extension. If it was already encrypted, it should decrypt the file and remove the .enc
extension [12]. Under no circumstance should the program multiply encrypt the file [4]. Call the
program encrypt.cpp. here is encrypt.rst Suppose I have an input file to encrypt: .. raw: The only
true wisdom is in knowing you know nothing. (A quote by Socrates.) What I can do then is ask
the user for a password. Suppose the user enters kitties. Then what I may do is pre-pend the
password to an output file, and add kitties in rounds to the file: .. raw: kittiesThe only true
wisdom is in knowing you know nothing. + kittieskittieskittieskittieskittieskittieskittieskittieskit -
---------------------------------------------------------- =
fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd When I add the characters in the
string kitties, I get what appears to be jumbled garbage. Without the password, it is hard to
decrypt the file. To decrypt the file, I ask the user for the password. Suppose they enter bubbles
(the wrong password). .. raw: fhdkalhfioepwah... - bubbles ------------------ = ueiaqnv I see that
by subtracting bubbles off the encrypted text, I do not get the string bubbles back, so bubbles is
not the password. If the user enters kitties (the correct password): .. raw: fhdkalhfioepwah... -
kitties ------------------ = kitties Then I see that what I get back is kitties, and since it matches the
user password entered, I may proceed to decrypt the rest of the file simply by subtracting kitties
off it in rounds. .. raw: = fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd -
kittieskittieskittieskittieskittieskittieskittieskittieskit ------------------------------------------------------
----- kittiesThe only true wisdom is in knowing you know nothing. Thus I obtain the original
message. Notice the user-supplied password itself is a necessary element of the decryption. This
type of algorithm is called a block cipher algorithm.
Solution
// Encrypting_a_File.cpp : Defines the entry point for the console
// application.
//
#include
#include
#include
#include
#include
// Link with the Advapi32.lib file.
#pragma comment (lib, \"advapi32\")
#define KEYLENGTH 0x00800000
#define ENCRYPT_ALGORITHM CALG_RC4
#define ENCRYPT_BLOCK_SIZE 8
bool MyEncryptFile(
LPTSTR szSource,
LPTSTR szDestination,
LPTSTR szPassword);
void MyHandleError(
LPTSTR psz,
int nErrorNumber);
int _tmain(int argc, _TCHAR* argv[])
{
if(argc < 3)
{
_tprintf(TEXT(\"Usage: \")
TEXT(\" | \ \"));
_tprintf(TEXT(\" is optional.\ \"));
_tprintf(TEXT(\"Press any key to exit.\"));
_gettch();
return 1;
}
LPTS.
Using Puppet to Create a Dynamic Network - PuppetConf 2013Puppet
"Using Puppet to Create a Dynamic Network" by Thomas Uphill Infrastructure Analyst, Costco Wholesale.
Presentation Overview: Complex networks often need complex configurations and a lot of care and attention to individual severs. Using hiera, exported resources, custom facts, defined types, augeas and some forge modules we will explore the possibilities for having puppet take care of the complex configuration. We'll start with a few simple examples of exported resources and scale up to having hiera key off custom facts and having exported augeas resources build configurations.
Speaker Bio: An early adopter of puppet, Thomas has been using puppet since 0.24. He started with puppet for workstation management at the Institute for Advanced Study where he also helped develop the Springdale Linux distribution. He currently works with puppet at Costco Wholesale Headquarters In Issaquah Washington. He has been working with Red Hat systems since 7.3 and currently holds an RCHA.
This presentation has been created for Red Hat System Administration I (RH124) training course conducted at Cybergate. This will help every one who wish to update their knowledge on Linux user management.
Puppi is a Puppet modules that drives Puppet's knowledge of the Systems to a command line tool that you can use to check services availability, gather info on the system and deploy application with a single command.
Using Puppet to Create a Dynamic Network - PuppetConf 2013Puppet
"Using Puppet to Create a Dynamic Network" by Thomas Uphill Infrastructure Analyst, Costco Wholesale.
Presentation Overview: Complex networks often need complex configurations and a lot of care and attention to individual severs. Using hiera, exported resources, custom facts, defined types, augeas and some forge modules we will explore the possibilities for having puppet take care of the complex configuration. We'll start with a few simple examples of exported resources and scale up to having hiera key off custom facts and having exported augeas resources build configurations.
Speaker Bio: An early adopter of puppet, Thomas has been using puppet since 0.24. He started with puppet for workstation management at the Institute for Advanced Study where he also helped develop the Springdale Linux distribution. He currently works with puppet at Costco Wholesale Headquarters In Issaquah Washington. He has been working with Red Hat systems since 7.3 and currently holds an RCHA.
This presentation has been created for Red Hat System Administration I (RH124) training course conducted at Cybergate. This will help every one who wish to update their knowledge on Linux user management.
Puppi is a Puppet modules that drives Puppet's knowledge of the Systems to a command line tool that you can use to check services availability, gather info on the system and deploy application with a single command.
Linux Tracing Superpowers by Eugene PirogovPivorak MeetUp
For a long time Linux was far behind operating systems of Unix family from the perspective of debuggability, specifically in a live production systems.
However, over the course of 2016 Linux saw a series of patches that brought it on par with Unix world: an old Linux tool called BPF has risen and extended into powerful new one – eBPF. Some say that eBPF marks the begining of true DTrace for Linux.
During the presentation I'm going to talk about tracing basics, cover a series of events that led to the development of eBPF and will compare eBPF with DTrace from Unix world. Current state of affairs of Linux tracing tools will be explored. Finally, together we'll look at some of the exciting examples of eBPF application.
***
Eugene is well known in our Ruby (and Elixir) communities. Last time when he was at #pivorak he made a very light and interesting intro to the Elixir. You can check his speech out here - http://bit.ly/2evCd9R
Beyond Golden Containers: Complementing Docker with Puppetlutter
Often, Docker or more generally containers and immutable infrastructure are viewed as a replacement for configuration management. This talk explains why that is not the case, and that they are in fact complementary.
Containers move the challenges that configuration management solves to different places in the application lifecycle. The talk explains where Puppet fits into this changed lifecycle, and what tools Puppet provides there.
Slides for a talk I gave at the Linux Foundation Colaboration Summit 2015
Postgresql 12 streaming replication holVijay Kumar N
This is a step by step hands on lab for PostgreSQL 12 , setup of replication, replication slot, failover (promoting) to standby as new master cluster and also covering the scenario where old master has to be reinstated using the utility "pg_rewind"
Need help implementing the skeleton code below, I have provided the .pdfezzi552
I need help with this practice problem?
Execute the following coding segment and identify the errors in the program. Debug the program
and provide the correct version of the code. Hinclude int main() printf(\"%s\", isdigit(\'A\') ? \"A
is digit\" \"A is not digit\"); a : a printf(\"Inlnln\") return return e;
Solution
in range [0,9]. If it\'s not then this function returns 0.
Given program compiles successfully, compiler does not give any error.
But If the input of isdigit(\'A\') is changed then the program will always print
\"A is a digit\" or
\"A is not a digit\" .
It will not print exact value of char A.
So, correct code is given below.
#include
int main()
{
char A = \'1\';
printf(\"%c%s\",A,isdigit(A)? \" is a digit\" : \" is not a digit\");
printf(\"\ \");
A = \'B\';
printf(\"%c%s\",A,isdigit(A)? \" is a digit\" : \" is not a digit\");
printf(\"\ \");
return 0;
}
Sample Output:
1 is a digit
B is not a digit.
Spraykatz is a credentials gathering tool automating remote procdump and parse of lsass process. Spraykatz is a tool able to retrieve credentials on Windows machines and large Active Directory environments. It simply tries to procdump machines and parse dumps remotely in order to avoid detections by antivirus softwares as much as possible.
Program Assignment Process ManagementObjective This program a.docxwkyra78
Program Assignment : Process Management
Objective: This program assignment is given to the Operating Systems course to allow the students to figure out how a single process (parent process) creates a child process and how they work on Unix/Linux(/Mac OS X/Windows) environment. Additionally, student should combine the code for describing inter-process communication into this assignment. Both parent and child processes interact with each other through shared memory-based communication scheme or message passing scheme.
Environment: Unix/Linux environment (VM Linux or Triton Server, or Mac OS X), Windows platform
Language: C or C++, Java
Requirements:
i. You have wide range of choices for this assignment. First, design your program to explain the basic concept of the process management in Unix Kernel. This main idea will be evolved to show your understanding on inter-process communication, file processing, etc.
ii. Refer to the following system calls:
- fork(), getpid(), family of exec(), wait(), sleep() system calls for process management
- shmget(), shmat(), shmdt(), shmctl() for shared memory support or
- msgget(), msgsnd(), msgrcv(), msgctl(), etc. for message passing support
iii. The program should present that two different processes, both parent and child, execute as they are supposed to.
iv. The output should contain the screen capture of the execution procedure of the program.
v. Interaction between parent and child processes can be provided through inter-process communication schemes, such as shared-memory or message passing schemes.
vi. Result should be organized as a document which explains the overview of your program, code, execution results, and the conclusion including justification of your program, lessons you've learned, comments, etc.
Note:
i. In addition, please try to understand how the local and global variables work across the processes
ii. read() or write () functions are used to understand how they work on the different processes.
iii. For extra credit, you can also incorporate advanced features, like socket or thread functions, into your code.
Examples:
1. Process Creation and IPC with Shared Memory Scheme
=============================================================
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t pid;
int segment_id; //allocate the memory
char *shared_memory; //pointer to memory
const int size = 4096;
segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);
shared_memory = (char *) shmat(segment_id, NULL, 0);
pid = fork();
if(pid < 0) { //error
fprintf(stderr, "Fork failed");
return 1;
}
else if(pid == 0){ //child process
char *child_shared_memory;
child_shared_memory = (char *) shmat(segment_id,NULL,0); //attach mem
sprintf(child_shared_memory, "Hello parent process!"); //write to the shared mem
shmdt(child_shared_memory);
}
else ...
Backdooring the web is the cheapest and most hidden way to achieve
persistence on a compromised network, both if you're looking at
privileges on the webapp itself or at executing command to underlying
system.
During the talk, we will discuss the context of a web backdoor: the
environment where she can born and grow up will be defined.
Each environmental aspect will be thoroughly analyzed: where is the best
point of injection, why we choose a specific function or trick, what
permissions are needed, how to trigger the backdoor in a safe, hidden
and reproducible way, and of course what to inject.
The talk will thus present several ways to inject obfuscated and hard to
spot vulnerabilities in PHP code. Shown examples will backdoor CMS
plugins as well as custom code, altering the code and polluting the
webapp ecosystem (read: DBMS and webservers).
How does an open source operating system like Linux® affect Internet.pdfjyothimuppasani1
How does an open source operating system like Linux® affect Internet security and safety?
Solution
Since open source operating system\'s code is available to all,it\'s provides an easy access to
hackers and potential misusers which affects safety of such systems.
The non stable nature of Open source operating system also can be considered an important
factor that affects the Security.This is because Developers all over the globe modify the code and
thus the code is not stable and it becomes vulnerable to security threats.
Even if patches are introduced from time to time,mostly after an attack or so but due to large
flavours or distributions of open source software, some flavours are left without patches that
makes them vulnerable to attacks.
Also,The administration of open source operating system Servers also plays an important factor
in Internet Security. Since it is known that for example,Linux Server administration is more
difficult and when multiple ports are open it is sometimes not possible to handle an attack or
security threat immediately.
But then as it is said that every coin has two sides, Sometimes it is considered that Open Source
Systems like Linux are more secure because of the following reasons :.
Help please!!(Include your modified DList.java source code file in.pdfjyothimuppasani1
Help please!!
(Include your modified DList.java source code file in your homework solution zip archive)
Using
whatever Java IDE you prefer, create a project and add DList.java and DListTest.java to it (these
files are provided
in the Week 6 Source zip archive). Modify DList to implement a method that removes all
occurrences of a specific
integer from the list. Here is the pseudocode:
Method removeAll(In: Integer pData) Returns Nothing
Define index variable i and initialize i to 0
While i < the size of this Dlist Do
If get(i) equals pData Then
remove(i)
Else
Increment i
End If
End While
End Method removeAll
Next, modify DListTest() to add test case 21 which tests that removeAll() works correctly.
WHat more do i need to provide to get help on this???
Solution
/* DListNode.java */
/**
* A DListNode is a node in a DList (doubly-linked list).
*/
class DListNode {
/**
* item references the item stored in the current node.
* prev references the previous node in the DList.
* next references the next node in the DList.
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
public Object item;
protected DListNode prev;
protected DListNode next;
/**
* DListNode() constructor.
* @param i the item to store in the node.
* @param p the node previous to this node.
* @param n the node following this node.
*/
DListNode(Object i, DListNode p, DListNode n) {
item = i;
prev = p;
next = n;
}
}
/* DList.java */
/**
* A DList is a mutable doubly-linked list ADT. Its implementation is
* circularly-linked and employs a sentinel (dummy) node at the head
* of the list.
*
* DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE.
*/
class DList {
/**
* head references the sentinel node.
* size is the number of items in the list. (The sentinel node does not
* store an item.)
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
protected DListNode head;
protected int size;
/* DList invariants:
* 1) head != null.
* 2) For any DListNode x in a DList, x.next != null.
* 3) For any DListNode x in a DList, x.prev != null.
* 4) For any DListNode x in a DList, if x.next == y, then y.prev == x.
* 5) For any DListNode x in a DList, if x.prev == y, then y.next == x.
* 6) size is the number of DListNodes, NOT COUNTING the sentinel,
* that can be accessed from the sentinel (head) by a sequence of
* \"next\" references.
*/
/**
* newNode() calls the DListNode constructor. Use this class to allocate
* new DListNodes rather than calling the DListNode constructor directly.
* That way, only this method needs to be overridden if a subclass of DList
* wants to use a different kind of node.
* @param item the item to store in the node.
* @param prev the node previous to this node.
* @param next the node following this node.
*/
protected DListNode newNode(Object item, DListNode prev, DListNode next) {
return new DListNode(item, prev, next);
}
/**
* DList() constructor for an empty DList.
*/
public DList() {
// Your solution here.
head = newNode(null, head, head);
head.prev = head;
head.next = head;
si.
More Related Content
Similar to File encryption. [32] Write a program which accepts a filename as a .pdf
Linux Tracing Superpowers by Eugene PirogovPivorak MeetUp
For a long time Linux was far behind operating systems of Unix family from the perspective of debuggability, specifically in a live production systems.
However, over the course of 2016 Linux saw a series of patches that brought it on par with Unix world: an old Linux tool called BPF has risen and extended into powerful new one – eBPF. Some say that eBPF marks the begining of true DTrace for Linux.
During the presentation I'm going to talk about tracing basics, cover a series of events that led to the development of eBPF and will compare eBPF with DTrace from Unix world. Current state of affairs of Linux tracing tools will be explored. Finally, together we'll look at some of the exciting examples of eBPF application.
***
Eugene is well known in our Ruby (and Elixir) communities. Last time when he was at #pivorak he made a very light and interesting intro to the Elixir. You can check his speech out here - http://bit.ly/2evCd9R
Beyond Golden Containers: Complementing Docker with Puppetlutter
Often, Docker or more generally containers and immutable infrastructure are viewed as a replacement for configuration management. This talk explains why that is not the case, and that they are in fact complementary.
Containers move the challenges that configuration management solves to different places in the application lifecycle. The talk explains where Puppet fits into this changed lifecycle, and what tools Puppet provides there.
Slides for a talk I gave at the Linux Foundation Colaboration Summit 2015
Postgresql 12 streaming replication holVijay Kumar N
This is a step by step hands on lab for PostgreSQL 12 , setup of replication, replication slot, failover (promoting) to standby as new master cluster and also covering the scenario where old master has to be reinstated using the utility "pg_rewind"
Need help implementing the skeleton code below, I have provided the .pdfezzi552
I need help with this practice problem?
Execute the following coding segment and identify the errors in the program. Debug the program
and provide the correct version of the code. Hinclude int main() printf(\"%s\", isdigit(\'A\') ? \"A
is digit\" \"A is not digit\"); a : a printf(\"Inlnln\") return return e;
Solution
in range [0,9]. If it\'s not then this function returns 0.
Given program compiles successfully, compiler does not give any error.
But If the input of isdigit(\'A\') is changed then the program will always print
\"A is a digit\" or
\"A is not a digit\" .
It will not print exact value of char A.
So, correct code is given below.
#include
int main()
{
char A = \'1\';
printf(\"%c%s\",A,isdigit(A)? \" is a digit\" : \" is not a digit\");
printf(\"\ \");
A = \'B\';
printf(\"%c%s\",A,isdigit(A)? \" is a digit\" : \" is not a digit\");
printf(\"\ \");
return 0;
}
Sample Output:
1 is a digit
B is not a digit.
Spraykatz is a credentials gathering tool automating remote procdump and parse of lsass process. Spraykatz is a tool able to retrieve credentials on Windows machines and large Active Directory environments. It simply tries to procdump machines and parse dumps remotely in order to avoid detections by antivirus softwares as much as possible.
Program Assignment Process ManagementObjective This program a.docxwkyra78
Program Assignment : Process Management
Objective: This program assignment is given to the Operating Systems course to allow the students to figure out how a single process (parent process) creates a child process and how they work on Unix/Linux(/Mac OS X/Windows) environment. Additionally, student should combine the code for describing inter-process communication into this assignment. Both parent and child processes interact with each other through shared memory-based communication scheme or message passing scheme.
Environment: Unix/Linux environment (VM Linux or Triton Server, or Mac OS X), Windows platform
Language: C or C++, Java
Requirements:
i. You have wide range of choices for this assignment. First, design your program to explain the basic concept of the process management in Unix Kernel. This main idea will be evolved to show your understanding on inter-process communication, file processing, etc.
ii. Refer to the following system calls:
- fork(), getpid(), family of exec(), wait(), sleep() system calls for process management
- shmget(), shmat(), shmdt(), shmctl() for shared memory support or
- msgget(), msgsnd(), msgrcv(), msgctl(), etc. for message passing support
iii. The program should present that two different processes, both parent and child, execute as they are supposed to.
iv. The output should contain the screen capture of the execution procedure of the program.
v. Interaction between parent and child processes can be provided through inter-process communication schemes, such as shared-memory or message passing schemes.
vi. Result should be organized as a document which explains the overview of your program, code, execution results, and the conclusion including justification of your program, lessons you've learned, comments, etc.
Note:
i. In addition, please try to understand how the local and global variables work across the processes
ii. read() or write () functions are used to understand how they work on the different processes.
iii. For extra credit, you can also incorporate advanced features, like socket or thread functions, into your code.
Examples:
1. Process Creation and IPC with Shared Memory Scheme
=============================================================
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
pid_t pid;
int segment_id; //allocate the memory
char *shared_memory; //pointer to memory
const int size = 4096;
segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);
shared_memory = (char *) shmat(segment_id, NULL, 0);
pid = fork();
if(pid < 0) { //error
fprintf(stderr, "Fork failed");
return 1;
}
else if(pid == 0){ //child process
char *child_shared_memory;
child_shared_memory = (char *) shmat(segment_id,NULL,0); //attach mem
sprintf(child_shared_memory, "Hello parent process!"); //write to the shared mem
shmdt(child_shared_memory);
}
else ...
Backdooring the web is the cheapest and most hidden way to achieve
persistence on a compromised network, both if you're looking at
privileges on the webapp itself or at executing command to underlying
system.
During the talk, we will discuss the context of a web backdoor: the
environment where she can born and grow up will be defined.
Each environmental aspect will be thoroughly analyzed: where is the best
point of injection, why we choose a specific function or trick, what
permissions are needed, how to trigger the backdoor in a safe, hidden
and reproducible way, and of course what to inject.
The talk will thus present several ways to inject obfuscated and hard to
spot vulnerabilities in PHP code. Shown examples will backdoor CMS
plugins as well as custom code, altering the code and polluting the
webapp ecosystem (read: DBMS and webservers).
How does an open source operating system like Linux® affect Internet.pdfjyothimuppasani1
How does an open source operating system like Linux® affect Internet security and safety?
Solution
Since open source operating system\'s code is available to all,it\'s provides an easy access to
hackers and potential misusers which affects safety of such systems.
The non stable nature of Open source operating system also can be considered an important
factor that affects the Security.This is because Developers all over the globe modify the code and
thus the code is not stable and it becomes vulnerable to security threats.
Even if patches are introduced from time to time,mostly after an attack or so but due to large
flavours or distributions of open source software, some flavours are left without patches that
makes them vulnerable to attacks.
Also,The administration of open source operating system Servers also plays an important factor
in Internet Security. Since it is known that for example,Linux Server administration is more
difficult and when multiple ports are open it is sometimes not possible to handle an attack or
security threat immediately.
But then as it is said that every coin has two sides, Sometimes it is considered that Open Source
Systems like Linux are more secure because of the following reasons :.
Help please!!(Include your modified DList.java source code file in.pdfjyothimuppasani1
Help please!!
(Include your modified DList.java source code file in your homework solution zip archive)
Using
whatever Java IDE you prefer, create a project and add DList.java and DListTest.java to it (these
files are provided
in the Week 6 Source zip archive). Modify DList to implement a method that removes all
occurrences of a specific
integer from the list. Here is the pseudocode:
Method removeAll(In: Integer pData) Returns Nothing
Define index variable i and initialize i to 0
While i < the size of this Dlist Do
If get(i) equals pData Then
remove(i)
Else
Increment i
End If
End While
End Method removeAll
Next, modify DListTest() to add test case 21 which tests that removeAll() works correctly.
WHat more do i need to provide to get help on this???
Solution
/* DListNode.java */
/**
* A DListNode is a node in a DList (doubly-linked list).
*/
class DListNode {
/**
* item references the item stored in the current node.
* prev references the previous node in the DList.
* next references the next node in the DList.
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
public Object item;
protected DListNode prev;
protected DListNode next;
/**
* DListNode() constructor.
* @param i the item to store in the node.
* @param p the node previous to this node.
* @param n the node following this node.
*/
DListNode(Object i, DListNode p, DListNode n) {
item = i;
prev = p;
next = n;
}
}
/* DList.java */
/**
* A DList is a mutable doubly-linked list ADT. Its implementation is
* circularly-linked and employs a sentinel (dummy) node at the head
* of the list.
*
* DO NOT CHANGE ANY METHOD PROTOTYPES IN THIS FILE.
*/
class DList {
/**
* head references the sentinel node.
* size is the number of items in the list. (The sentinel node does not
* store an item.)
*
* DO NOT CHANGE THE FOLLOWING FIELD DECLARATIONS.
*/
protected DListNode head;
protected int size;
/* DList invariants:
* 1) head != null.
* 2) For any DListNode x in a DList, x.next != null.
* 3) For any DListNode x in a DList, x.prev != null.
* 4) For any DListNode x in a DList, if x.next == y, then y.prev == x.
* 5) For any DListNode x in a DList, if x.prev == y, then y.next == x.
* 6) size is the number of DListNodes, NOT COUNTING the sentinel,
* that can be accessed from the sentinel (head) by a sequence of
* \"next\" references.
*/
/**
* newNode() calls the DListNode constructor. Use this class to allocate
* new DListNodes rather than calling the DListNode constructor directly.
* That way, only this method needs to be overridden if a subclass of DList
* wants to use a different kind of node.
* @param item the item to store in the node.
* @param prev the node previous to this node.
* @param next the node following this node.
*/
protected DListNode newNode(Object item, DListNode prev, DListNode next) {
return new DListNode(item, prev, next);
}
/**
* DList() constructor for an empty DList.
*/
public DList() {
// Your solution here.
head = newNode(null, head, head);
head.prev = head;
head.next = head;
si.
how can I replace the Newsfeed text with a custom on in SharePoi.pdfjyothimuppasani1
how can I replace the \"Newsfeed\" text with a custom on in SharePoint 365.
(Newsfeed Webpart)
Solution
First of all there are some differences between sharepoint and office 365. SharePoint has 4
versions still in active use : SharePoint 2007,2010,2016 and office 365. Office 365 released in
2011 With SharePoint2010 interface. Office 365 hav a various exclusive features like NextGen
Portals (Out of the box “ready to go” portals), Delve (A technology based on Office Graph that
presents “relevant information” to you based on your actions and interactions with colleague
files), Sway (A presentation web par that allows users to combine text, images and videos locally
and from the wider internet to create a usable website.), Yammer Integration (Yammer is the
enterprise social network that\'s being gradually rolled into all Office 365 features.) anf Office
365 Groups.
A custom CSS included in SharePoint master page in order to customize Newsfeed Web Part.
the code is:
.ms-microfeed-siteFeedTitleArea
{
background-color: silver;
padding-left: 20px;
text-transform:uppercase;
padding-bottom: 3px;
padding-top: 2px;
margin-bottom: 5px;
}
.ms-microfeed-siteFeedMicroBlogPart
{
margin-bottom: 2px;
}
.ms-microfeed-siteFeedTitleLabel
{
color: red !important;
}
.ms-microfeed-threadsDiv
{
height: 250px;
overflow-y: auto;
overflow-x: hidden;
}
.ms-microfeed-thread
{
max-width: 435px;
margin-bottom: 10px;
}
.ms-microfeed-replyArea
{
max-width: 375px;
min-width: 300px;
}
.ms-microfeed-attachmentButton
{
padding-top: 2px;
padding-bottom: 2px;
display: block;
}
.ms-microfeed-postButton
{
padding-top: 2px;
padding-bottom: 2px;
}
.ms-microfeed-postButtonSpan
{
margin-top: 2px;
}
.ms-microfeed-postBox
{
height: 20px;
}
Apart from this we can also hide controls, for this first we need to activate Site Feed feature, to
do this go to site settings->Manage Site Features and activate it
script for hide controls
I used the following CSS classes and its worked.
.ms-microfeed-cancelButton{
background-color: #fcfcfc !important;
border: 1px solid #d4d4d4 !important;
-moz-border-radius: 10px !important;
-webkit-border-radius: 10px !important;
border-radius: 10px !important;
color: #00a6d9 !important;
height: 22px !important;
padding-top: 3px !important;
width: 78px !important;
font-family: Arial !important;
font-size: 11px!important;
font-weight: normal !important;
}
.ms-microfeed-siteFeedTitleArea
{
background-color: silver;
padding-left: 20px;
text-transform:uppercase;
padding-bottom: 3px;
padding-top: 2px;
margin-bottom: 5px;
}
.ms-microfeed-siteFeedMicroBlogPart
{
margin-bottom: 2px;
}
.ms-microfeed-siteFeedTitleLabel
{
color: red !important;
}
.ms-microfeed-threadsDiv
{
height: 250px;
overflow-y: auto;
overflow-x: hidden;
}
.ms-microfeed-thread
{
max-width: 435px;
margin-bottom: 10px;
}
.ms-microfeed-replyArea
{
max-width: 375px;
min-width: 300px;
}
.ms-microfeed-attachmentButton
{
padding-top: 2px;
padding-bottom: 2px;
padding-bottom: 2px;
display: block;
}
.ms-microfeed-pos.
Hello!This is Java assignment applet.Can someone help me writing.pdfjyothimuppasani1
Hello!
This is Java assignment applet.
Can someone help me writing a code how to exit the game when I press no in question( would
you like to play again?). Also if no one wins or draws i would like to pop up the question ( would
you like to play again?). I have the code below i would like someone to add it
Thanks in advance!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TicTacToe extends Applet implements ActionListener{
// Array to store buttons
JButton button[][] = new JButton[3][3];
boolean isNewGame =false;
// To switch player either X or O
boolean isZero = true; //first turn is always 0
// Setup size
// Set layout to grid
// Create buttons through loop
// Add buttons to layout
// Add listener
public void init(){
setSize(500, 500);
setLayout(new GridLayout(3,3));
// if it is not a new game
if(isNewGame==false) {
// Adding buttons to layout
//initialize the Grid and add ActionListener to each Button
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
// init jButton
button[i][j] = new JButton(\"\");
// Setup Font and Size here
button[i][j].setFont(new Font(\"Lucida Grande\", Font.PLAIN, 28));
// Add is a method from applet to add buttons in layout
add(button[i][j]);
// Listener
button[i][j].addActionListener(this);
}
}
}
else {
// If we need to restart the game, then we only set text to empty
// Back to black color
// add listener
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
button[i][j].setText(\"\");
button[i][j].setForeground(Color.BLACK);
button[i][j].removeActionListener(this);
button[i][j].addActionListener(this);
}
}
}
}
// Go all the buttons in arrsy
// Check the event with button in array
// if player O is true, set button text O. Otherwise. X
// Remove Listerner. Why? only once you can click
// Change player by isZero
// Check for winner
public void actionPerformed(ActionEvent event){
for(int i = 0; i < 3; i++)
for(int j = 0; j < 3; j++){
if((event.getSource() == button[i][j])){
if(isZero){
button[i][j].setText(\"O\");
}
else{
button[i][j].setText(\"X\");
}
button[i][j].removeActionListener(this); //you cannot click on one tile more than
once
isZero = !isZero;
checkForWinners(); //check if any winner after each move
}
}
}
public void checkForWinners(){
//3 horizontal lines
for(int i = 0; i < 3; i++){
if(button[i][0].getText().equals(button[i][1].getText())
&& button[i][1].getText().equals(button[i][2].getText())
&& !button[i][0].getText().equals(\"\")){
String player = button[i][0].getText();
button[i][0].setForeground(Color.RED);
button[i][1].setForeground(Color.RED);
button[i][2].setForeground(Color.RED);
int reply =JOptionPane.showConfirmDialog(null, player + \" wins!\"+\"\ Would like
to play again?\",\"Game over\",JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
isNewGame = true;
init();
return;
}
else {
System.exit(0);
return;
}
}
}
//3 vertical lines
for(int i = 0; i < 3; i++){
if(button[0][i].getText().equals(button[1][i].getText())
&& .
For each of the following reseach questions identify the observation.pdfjyothimuppasani1
For each of the following reseach questions identify the observational units and variable (s)
P. 1.2Subjects listened to ten second of the Jackson 5 \'s song \"ABC\" and then were how long
they thought the song snippet lasted . Do people tend to overestimate the song length?
Solution
variable is song length. In other words the time subjects think they listened to song.
unit is seconds.
Find an Eulerian trail in the following graph. Be sure to indicate th.pdfjyothimuppasani1
Find an Eulerian trail in the following graph. Be sure to indicate the order in which the edges are
visited.
Solution
Eulerian path/ trail:
A path is called as Eulerian path if every edge of the graph G appears exactly ince in the path.
NOTE::
A graph possesses an Eulerian trail if and only if it is connected and has either zero and 2
vertices of odd degrees
ANSWER:
order -> h,d,c,b,f,e,b,a,e,i,j,f,g,k,l,h,g,c,d.
Explain the relevance that medical standards of practice have to one.pdfjyothimuppasani1
Explain the relevance that medical standards of practice have to one as a practioner?
Solution
\'Providing care\' incorporates, however isn\'t restricted to any care,
treatment, counsel, administration or merchandise gave in regard
of the physical or emotional well-being of a man, regardless of whether
compensated or genius bono.
\'Practice\' implies any part, regardless of whether compensated or not,
in which the individual uses their aptitudes and learning
as a specialist in their controlled wellbeing calling. For
the motivations behind this Code, rehearse isn\'t limited to
the arrangement of direct clinical care. It additionally incorporates utilizing
proficient learning in a direct nonclinical relationship
with patients or customers, working in administration,
organization, instruction, look into, warning, administrative or
arrangement improvement parts and whatever other parts that effect
on sheltered, powerful conveyance of wellbeing administrations in the wellbeing
calling.
Keeping up and creating learning, aptitudes and
proficient conduct are center parts of good practice.
This requires self-reflection and support in pertinent
proficient advancement, rehearse change and
execution evaluation procedures to persistently create
proficient capacities. These exercises must proceed
through a specialist\'s working life as science and
innovation create and society changes.
giving specialists who are patients or customers with
a similar nature of care gave to different patients or
customers
b). informing the sheets if treating another enrolled
specialist who has set patients or customers in danger
of significant mischief while rehearsing their calling
since they have an impedance (allude to the
board\'s rules on compulsory detailing) this is a
proficient and also a statutory obligation under
the National Law
At the point when specialists are engaged with look into that includes
patients or customers, great practice incorporates:
a). regarding the privilege of patients or customers to pull back
from an investigation without partiality to their treatment
b). guaranteeing that a choice by patients or customers not to
take an interest does not bargain the specialist
tolerant/customer relationship or the care of the patient or
customer..
Find the mission and values statements for four different hospita.pdfjyothimuppasani1
Find the mission and values statements for four different hospital types. Do their missions and
values reconcile with your expectations for the type of organization? Look at a religious based
organization. Does their mission and values reflect their religious teachings and mission? Now
examine a for-profit hospital. Does their mission and values include the need to increase their
owners\' value and maximizing their earning? Why do you think the missions and values are
structured as they are? 1. The missions and values are structured as they are to meet the desires
of the stakeholders. The specifics of this question must be left to the particulars of the
instructional environment.
Solution
We will describe mission and value statements of four hospitals given below:-
a) Seattle Children\'s Hospital
Mission statement:-
We provide hope, care and cures to help every child live the healthiest and most fulfilling life
possible.
Value statement:-
Compassion
Empathy for patients, their families and staff is ingrained in our history and inspires our future.
We do more than treat the child; we practice family-centered care as the cornerstone of
compassion.
Excellence
Our promise to treat, prevent and cure pediatric disease is an enormous responsibility. We follow
the highest standards of quality and safety and expect accountability from each other.
Integrity
At all times, we approach our work with openness, transparency, decency and humility. It is our
responsibility to use resources wisely to sustain Seattle Children’s for generations to come.
Collaboration
We work in partnership with patients, their families, staff, providers, volunteers and donors. This
spirit of respectful cooperation extends beyond our walls to our business partners and the
community.
Equity
We embrace and find strength in the diversity of our patients, their families, staff and
community. We believe all children deserve exceptional care, the best outcomes, respect and a
safe environment.
Innovation
We aspire to be an innovative leader in pediatric healthcare, research and philanthropy. We
continually seek new and better solutions. Because innovation springs from knowledge, we
foster learning in all disciplines.
b) Rochester Regional Health
Mission statement:-
To enhance lives and preserve health by enabling access to a comprehensive, fully integrated
network of the highest quality and most affordable care, delivered with kindness, integrity and
respect.
Value Statement:-
Quality
By setting and surpassing higher standards, we will continue to build a smarter, faster, more
efficient organization that delivers excellent, appropriate care in the right place at the right time.
Compassion
Our culture of caring will be unmistakable in every personal interaction as we treat individuals,
families and colleagues with empathy, honesty and openness.
Respect
We will treat each individual with caring consideration and value the diverse perspectives each
one of them can bring.
Collaboration
By w.
Did colonial rule freeze colonized societies by preserving old s.pdfjyothimuppasani1
Did colonial rule \"freeze\" colonized societies by preserving old social and economic patterns,
or was colonial rule a disruptive force of change?
Provide specific evidence to support each side of this question.
Solution
Transforming: Colonial rule gave African women greater autonomy in their day to day lives,
some of whom took advantage of trade.
New opportunities were also offered to cash crop farmers who were able to use colonial trade
networks for their own benefit.
Large scale conversion of some populations to Christianity
A minority got Western educations, which transformed their lives and their vision of their
society.
Preserving: No colonial society underwent Japanese-style industrialization.
Colonial societies engages mostly in primary economic activities, such as agriculture.
Colonialism stunted the growth of the middle class, creating unstable societies.
The practice of ruling through established authorities maintained the status quo..
Do you think that nonhuman animals have interests Does this mean th.pdfjyothimuppasani1
Do you think that nonhuman animals have interests? Does this mean that they also have rights?
Explain.
Solution
Human beings are living beings and so are the animals. A man is a known as a social animal only
because he has the ability to speak and interact in a more civilized way than any other animals.
But having said that, the rights surrounding to the human beings such as the ‘Right to live’,
remains the same even for the feral human beings who are such humans who are raised in the
Jungle and are isolated for some reason from the human world or contact. In this regard, if one
cannot distinguish a feral child, who can simply screech or crawl, rather than walk on two legs
and behave more like animals than like humans, from that of any other civilized human being,
then such a distinguished nature of human beings towards the nonhuman animals, is simply a
biased opinion. Animals are mute. They cannot speak for themselves. But they too have a heart
that throb like a human. They feel hunger. They feel the pain too. Even they long
companionship. They long for a community of their own to co-stay. Hence, I do believe
nonhuman animals do have interests. In such a case, they also have rights. They are simply
helpless because they are unable to reach us out in our ways. But that is not their fault. Perhaps
the rule of nature. The nature requires all to co-exist and hence the Noah’s ark once gave shelter
to creatures of all kind and not just restricted to the mankind. Even the nature wants the creatures
to live in harmony and that is possible when we do not invade their territory but of course, let not
them invade ours too. However, in today’s world, man’s greed has unturned the entire balanced
eco-cycle. We have deeply penetrated into the woods and concretized the Jungle to the extent
that we have quite literally done away with the interests of these nonhuman animals. For the
balanced eco-system, the contribution of the nonhuman animals have also been very significant.
But in a course of time, we snatched away their rights. Yes, we have laws in place to protect the
near-to-extinct animals or to stop killing or preying the nonhuman animals for organs selling and
other purposes. However, the illegal exploitation of these nonhuman animals have only helped us
think that perhaps the interests of the nonhumans or their rights are of much lesser importance
than that of the pleasure of the human beings for the only reason being that we, the humans can
speak and represent for ourselves. In the mask of civilization, we are rather heading to a more
sophisticated way of demeaning the rights of the animals or their interests..
Discuss the importance of recognizing and implementing different ent.pdfjyothimuppasani1
Discuss the importance of recognizing and implementing different entry strategies and
organizational arrangements which result in shared control and oversight through collaborative
relationships
Solution
Entry strategies are explained as a well planned method through which the company decide to
delivery its good and services to the targeted market.
The different types of market entry strategies and organizational arrangement and its importance
are discussed below:
1 .Exporting: when goods/Product are produced in one country and marketed in another country
then it is known as exporting.
2. Licensing: When a firm permit the company operating in another company to use its
manufacturing process, copyrights, and trademark with specific and determined payment.
3. Franchising: It’s an agreement between two companies, where a company (the franchiser)
gives all its rights to another company (the franchisee) to use its trademark, manufacturing
process and market to certain specification.
4. Joint venturing: In this two companies or investors share ownership and control over the
finance and operations of the firm.
5. Contract Manufacturing: In this the company operating in foreign countries gets into contract
to with the country operating there for manufacturing or assembling of the product.
6. Merger & Acquisitions: It is defined as restructuring of organization, for positive growth and
value. Merger means to ‘merge’ in which two companies legally merge into one into one entity,
whereas an acquisition means when one company takes over another and completely become
new owner.
All the entry strategies discussed above results in shared control through collaborative
relationships..
Considering the challenges she is facing, what Anitas plan before .pdfjyothimuppasani1
Considering the challenges she is facing, what Anita\'s plan before the strategic planning retreat?
How would you reformulate the art center mission, has the center need a new strategy? why or
why not?
Solution
Anitha wants to bring some new innovation arts to the Arts center. This also brings more profit
for her. People who are crazy of arts expect more attractive and interesting arts,so she has to
increase her quality of arts to entertain the art lovers. Few people who don\'t have any knowledge
about arts also started trying out with arts. The art center mission can be reformulated by
inspiring them in participating in performances and they have to feel that what time they have
towards arts must be meaningful.
The strategy that can be used by sponsoring and contributing. This work can get help by adding
partners also. Through this they can teach others and also bring their talents out. By performing
like this the whole community gets attracted and her dream comes true. Through this they can
bring out the most hidden artists in the community and many artists are come out showing their
excellence in their art..
Data Structure in C++Doubly Linked Lists of ints httpstaffwww.pdfjyothimuppasani1
Data Structure in C++
Doubly Linked Lists of ints
http://staffwww.fullcoll.edu/aclifton/courses/cs133_fa16/files/dlist.h
This is my code below: dlist.cc
-------------------------------------------------------------------------------------------------------
#include
#include \"dlist.h\"
dlist::node* dlist::at(int n){
node* c = _head;
while(n > 0 && c){
c = c->next;
n--;
}
return c;
}
void dlist::insert(node* previous, int value){
node* n = new node{value, previous->next};
previous->next = n;
}//update tail
void dlist::del(node* which){
node* nn = which->next;
which->next = nn->next;
delete nn;
}
void dlist::push_back(int value){
node* n = new node{value, nullptr};
_tail->next = n;
_tail-> n;
}
void dlist::push_front(int value){
node* n = new node(value, nullptr);
_head->prev = n;
_head-> n;
}
void dlist::pop_front(){
node* n = _head;
_head = _head->next;
delete n;
}
void dlist::pop_back(){
node* n = _tail;
_tail = _tail->prev;
delete n;
}
int dlist::size() {
node* c = _head;
int s = 0;
while(c){
s++;
c = c->next;
}
return s;
}
--------------------------------------------------------------------------------
Please fix and complete my code, and I also need whole code contatining main function for
testing dlist.cc In this assignment, you will implement a doubly-linked list class. together with
some list operations. To make things easier, you\'ll implement a list of int rather than a template
class pragma once dlist. h Doubly linked lists of ints include Kostream class dlist public: d list
struct node int value node next node prev; node\' head() const return -head; node\" tail() const t
return -tail Implement ALL the following methods Returns the node at a particular index (0 is the
head node at(int) Insert a new value, after an existing one void insert(node *previous int value
Delete the given node void del (node which)
Solution
#include
#include
#include
/*
* Node Declaration
*/
using namespace std;
struct node
{
int value;
string name;
struct node *next;
struct node *prev;
}*start;
/*class declaration
class dlist
{
public:
void create_list(int value);
void push_front(int value);
void push_back(int value, int position);
void pop_front(int value);
void pop_back(int value);
void display_dlist();
void reverse();
dlist()
{
start = NULL;
head=NULL;
last=NULL;
}
bool empty() const { return head==NULL; }
friend ostream& operator<<(ostream& ,const dlist& );
void insert(const string& );
void remove(const string& );
private:
node* head() const { return _head; }
node* tail() const { return _tail; }
};
dlist.cc:
/* Create Double Link List*/
void dlist::create_list(int value)
{
struct node *s, *temp;
temp = new(struct node);
temp->info = value;
temp->next = NULL;
if (start == NULL)
{
temp->prev = NULL;
start = temp;
}
else
{
s = start;
while (s->next != NULL)
s = s->next;
s->next = temp;
temp->prev = s;
}
}
/*
* Insertion at the beginning
*/
void dlist::add_begin(int value)
{
if (start == NULL)
{
cout<<\"First Create the list.\"<prev = NULL;
temp->info = val.
Conceptual skills are most important at theSolutionConceptual .pdfjyothimuppasani1
Conceptual skills are most important at the
Solution
Conceptual skills relate to the managers\' mental ability to coordinate and integrate all of the
organization\'s interests and activities. It is about thinking in the abstract and observing
relationships between forces that many others may not be able to see and to take a global
perspective of the organization and its environment. This is not so relevant at the lower level of
management and is most important at the top management level because the senior managers
must look for and exploit unseen opportunities for their organizations..
A variable whose scope is restricted to the method where it was decl.pdfjyothimuppasani1
A variable whose scope is restricted to the method where it was declared is known as a(n)
parameter
global variable
local variable
public instance data
private instance data
parameter
global variable
local variable
public instance data
private instance data
Solution
Answer is \"Local Variable\"
Parameter: parameter is something which is passed to the method, and not declared in the
method.
Global Variable: Global Variable is accessible from anywhere in the program. And not just
restricted to a certain method..
•Design (create) 3 questions for a quiz show game and design regular.pdfjyothimuppasani1
•Design (create) 3 questions for a quiz show game and design regular expressions that validate
the answers. The challenge is to be no more and no less exacting than a human checker. I have
the sample quiz done already.email me for code
Solution
Database design
• Not easy!
• Will discuss formal methods next week
• Review: databases are made up of
– Tables: tables made up of
• Records: records made up of fields
• Speaking of rows and columns is misleading
• Critical issue: fixed number of fields, though a
specific field may be optional (aka not required)
– NOT NULL in MySQL jargon means required!
– MySQL does support variable length strings.
Data types
• Terminology varies for different DBMS
products
• Performance (speed) of operations varies
with different datatypes
• Size varies with different datatypes
• Performance and size limits are points of
competition among the different products
MySQL datatypes: numbers
• INT (aka INTEGER), can be UNSIGNED
(Size 4 bytes = 32 bits)
• TINYINT, SMALLINT, MEDIUMINT,
BIGINT
– Different sizes
• float (4 bytes), double (8 bytes), can
specify precision within these limits
• more
MySQL datatypes, strings
• CHAR(specified length)
• VARCHAR(maximum length)
• TINYBLOB short, variable length string,
up to 255 characters
• BLOB, TEXT variable length string
• MEDIUMBLOB, MEDIUMTEXT,
LONGBLOB, LONGTEXT
MySQL datatypes: enum
• ENUM
– Specify one of a set of values
– Stored as an integer, with 0 indicated unset or
not in the specified set
– Doing this may be more efficient because
built-in MySQL routines do the searching
MySQL datatypes: date/time
• DATE
• TIME
• DATETIME
• YEAR
• TIMESTAMP
Tables
• Specify one field as the primary key
• Primary keys are unique IN THAT TABLE
– Let the DBMS create the primary key OR
– Depend on intrinsic value that is guaranteed to be
unique
• Email addresses
• ISBN numbers
• ?
• A field in one table may be a foreign key. This is
a reference to a primary key in another table (or
this table). MORE ON THIS LATER.
Database
• Assume database itself is created for us
AND we have permissions to create new
tables.
• NOTE: permissions can be set by MySQL
commands, including queries sent by php.
• Start off talking general SQL and then
specific php and MySQL
Create table example
• CREATE TABLE movies (
mid INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,
mname CHAR(30),
mdesc TEXT,
myear YEAR
)
Create table example
CREATE TABLE players (
pid INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,
pname CHAR(30),
score INT NOT NULL,
lastplayed DATE
)
Create example
CREATE TABLE games (
gid INT NOT NULL AUTO_INCREMENT
PRIMARY KEY,
pid INT,
gtime TIMESTAMP,
score INT
)
The pid field will refer to / have the value of
the pid field (the primary key) of a specific
player. Here in this table, it is called a
foreign key.
Foreign keys
• Some versions of MySQL (and other DBMS)
have ways to specify the the pid value is a
foreign key
pid INT REFERENCE players
• The DBMS will check to make sure it is a valid
value.
• Since the php.
You are to write a GUI program that will allow a user to buy, sell a.pdfjyothimuppasani1
You are to write a GUI program that will allow a user to buy, sell and view stocks in a stock
portfolio.
Objective:
Write a GUI program that maintains a cash balance, list of stock holdings, supports buying and
selling of stocks and displays the current portfolio inventory.
Program Capabilities:
1. Allow a user to buy a stock with a given number of shares and price per share.
2. Display the current portfolio (stock ticker, number of shares, initial price).
3. Update the portfolio display for purchases and sales.
4. Allow the user to sell all of the shares of a given stock.
5. Give the user an initial cash balance, and update and display the balance according to the
user\'s purchases and sales.
6. Ignore any transaction that causes the cash position to go below $0.
USE OF PREVIOUS StockHolding and PortfolioList LABS IS ADVISED. (I\'ve including my
solutions to these below)
This is my written code from earlier homework:
public class StockHolding {
private String ticker;
private int numShares;
private double initialSharePrice;
private double currentSharePrice;
public StockHolding(String ticker, int numberShares, double initialPrice) {
this.ticker = ticker;
numShares = numberShares;
initialSharePrice = initialPrice;
currentSharePrice = initialPrice;
}
public double getCurrentValue() {
return numShares * getCurrentSharePrice();
}
public double getInitialCost() {
return numShares * getInitialSharePrice();
}
public double getCurrentProfit() {
return getCurrentValue() - getInitialCost();
}
public double getCurrentSharePrice() {
return currentSharePrice;
}
public void setCurrentSharePrice(double currentSharePrice) {
this.currentSharePrice = currentSharePrice;
}
public String getTicker() {
return ticker;
}
public int getShares() {
return numShares;
}
public double getInitialSharePrice() {
return initialSharePrice;
}
@Override
public String toString() {
return \"Stock \" + ticker + \", \" + numShares + \", shares bought at \"
+ initialSharePrice + \", current price \"
+ currentSharePrice;
}
}
AND
import java.util.ArrayList;
public class PortfolioList {
private ArrayList portfolio;
public PortfolioList() {
portfolio = new ArrayList();
}
public void add(StockHolding stock) {
portfolio.add(stock);
}
public StockHolding find(String ticker) {
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
return sh;
}
}
return null;
}
public void remove(String ticker) {
int pos = -1;
for (int i = 0; i < portfolio.size(); i++) {
StockHolding sh = portfolio.get(i);
if (sh.getTicker().equals(ticker)) {
pos = i;
}
}
if (pos != -1) {
portfolio.remove(pos);
}
}
I\'ve been staring at this for two days, and I am lost. Please, any guidance/help would be greatly
appreciated.
Honestly don\'t even need a full solution, just need something to kick start. A comment skeleton
would help a ton. Thanks!
Solution
SOURCE CODE:
package stock;
public class StockHolding {
private String ticker;
private int numShares;
private do.
write the To Dos to get the exact outputNOte A valid Fraction .pdfjyothimuppasani1
write the To Do\'s to get the exact output:
NOte: A valid Fraction number has a non-negative numerator and a positive denominator.
Default constructor initializes the object to safe empty state (an object with denom equals -1).
The two-argument constructor also validates the parameters and sets the object to the safe empty
state if the parameters are not valid.
Write the definitions and prototypes of following functions in Fraction.cpp and Fraction.h
respectively (They are indicated in the files by //TODO tag):
Define isEmpty function as a member function, which returns true if the object is in safe empty
state (an object is in the safe empty state if denominator (denom) equals -1).
Define display function, which sends a Fraction number to the output stream (with the
“Numerator/denominator” format). This function just prints \"Invalid Fraction Object!\" in the
screen if the object is in the safe empty state. In case that object denominator equals 1, it just
print the numerator.
Define the operator functions for the following operators:
“+=”, “+”, “*”
The overload of the above operators should make the following code possible:
The member operator+ : Adds two Fraction numbers and returns a Fraction number as the result.
This function returns an object with the safe empty state if either of Fraction numbers (operands)
is in safe empty state. It makes following code possible:
A+B ( where A and B are Fraction objects)
The member operator+= : Adds two Fraction numbers and assigns the result to the left operand,
then returns a reference to the left operand. If either of Fraction numbers (operands) is in safe
empty state, it initializes the left operand to the safe empty state, then returns a reference to the
left operand. It makes following code possible:
A+=B ( where A and B are Fraction objects)
The member operator* : Multiplies two Fraction numbers and returns a Fraction number as the
result. This function returns an object with the safe empty state if either of Fraction numbers
(operands) is in safe empty state. It makes following code possible:
A*B ( where A and B are Fraction objects)
fraction.cpp
#include \"Fraction.h\"
using namespace std;
namespace sict{
Fraction::Fraction(){
denom =-1; // safe empty state
}
Fraction::Fraction(int n, int d) // n: numerator, d: denominator
{
if(n >= 0 && d > 0){
num = n;
denom = d;
reduce();
}
else
denom =-1; // set to safe empty state
}
int Fraction::gcd() // returns the greatest common divisor of num and
denom
{
int mn = min(); // min of num and denom
int mx = max(); // mX of num and denom
for (int x=mn ; x > 0 ; x--) // find the greatest common divisor
if( mx % x == 0 && mn % x == 0)
return x;
return 1;
}
void Fraction::reduce() // simplify the Fraction number
{
int tmp = gcd();
num /= tmp;
denom /= tmp;
}
int Fraction::max ()
{
return (num >= denom) ? num : denom;
}
int Fraction::min()
{
return (num >= denom) ? denom : num;
}
// in_lab
// TODO: write the implementation of display function HERE
// TODO: w.
What are the factors that contribute to H+ gain or loss How do lung.pdfjyothimuppasani1
What are the factors that contribute to H+ gain or loss? How do lungs and the kidneys balance or
regulate the changes in pH?
Solution
Answer=
Factors that contribute to loss or gain of H ions are=
CO2 concentration
O2 concentration
bicarbonate concentration in urine
The lungs regulate the changes in PH = Acid base imbalances in the bloods pH can be altered by
changes in breathing to expel ,ore CO2 & raise the pH back to normal
Hydrogen ions are carried in the blood along with oxygen & carbon dioxide
60 % CO2 is carried as a dissolved bicarbonate
A small amount of CO2 is carried on Haemoglobin as carbaminohaemoglobin which is
transported to the lungs for removal
Acid base imbalances that overcome the buffer system can be compensated in the short term by
changing the rate of ventilation
When pH of blood drops too low ,the body compensates by increasing breathing to expel more
CO2 & during alkalemia the inspiration occurs
Regulation of pH by kidneys =
kidneys have 2 important roles in maintaining the acid -base balance
1]They reabsorb bicarbonate from urine
2] they excrete hydrogen ions into urine
The major homeostatic control point for maintaining a stable pH balance is renal excretion
Bicarbonate does not have transporter ,so its reabsorption involves a series of reactions in the
tubule lumen & tubular epithelium .
In response tyo acidosis the tubular cells reabsorb more bicarbonate from the tubular fluid ,& the
collecting cells secrete more hydrogen & generate more bicarbonate
In response to alkalosis ,the kidneys may excrete more bicarbonate by decreasing Hydrogen ion
secretion from tubular epithelial cells ,& lowering the rates of glutamine metabolism &
ammonium excretion.
Write down the four (4) nonlinear regression models covered in class,.pdfjyothimuppasani1
Write down the four (4) nonlinear regression models covered in class, i.e. both the name of the
model and their functional form showing their respective regression coefficients. A rapidly
growing bacteria has been discovered with a growth rate as shown in the table. Analyze this date
using a power law model. First linearize the data in the table based on the power law model, call
this new linearized data x and y. Next, determine the coefficients a_0 and a_1 of a linear
regression y = a_0 + a_1x for the linearized power law data x and y, and compute the correlation
coefficient for the liner regression. Note that you are not being asked to do a linear regression of
the data in the table but rather a linear regression of the linearized version of that data. Once you
compute a_0 and a_1 use these to determine the coefficients of the power law model. Write a
Matlab script that uses the polyfit function to determine the regression coefficients of a second
order polynomial fit to data in the table. In the same script, write down the code for using the
polyval command to determine the value of the regression curve at the observed times.
Solution
Nonlinear regression is a statistical technique that helps describe nonlinear relationships in
experimental data. A nonlinear regression model can be written Yn = f(xn, ) + Zn where f is the
expectation function and xn is a vector of associated regressor variables or independent variables
for the nth case.
A nonlinear model is one in which at least one of the parameters appears nonlinearly. More
formally, in a nonlinear model, at least one derivative with respect to a parameter should involve
that parameter. Examples of a nonlinear model are:
Y(t) = exp(at+bt2)
Y(t) = at + exp(-bt).
Important non linear growth models
1.Logistic Model
This model is represented by the differential equation
dN/dt = rN (1-N/K).
Integrating, we get
N(t) = K / [1+(K/No-1) exp(-rt)]
The graph of N(t) versus t is elongated S-shaped and the curve is symmetrical about its point of
inflexion.
2.Malthus Model
If N(t) denotes the population size or biomass at time t and r is the intrinsic growth rate, then the
rate of growth of population size is given by
dN/dt = rN.
Integrating, we get
N(t) = No exp (rt),
where No denotes the population size at t=0. Thus this law entails an exponential increase for
r>0. Furthermore, N(t) à as t à , which cannot happen in reality.
3. Monomolecular Model
This model describes the progress of a growth situation in which it is believed that the rate of
growth at any time is proportional to the resources yet to be achieved, i.e.
dN/dt = r(K-N),
where K is the carrying size of the system. Integrating (3.3), we get
N(t) = K-(K-No) exp (-rt).
4. Richards Model.
This model is given by dN/dt = rN (KN – Nm)/mKm which, on integration, gives N(t )=K N0 /[
N0+ (KN – N0m) exp (-rt)]1/m.
Unlike the earlier models, this model has four parameters
Hours (H)
10
20
40
50
No fo bacteria (N)
25
70
380
550
610
b)
N = b H m
Log10.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...Levi Shapiro
Letter from the Congress of the United States regarding Anti-Semitism sent June 3rd to MIT President Sally Kornbluth, MIT Corp Chair, Mark Gorenberg
Dear Dr. Kornbluth and Mr. Gorenberg,
The US House of Representatives is deeply concerned by ongoing and pervasive acts of antisemitic
harassment and intimidation at the Massachusetts Institute of Technology (MIT). Failing to act decisively to ensure a safe learning environment for all students would be a grave dereliction of your responsibilities as President of MIT and Chair of the MIT Corporation.
This Congress will not stand idly by and allow an environment hostile to Jewish students to persist. The House believes that your institution is in violation of Title VI of the Civil Rights Act, and the inability or
unwillingness to rectify this violation through action requires accountability.
Postsecondary education is a unique opportunity for students to learn and have their ideas and beliefs challenged. However, universities receiving hundreds of millions of federal funds annually have denied
students that opportunity and have been hijacked to become venues for the promotion of terrorism, antisemitic harassment and intimidation, unlawful encampments, and in some cases, assaults and riots.
The House of Representatives will not countenance the use of federal funds to indoctrinate students into hateful, antisemitic, anti-American supporters of terrorism. Investigations into campus antisemitism by the Committee on Education and the Workforce and the Committee on Ways and Means have been expanded into a Congress-wide probe across all relevant jurisdictions to address this national crisis. The undersigned Committees will conduct oversight into the use of federal funds at MIT and its learning environment under authorities granted to each Committee.
• The Committee on Education and the Workforce has been investigating your institution since December 7, 2023. The Committee has broad jurisdiction over postsecondary education, including its compliance with Title VI of the Civil Rights Act, campus safety concerns over disruptions to the learning environment, and the awarding of federal student aid under the Higher Education Act.
• The Committee on Oversight and Accountability is investigating the sources of funding and other support flowing to groups espousing pro-Hamas propaganda and engaged in antisemitic harassment and intimidation of students. The Committee on Oversight and Accountability is the principal oversight committee of the US House of Representatives and has broad authority to investigate “any matter” at “any time” under House Rule X.
• The Committee on Ways and Means has been investigating several universities since November 15, 2023, when the Committee held a hearing entitled From Ivory Towers to Dark Corners: Investigating the Nexus Between Antisemitism, Tax-Exempt Universities, and Terror Financing. The Committee followed the hearing with letters to those institutions on January 10, 202
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
File encryption. [32] Write a program which accepts a filename as a .pdf
1. File encryption. [32] Write a program which accepts a filename as a command-line argument [-
32]. It should then ask for a password via stdin (but it should not visible when entered; use
getpass for this) [4]. The program should encrypt the file using a block-cipher algorithm (see
encryption.rst for details) [12] if it was not already encrypted by the program, and rename it with
a .enc extension. If it was already encrypted, it should decrypt the file and remove the .enc
extension [12]. Under no circumstance should the program multiply encrypt the file [4]. Call the
program encrypt.cpp. here is encrypt.rst Suppose I have an input file to encrypt: .. raw: The only
true wisdom is in knowing you know nothing. (A quote by Socrates.) What I can do then is ask
the user for a password. Suppose the user enters kitties. Then what I may do is pre-pend the
password to an output file, and add kitties in rounds to the file: .. raw: kittiesThe only true
wisdom is in knowing you know nothing. + kittieskittieskittieskittieskittieskittieskittieskittieskit -
---------------------------------------------------------- =
fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd When I add the characters in the
string kitties, I get what appears to be jumbled garbage. Without the password, it is hard to
decrypt the file. To decrypt the file, I ask the user for the password. Suppose they enter bubbles
(the wrong password). .. raw: fhdkalhfioepwah... - bubbles ------------------ = ueiaqnv I see that
by subtracting bubbles off the encrypted text, I do not get the string bubbles back, so bubbles is
not the password. If the user enters kitties (the correct password): .. raw: fhdkalhfioepwah... -
kitties ------------------ = kitties Then I see that what I get back is kitties, and since it matches the
user password entered, I may proceed to decrypt the rest of the file simply by subtracting kitties
off it in rounds. .. raw: = fhdkalhfioepwahfkdsanklvcxznkjvpwipqnkxlkdlajsflkjkljkljlkd -
kittieskittieskittieskittieskittieskittieskittieskittieskit ------------------------------------------------------
----- kittiesThe only true wisdom is in knowing you know nothing. Thus I obtain the original
message. Notice the user-supplied password itself is a necessary element of the decryption. This
type of algorithm is called a block cipher algorithm.
Solution
// Encrypting_a_File.cpp : Defines the entry point for the console
// application.
//
#include
#include
#include
#include
2. #include
// Link with the Advapi32.lib file.
#pragma comment (lib, "advapi32")
#define KEYLENGTH 0x00800000
#define ENCRYPT_ALGORITHM CALG_RC4
#define ENCRYPT_BLOCK_SIZE 8
bool MyEncryptFile(
LPTSTR szSource,
LPTSTR szDestination,
LPTSTR szPassword);
void MyHandleError(
LPTSTR psz,
int nErrorNumber);
int _tmain(int argc, _TCHAR* argv[])
{
if(argc < 3)
{
_tprintf(TEXT("Usage: ")
TEXT(" | "));
_tprintf(TEXT(" is optional. "));
_tprintf(TEXT("Press any key to exit."));
_gettch();
return 1;
}
LPTSTR pszSource = argv[1];
LPTSTR pszDestination = argv[2];
LPTSTR pszPassword = NULL;
if(argc >= 4)
{
pszPassword = argv[3];
}
//---------------------------------------------------------------
// Call EncryptFile to do the actual encryption.
if(MyEncryptFile(pszSource, pszDestination, pszPassword))
{
_tprintf(
3. TEXT("Encryption of the file %s was successful. "),
pszSource);
_tprintf(
TEXT("The encrypted data is in file %s. "),
pszDestination);
}
else
{
MyHandleError(
TEXT("Error encrypting file! "),
GetLastError());
}
return 0;
}
//-------------------------------------------------------------------
// Code for the function MyEncryptFile called by main.
//-------------------------------------------------------------------
// Parameters passed are:
// pszSource, the name of the input, a plaintext file.
// pszDestination, the name of the output, an encrypted file to be
// created.
// pszPassword, either NULL if a password is not to be used or the
// string that is the password.
bool MyEncryptFile(
LPTSTR pszSourceFile,
LPTSTR pszDestinationFile,
LPTSTR pszPassword)
{
//---------------------------------------------------------------
// Declare and initialize local variables.
bool fReturn = false;
HANDLE hSourceFile = INVALID_HANDLE_VALUE;
HANDLE hDestinationFile = INVALID_HANDLE_VALUE;
HCRYPTPROV hCryptProv = NULL;
HCRYPTKEY hKey = NULL;
HCRYPTKEY hXchgKey = NULL;
5. FILE_SHARE_READ,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(INVALID_HANDLE_VALUE != hDestinationFile)
{
_tprintf(
TEXT("The destination file, %s, is open. "),
pszDestinationFile);
}
else
{
MyHandleError(
TEXT("Error opening destination file! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//---------------------------------------------------------------
// Get the handle to the default provider.
if(CryptAcquireContext(
&hCryptProv,
NULL,
MS_ENHANCED_PROV,
PROV_RSA_FULL,
0))
{
_tprintf(
TEXT("A cryptographic provider has been acquired. "));
}
else
{
MyHandleError(
TEXT("Error during CryptAcquireContext! "),
GetLastError());
goto Exit_MyEncryptFile;
6. }
//---------------------------------------------------------------
// Create the session key.
if(!pszPassword || !pszPassword[0])
{
//-----------------------------------------------------------
// No password was passed.
// Encrypt the file with a random session key, and write the
// key to a file.
//-----------------------------------------------------------
// Create a random session key.
if(CryptGenKey(
hCryptProv,
ENCRYPT_ALGORITHM,
KEYLENGTH | CRYPT_EXPORTABLE,
&hKey))
{
_tprintf(TEXT("A session key has been created. "));
}
else
{
MyHandleError(
TEXT("Error during CryptGenKey. "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Get the handle to the exchange public key.
if(CryptGetUserKey(
hCryptProv,
AT_KEYEXCHANGE,
&hXchgKey))
{
_tprintf(
TEXT("The user public key has been retrieved. "));
}
7. else
{
if(NTE_NO_KEY == GetLastError())
{
// No exchange key exists. Try to create one.
if(!CryptGenKey(
hCryptProv,
AT_KEYEXCHANGE,
CRYPT_EXPORTABLE,
&hXchgKey))
{
MyHandleError(
TEXT("Could not create "
"a user public key. "),
GetLastError());
goto Exit_MyEncryptFile;
}
}
else
{
MyHandleError(
TEXT("User public key is not available and may ")
TEXT("not exist. "),
GetLastError());
goto Exit_MyEncryptFile;
}
}
//-----------------------------------------------------------
// Determine size of the key BLOB, and allocate memory.
if(CryptExportKey(
hKey,
hXchgKey,
SIMPLEBLOB,
0,
NULL,
&dwKeyBlobLen))
8. {
_tprintf(
TEXT("The key BLOB is %d bytes long. "),
dwKeyBlobLen);
}
else
{
MyHandleError(
TEXT("Error computing BLOB length! "),
GetLastError());
goto Exit_MyEncryptFile;
}
if(pbKeyBlob = (BYTE *)malloc(dwKeyBlobLen))
{
_tprintf(
TEXT("Memory is allocated for the key BLOB. "));
}
else
{
MyHandleError(TEXT("Out of memory. "), E_OUTOFMEMORY);
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Encrypt and export the session key into a simple key
// BLOB.
if(CryptExportKey(
hKey,
hXchgKey,
SIMPLEBLOB,
0,
pbKeyBlob,
&dwKeyBlobLen))
{
_tprintf(TEXT("The key has been exported. "));
}
else
9. {
MyHandleError(
TEXT("Error during CryptExportKey! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Release the key exchange key handle.
if(hXchgKey)
{
if(!(CryptDestroyKey(hXchgKey)))
{
MyHandleError(
TEXT("Error during CryptDestroyKey. "),
GetLastError());
goto Exit_MyEncryptFile;
}
hXchgKey = 0;
}
//-----------------------------------------------------------
// Write the size of the key BLOB to the destination file.
if(!WriteFile(
hDestinationFile,
&dwKeyBlobLen,
sizeof(DWORD),
&dwCount,
NULL))
{
MyHandleError(
TEXT("Error writing header. "),
GetLastError());
goto Exit_MyEncryptFile;
}
10. else
{
_tprintf(TEXT("A file header has been written. "));
}
//-----------------------------------------------------------
// Write the key BLOB to the destination file.
if(!WriteFile(
hDestinationFile,
pbKeyBlob,
dwKeyBlobLen,
&dwCount,
NULL))
{
MyHandleError(
TEXT("Error writing header. "),
GetLastError());
goto Exit_MyEncryptFile;
}
else
{
_tprintf(
TEXT("The key BLOB has been written to the ")
TEXT("file. "));
}
// Free memory.
free(pbKeyBlob);
}
else
{
//-----------------------------------------------------------
// The file will be encrypted with a session key derived
// from a password.
// The session key will be recreated when the file is
// decrypted only if the password used to create the key is
// available.
//-----------------------------------------------------------
11. // Create a hash object.
if(CryptCreateHash(
hCryptProv,
CALG_MD5,
0,
0,
&hHash))
{
_tprintf(TEXT("A hash object has been created. "));
}
else
{
MyHandleError(
TEXT("Error during CryptCreateHash! "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
// Hash the password.
if(CryptHashData(
hHash,
(BYTE *)pszPassword,
lstrlen(pszPassword),
0))
{
_tprintf(
TEXT("The password has been added to the hash. "));
}
else
{
MyHandleError(
TEXT("Error during CryptHashData. "),
GetLastError());
goto Exit_MyEncryptFile;
}
//-----------------------------------------------------------
12. // Derive a session key from the hash object.
if(CryptDeriveKey(
hCryptProv,
ENCRYPT_ALGORITHM,
hHash,
KEYLENGTH,
&hKey))
{
_tprintf(
TEXT("An encryption key is derived from the ")
TEXT("password hash. "));
}
else
{
MyHandleError(
TEXT("Error during CryptDeriveKey! "),
GetLastError());
goto Exit_MyEncryptFile;
}
}
//---------------------------------------------------------------
// The session key is now ready. If it is not a key derived from
// a password, the session key encrypted with the private key
// has been written to the destination file.
//---------------------------------------------------------------
// Determine the number of bytes to encrypt at a time.
// This must be a multiple of ENCRYPT_BLOCK_SIZE.
// ENCRYPT_BLOCK_SIZE is set by a #define statement.
dwBlockLen = 1000 - 1000 % ENCRYPT_BLOCK_SIZE;
//---------------------------------------------------------------
// Determine the block size. If a block cipher is used,
// it must have room for an extra block.
if(ENCRYPT_BLOCK_SIZE > 1)
{
dwBufferLen = dwBlockLen + ENCRYPT_BLOCK_SIZE;
13. }
else
{
dwBufferLen = dwBlockLen;
}
//---------------------------------------------------------------
// Allocate memory.
if(pbBuffer = (BYTE *)malloc(dwBufferLen))
{
_tprintf(
TEXT("Memory has been allocated for the buffer. "));
}
else
{
MyHandleError(TEXT("Out of memory. "), E_OUTOFMEMORY);
goto Exit_MyEncryptFile;
}
//---------------------------------------------------------------
// In a do loop, encrypt the source file,
// and write to the source file.
bool fEOF = FALSE;
do
{
//-----------------------------------------------------------
// Read up to dwBlockLen bytes from the source file.
if(!ReadFile(
hSourceFile,
pbBuffer,
dwBlockLen,
&dwCount,
NULL))
{
MyHandleError(
TEXT("Error reading plaintext! "),
GetLastError());
15. //-----------------------------------------------------------
// End the do loop when the last block of the source file
// has been read, encrypted, and written to the destination
// file.
} while(!fEOF);
fReturn = true;
Exit_MyEncryptFile:
//---------------------------------------------------------------
// Close files.
if(hSourceFile)
{
CloseHandle(hSourceFile);
}
if(hDestinationFile)
{
CloseHandle(hDestinationFile);
}
//---------------------------------------------------------------
// Free memory.
if(pbBuffer)
{
free(pbBuffer);
}
//-----------------------------------------------------------
// Release the hash object.
if(hHash)
{
if(!(CryptDestroyHash(hHash)))
{
MyHandleError(
TEXT("Error during CryptDestroyHash. "),
GetLastError());
}
hHash = NULL;
}
16. //---------------------------------------------------------------
// Release the session key.
if(hKey)
{
if(!(CryptDestroyKey(hKey)))
{
MyHandleError(
TEXT("Error during CryptDestroyKey! "),
GetLastError());
}
}
//---------------------------------------------------------------
// Release the provider handle.
if(hCryptProv)
{
if(!(CryptReleaseContext(hCryptProv, 0)))
{
MyHandleError(
TEXT("Error during CryptReleaseContext! "),
GetLastError());
}
}
return fReturn;
} // End Encryptfile.
//-------------------------------------------------------------------
// This example uses the function MyHandleError, a simple error
// handling function, to print an error message to the
// standard error (stderr) file and exit the program.
// For most applications, replace this function with one
// that does more extensive error reporting.
void MyHandleError(LPTSTR psz, int nErrorNumber)
{
_ftprintf(stderr, TEXT("An error occurred in the program. "));
_ftprintf(stderr, TEXT("%s "), psz);