Useful functions in all languages ​​- Page 3 - Programming - HWzone Forums
adplus-dvertising
Skip to content
  • Create an account
  • About Us

    Hello Guest!

     
    Please note - in order to participate in our community, comment and open new discussions, you must join as a registered member.

    Our members enjoy many advantages, including the ability to participate in discussions, enjoy raffles and promotions for members of the site, and receive our weekly content directly by email.

    Do not like being harassed by email? You can register for the site but do not submit your registration to the weekly email updates.

Useful functions in all languages


Pure-Gold

Recommended Posts

When I build scripts with autoit , I find myself repeatedly using INI files to import settings

To my script, because they are very simple and because there is a very cool function in autoit named IniRead .

The project I'm currently working on is in C, so I decided that I wanted a function like that in C ...

I did not find one, so I built one of my own and 2 functions that call it and change the returned value, here are their prototypes:

char * IniReadKey (FILE * ini_file, char * key, char * section, char * default_string)

int IniReadInt (FILE * ini_file, char * key, char * section, int default_value)

short IniReadBool (FILE * ini_file, char * key, char * section, short default_value)

Here's the code:

#define BUFFER_SIZE 1000

char * IniReadKey (FILE * ini_file, char * key, char * section, char * default_string)
{
char buffer [BUFFER_SIZE];
short i;
short section_found = 0, key_found = 0;
char * value;
char * default_value = NULL;


if (default_string)
{
default_value = malloc (strlen (default_string) + 1);
if (default_value)
strcpy (default_value, default_string);
}



if (! ini_file ||! key ||! section) return default_value;

fseek (ini_file, 0, SEEK_SET);


while (fgets (buffer, BUFFER_SIZE, ini_file))
{
if (buffer [0] == '#') continue; / * Comment * /


if (section_found)
{
if (buffer [0] == '[' break; / * If a new section starts and no key was found, break and return * /


for (i = 0, key_found = 1; key_found &&! (buffer [i] == '=' && i! = 0); i ++)
key_found = (toupper (buffer [i]) == toupper (key [i]));

if (key_found)
{
buffer [strlen (buffer) - 1] = '\ 0'; / * Remove the new line character * /

value = malloc ((strlen (buffer) -i));
if (! value) break;

strcpy (value, buffer + (i + 1));

free (default_value); / * We found the value, so we dont need a default value anymore ... * /

return value;
}

else continue;
}

if (buffer [0] == '[') / * new section * /


for (i = 0, section_found = 1; section_found &&! (buffer [i + 1] == ']' && i! = 0); i ++)
section_found = (toupper (buffer [i + 1]) == toupper (section [i]));



}

return default_value;

}


int IniReadInt (FILE * ini_file, char * key, char * section, int default_value)
{
char * tmp_ptr;
int x;

tmp_ptr = IniReadKey (ini_file, key, section, NULL);
if (tmp_ptr == NULL)
return default_value;

x = atoi (tmp_ptr);
free (tmp_ptr);


return x;
}


short IniReadBool (FILE * ini_file, char * key, char * section, short default_value)
{
char * tmp_ptr;

tmp_ptr = IniReadKey (ini_file, key, section, NULL);
if (tmp_ptr == NULL)
return default_value;

switch (toupper (tmp_ptr [0]))
{
case '1':
case 'T': / * True * /
case 'Y': / * YES * /

free (tmp_ptr);
1 return;

case '0':
case 'F': / * False * /
case 'N': / * NO * /

free (tmp_ptr);
0 return;

default:

free (tmp_ptr);
return default_value;
}
}

The idea is that IniReadKey gets a pointer to the file, the key and section it is in, and a value it returns (which can also be NULL)

If it does not find, or a certain error occurs. If IniReadKey finds the key and everything will work properly, IniReadKey will copy the value

Of the key to the heap and return the pointer there. By the way, even if she does not find the key she will assign In heap and transliteration to default_string

There, of course it will not do it if it will be NULL.

2 Other mini functions Their function is to call IniReadKey and turn the value of the key from string to something else.

IniReadInt uses atoi to make the string to int and IniReadBool uses the switch and tries to guess whether it

true or false. Yes, I know that 2 functions are very simple and should not appear here ... but the number of times I have been

Need to make the value of IniReadKey to int already made me sick.

If anyone has found bugs or has had tips to improve the code I would really love to hear

Link to content
Share on other sites

  • תגובות 43
  • Opens on
  • Last comment

In the for loop that you do to compare strings, you should check that the current letter in buffer is not 0 and that you are not exceeding BUFFER_SIZE.

Also in malloc you need to add 1 for null termination.

Link to content
Share on other sites

Thanks for passing through the code, I immediately fixes the bug with strlen and malloc.

Regarding whether to check:

buffer [i]! = '\ 0'

In my opinion this is redundant because if the null terminator is then the following sentence will be 0:

toupper (buffer [i]) == toupper (key [i])

Then the loop will stop running.

As for whether I am not larger than BUFFER_SIZE.

Again, I'm not sure ... because if BUFFER_SIZE is a reasonable size (100 + bytes), what are the chances that all characters will be the same

The key you provide? And even if you're a strange person like me, who likes to give long names you're sure you'll leave room

To '=' and the value itself, remember that as soon as the loop encounters '=' or a letter that does not match the [buffer] i, it goes out.

Link to content
Share on other sites

  • 5 months later ...

A solution for discovering letters in C # when developing games or just textboxes (for those trying to do it with direct input - this is not the solution).

When you want to find out which key is pressed in DirectInput, this is not a problem. But what happens when you try to check which letters the user typed? It is not possible to create a function that converts from DirectInput to char because there are several languages ​​on the computer (usually in Hebrew and English), there are primary and lower letters by CAPS LOCK, there are primary and lower letters by SHIFT and more Which can not be easily tested through DirectInput. The solution is simple - in the form loading the 2 the following functions:


protected override bool ProcessKeyPreview (ref Message m)
{
bool flag = base.ProcessKeyPreview (ref m);

if (m.ToString (). Contains ("WM_CHAR"))
{
SendChar ((char) m.WParam);
}
return flag;
}

protected override bool ProcessKeyEventArgs (ref Message m)
{
bool flag = base.ProcessKeyEventArgs (ref m);

if (m.ToString (). Contains ("WM_CHAR"))
{
SendChar ((char) m.WParam);
}
return flag;
}

When the first is called when there are controls on the form, and the second when there is no.

What actually happens here - we check the messages from the operating system - if we find that the message is on a letter, we call the function called SendChar that you are creating.

There is additional data that can be obtained by lparam (for example, whether alt was pressed at the same time).

This solution in C # language does not yet exist (probably) in Google (I searched for and not found for C #, but for other languages ​​only).

I hope you find it useful.

Edit: Now I found it: http://www.codeproject.com/cs/miscctrl/validatingtextbox.asp

Apparently my tip is not that innovative.

Link to content
Share on other sites

  • 1 month later ...

Peyton Browser Mobile Phones:



#Created By Ofir Tadmor

import os
import appuifw
import e32

class MenuFileBrowser:
def __init __ (self):
self.dir_stack = []

def show (self):
selected_file = None
focused_item = 0

while 1:
#show the list
if len (self.dir_stack) == 0:
entries = e32.drive_list ()

index = appuifw.popup_menu (entries)

if index == None:
break
else:
self.dir_stack.append (entries [index])
else:
old_path = os.sep.join (self.dir_stack) .encode ('utf-8')
entries = [x.decode ('utf-8') for x in os.listdir (old_path)]
entries.insert (0, u "..")
entries.insert (1, u ".")

index = appuifw.popup_menu (entries)

if index == None or index == 0: #go up one directory
focused_item = self.dir_stack.pop ()
elif index == 1: #select current directory
selected_file = old_path
focused_item = self.dir_stack.pop ()
break
else:
short_path = entries [index]
new_path = ("% s% s% s"% (old_path.decode ('utf-8'), os.sep, short_path)) encode ('utf-8')
if ospath.isdir (new_path):
self.dir_stack.append (short_path)
else:
selected_file = new_path
focused_item = self.dir_stack.pop ()
break

return selected_file

Link to content
Share on other sites

  • 2 weeks later ...
  • 4 weeks later ...

I wrote a small PHP class that creates a pie graph using GD.

There are a variety of parameters that can be modified so that there is great flexibility in creating the graph.

In the end there is a very basic example of how to use the department.

You can freely add and modify the code and use it freely for any purpose you desire.

Enjoy:

<?php
Class PieSlice {
var $ Value; // Slice Vvlue;
var $ NormalColor; // Slice color
var $ Color3D; // Height color for slice at 3D mode
}

Class PieGraph {
var $ TotalSum; // Total value of the pei
var $ ImageWidth;
var $ ImageHeight;
var $ PieSlices; // Array
var $ BGColor;
var $ IsTransparent;
var $ DefaultColors; // Array of default colors is no color set for the Slice
var $ Height3D; // Set the pei height at 3D mode
var $ Enable3D; // Enable 3D mode
var $ GraphOffset;

function PieGraph ($ w, $ h, $ sum) {
$ this-> ImageWidth = $ w;
$ this-> ImageHeight = $ h;
$ this-> TotalSum = $ sum;
$ this-> IsTransparent = true;
$this->DefaultColors = Array("ff0000","0000ff","00ff00","fff000","ffa800","1bbbf6","d41bf6","1beef6","f0eca4","ad7e18");
$ this-> BGColor = Array (0,0,0);
$ this-> Height3D = 10;
$ this-> Enable3D = true;
$ this-> GraphOffset = 45;
}

function SetBGColor ($ RGB) {
$ this-> BGColor = $ this-> Hex2RGB ($ RGB);
}

function Hex2RGB ($ hex_color = "") {
// Convert hexadecimal to format {FFFFFF -> (255,255,255)}
// If no color supplied the function generates a random color
if (! empty ($ hex_color)) {
$ R = hexdec (substr ($ hex_color, 0,2));
$ G = hexdec (substr ($ hex_color, 2,2));
$ B = hexdec (substr ($ hex_color, 4,2));
Else {}
$ R = rand ()% 255;
$ G = rand ()% 255;
$ B = rand ()% 255;
}
$ RGB = Array ($ R, $ G, $ B);
RGB return $;
}

function Gen3DColor ($ RGB) {
// Set the color for Slice height for 3D effect
if ($ RGB [0]> 50) $ R = $ RGB [0] -50; else $ R = 0;
if ($ RGB [1]> 50) $ G = $ RGB [1] -50; else $ G = 0;
if ($ RGB [2]> 50) $ B = $ RGB [2] -50; else $ B = 0;
$ RGB = Array ($ R, $ G, $ B);
RGB return $;
}

function AddSlice ($ vlaue, $ color_rgb_1 = "", $ color_rgb_2 = "") {
// Add Slice to the Slice array
$ slice = & new PieSlice ();
$ slice-> Value = $ vlaue;
if (empty ($ color_rgb_1)) {
if (count ($ this-> PieSlices) <10) {
$ slice-> NormalColor = $ this-> Hex2RGB ($ this-> DefaultColors [count ($ this-> PieSlices)]);
Else {}
$ slice-> NormalColor = $ this-> Hex2RGB ();
}
Else {}
$ slice-> NormalColor = $ this-> Hex2RGB ($ color_rgb_1);
}
if ($ this-> Enable3D) {
if (empty ($ color_rgb_2)) {
$ slice-> Color3D = $ this-> Gen3DColor ($ slice-> NormalColor);
Else {}
$ slice-> Color3D = $ this-> Hex2RGB ($ color_rgb_2);
}
}
$ this-> PieSlices [] = & $ slice;
return $ slice;
}

function DrawGraph () {
$ image = imagecreatetruecolor ($ this-> ImageWidth, $ this-> ImageHeight);
$ bgcolor = imagecolorallocate ($ image, $ this-> BGColor [0], $ this-> BGColor [1], $ this-> BGColor [2]);
imagefill ($ image, 0,0, $ bgcolor);
if ($ this-> Enable3D) {
for ($ i = (($ this-> ImageWidth / 2) + $ this-> Height3D); $ i> ($ this-> ImageWidth / 2); $ i--) {
$ tmp_start = 0;
foreach ($ this-> PieSlices as $ key => $ val) {
$ SliceColor = imagecolorallocate ($ image, $ val-> Color3D [0], $ val-> Color3D [1], $ val-> Color3D [2]);
$ tmp_val = $ tmp_start + (($ val-> Value / $ this-> TotalSum) * 360);
imagefilledarc ($ image, $ this-> ImageWidth / 2, $ i, $ this-> ImageWidth-20, $ this-> ImageHeight / 2, $ this-> GraphOffset + $ tmp_start, $ this-> GraphOffset + $ tmp_val, $ SliceColor , IMG_ARC_PIE);
$ tmp_start = $ tmp_val;
}
}
}
if ($ this-> Enable3D) $ GraphHeight = $ this-> ImageHeight / 2; else $ GraphHeight = $ this-> ImageHeight-20;
$ tmp_start = 0;
foreach ($ this-> PieSlices as $ key => $ val) {
$ SliceColor = imagecolorallocate ($ image, $ val-> NormalColor [0], $ val-> NormalColor [1], $ val-> NormalColor [2]);
$ tmp_val = $ tmp_start + (($ val-> Value / $ this-> TotalSum) * 360);
imagefilledarc ($ image, $ this-> ImageWidth / 2, $ this-> ImageHeight / 2, $ this-> ImageWidth-20, $ GraphHeight, $ this-> GraphOffset + $ tmp_start, $ this-> GraphOffset + $ tmp_val, $ SliceColor , IMG_ARC_PIE);
$ tmp_start = $ tmp_val;
}
header ('Content-type: image / png');
if ($ this-> IsTransparent) imagecolortransparent ($ image, $ bgcolor);
imagepng ($ image);
imagedestroy ($ image);
}
}

// ------- Using ---
$ Graph = new PieGraph (500,500,300);
$ Slice = $ Graph-> AddSlice (100);
$ Slice = $ Graph-> AddSlice (100);
$ Slice = $ Graph-> AddSlice (100);

$ Graph-> DrawGraph ();
?>

[attachment deleted by admin]

Link to content
Share on other sites

I'm sorry to enter here, but I just wanted to emphasize that a POINTER whose value is 0 (equal to zero or by assignment p = 0) its true value (i.e. bits, registry value, or assignment to int) does not have to be 0 according to the language definition. A POINTER initialized to 0 or NULL does not necessarily point to 0x00000000.

It is convenient to think of it as if "0" of fonts is a reserved word like "null" in C # or something like that. This means that the pointer does not point to anything, but the value does not have to be 0.

But because a) it's easy to do it. B) The 0 address is really not particularly useful in C language for most processors. C) There are rules related to point-to-point conversions and int values. I think it's easier to fill them if you just decide 0 is 0.

Link to content
Share on other sites

  • 1 year later ...

PHP function that fully prints a date in Hebrew (day, month and year).

Format of: Friday, the 5 in June, 2009

<?php

function hebDate ($ date) {

$ Days = array ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');

$ Month = January, February, March, April, May, June, July, August, September, October, November, December');

return "day". $ Days [date ('w', $ date)]. " God-". date ('d', $ date). $ Months [date ('n', $ date) -1]. ",". date ('Y', $ date);

}

print hebDate (time ()); Friday, June 5, 2009

?>

Enjoy.

Link to content
Share on other sites

  • 1 month later ...

Static class in c # that runs queries added or updated on SQL Server. The running of the queries is limited (the number of threads determined in its initialize) so it is also suitable in cases where you want good performance on some And even if you just want something to run the queries in the background and will not interfere with the main thread (in this case it is recommended to do initialize with one thread).

The running of the queries is asynchronous and of course does not support the return of a response from the server, so it is suitable for queries added or updated.

I worked on it a lot until I came up with something with high performance and no clashes of race conditions and it seems more complex than most of the functions here, if anyone wants to use it I would love to explain more in a private post.

I guess you can make it work on another DB, say MySql or Access (only in one thread of course, it's Access after all) I can explain in detail.

public static class DBQueuer
{
public static void Initialize ()
{
Initialize (DEFAULT_NUMBER_OF_THREADS);
}

public static void Initialize (int numberOfThreads)
{
if (_isInitialized)
return;
_isInitialized = true;
_numOfThreads = numberOfThreads;
_queue = new List > (_ numOfThreads);
_threadList = new Thread [_numOfThreads];
InitializeThreadsAndQueues ();
}

private static void InitializeThreadsAndQueues ()
{
for (int i = 0; i <_numOfThreads; ++ i)
{
_queue.Add (new Queue (MAX_QUEUE_SIZE + 1));
}
for (int i = 0; i <_numOfThreads; ++ i)
{
_threadList [i] = new Thread (Start);
_threadList [i] .Start (i);
}
}

private static void Start (object threadNumerObject)
{
int threadNumber = (int) threadNumerObject;
SqlConnection connection = GetConnection (); // You must implement this method yourself!
SqlCommand cmd = connection.CreateCommand ();
while (_appRunning)
{
while (_queue [threadNumber] .Count> 0)
{
string query;
lock (_queue [threadNumber])
{
query = _queue [threadNumber] .Dequeue ();
}
cmd.CommandText = query;
for (int i = 0; i <TRIES_TO_RUN_QUERY; ++ i) // Give TRIES_TO_RUN_QUERY tries to executing the query
{
try
{
cmd.ExecuteNonQuery ();
break;
}
catch (SqlException)
{
continue;
}
}

}
if (_queue [threadNumber] .Count == 0)
Thread.Sleep (100);
}
cmd.Dispose ();
connection.Close ();
connection.Dispose ();
}



public static void QueueQuery (string query)
{
if (string.IsNullOrEmpty (query))
throw new Exception ("Problem with query");
unchecked
{
_queryCount ++;
}
int currentQueue = _queryCount% _numOfThreads;
lock (_queue [currentQueue])
{
if (_queue [currentQueue] .Count <MAX_QUEUE_SIZE)
{
_queue [currentQueue] .Enqueue (query);
return;
}
}
while (true)
{
for (int i = 0; i <_numOfThreads; ++ i)
{
if (null == _queue [i])
continue;
lock (_queue [i])
{
if (_queue [i] .Count <MAX_QUEUE_SIZE)
{
_queue [i] .Enqueue (query);
return;
}
}
}
Thread.Sleep (100);
}
}

public static void WaitForQueuesToEmpty ()
{
for (int i = 0; i <_numOfThreads; ++ i)
{
while (_queue [i] .Count> 0)
Thread.Sleep (100);
}
}

public static void Die ()
{
_appRunning = false;
}

private static int _numOfThreads;
private static List > _queue;
private const int MAX_QUEUE_SIZE = 1000;
private const int TRIES_TO_RUN_QUERY = 5;
private const int DEFAULT_NUMBER_OF_THREADS = 10;
private static int _queryCount;
private static Thread [] _threadList;
private static bool _appRunning = true;
private static bool _isInitialized;
}

Link to content
Share on other sites

  • 4 months later ...

A function in C that is used for orderly and "formatted" input from the command line with limits and settings such as numeric input only, password input, required field (and combination).

This is a long function with several parameters around, so I uploaded it to pastebin.ca so everything will be sorted with colors and description of the parameters (at the beginning of the page) and comments to explain the code

The function itself was written by Lloydus on VS2008, so even though I tried to make the code as generic as possible, it might not produce the same result in any other compiler, but these subtleties can be corrected with a few small changes to the existing code.

Here is the summary of the "important" part of the function itself:

int userInput (char * fieldName, char * defaultValue, unsigned int flags, char * outStr, int length)
{
int c;
int index = 0, i;
unsigned short x, y;
.
.
.
for (c = getch (); c! = '\ n' && c! = '\ r'; c = getch ())
{
// If user pressed on backspace, delete last char from string and screen.
if (c == '\ b')
{
if (index> 0)
{
printf ("\ b_ \ b");
index--;
}
}
// Else print char to screen and copy it to string.
else if (index <length)
{
// Ignore any non-standard ascii
if (! isprint (c))
continue;
// If Numeric-Only flag is on, make sure we only allow the input of numeric values.
if ((flags & UIF_NUMERIC) &&! isdigit (c))
{
// Position cursor behind the closing Field bracket.
getxy (& x, & y);
gotoxy (x + (length - index) + 2, y);
puts ("- This field is numeric"); // Spaces are added to make text the same length as other warnings, so that old warnnngs are overwritten
gotoxy (x, y);
continue;
}
if (flags & UIF_PASSWORD)
putch ('*');
else
putch (c);
outStr [index] = (char) c;
index ++;
}
}
.
.
.
return index;

The full function and everything around:

http://pastebin.ca/1688865

Link to content
Share on other sites

  • 5 months later ...

Sorting and searching on a disc. Attached is a file I created with a demo program.

Find length of number ©:

number_length = (int) floor (log10 ((double) program_number)) + 1; 

Find the amount of buildings listed in the file:

int GetTotalEntreis (FILE * db, int struct_size) {
fseek (db, 0, SEEK_END);
return ftell (db) / struct_size;
}

Is an existing file:


enum bool {False, True};
typedef enum bool bool;

bool FileExists (const char * filename) {
FILE * file;
if (file = fopen (filename, "r")) {
fclose (file);
return True;
}
return False;
}

Colors with C:

#include

#define CONSOLE_TEXT_COLOR_GREEN 10
#define CONSOLE_TEXT_COLOR_RED 12
#define CONSOLE_TEXT_COLOR_WHITE 7

HANDLE hConsole = GetStdHandle (STD_OUTPUT_HANDLE);

SetConsoleTextAttribute (hConsole, CONSOLE_TEXT_COLOR_RED);
puts ("some text");
SetConsoleTextAttribute (hConsole, CONSOLE_TEXT_COLOR_WHITE);

[attachment deleted by admin]

Link to content
Share on other sites

ארכיון

This discussion has been archived and new comments can not be added.


  • Latest news

  • Buzz-Zone: Everything hot on the net

×
  • Create new ...

At the top of the news:

new on the site