- 1
http://sqlserverplanet.com/troubleshooting/cannot-insert-explicit-value-for-identity-column-in-table-table-when-identity_insert-is-set-to-off
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+141
http://sqlserverplanet.com/troubleshooting/cannot-insert-explicit-value-for-identity-column-in-table-table-when-identity_insert-is-set-to-off
Последний комментарий
+88
//До рефакторинга
static function initConnectOnce(){
$who = get_called_class();
if(!$GLOBALS[$who][class_cllct]){
$db = new DataBase();
$GLOBALS[$who][class_cllct] = $db->selectCollection(get_called_class());
}
return $GLOBALS[$who][class_cllct];
}
//После
public static function initCollectOnce(){
$who = get_called_class();
$cllct = &self::$cacheCollect[$who];
if(!$cllct){
$db = new DataBase();
$cllct = $db->selectCollection($who);
}
return $cllct;
}
Недавно начал рефакторить свой же код. Нашел такой вот незаметный гавнокод...
Для тех кто в танке =)
1. selectCollection(get_called_class()) - зачем вызывать по второму разу, если результат уже есть в переменной $who.
2. $GLOBALS[$who][class_cllct] - немного глюкнуло наверное, когда писал... Логичнее так $GLOBALS[class_cllct][$who].
3. initConnectOnce - тут даже наверное не Connect должно быть, а Collect.
4. Вместо $GLOBALS[$who][class_cllct] лучше(имхо) заюзать статичное свойство для класса.
5. static function initConnectOnce - забыл public описать....
+61
public void insert()
{
super.insert();
if (this.ItemId == "")
this = this;
}
нарочно не придумаешь
+135
namespace CuttingBox
{
class Program
{
static public Tuple<int[], String> getProperty()
{
int[] itemDimensionProperty = new int[3];
String itemColorProperty;
String[] parseResult = new String[4];
parseResult = (Console.ReadLine().Split(' '));
for (int counter = 0; counter < 3; counter++)
{
itemDimensionProperty[counter] = Convert.ToInt32(parseResult[counter]);
}
itemColorProperty = parseResult[3];
Tuple<int[], String> itemProperty = new Tuple<int[], string>(itemDimensionProperty, itemColorProperty);
return itemProperty;
}
static void Main(string[] args)
{
List<Tuple<int[], String>> itemProperty = new List<Tuple<int[], String>>();
itemProperty.Add(getProperty());
int numberOfBoxes = Convert.ToInt32(Console.ReadLine());
for (int counter=1; counter<=numberOfBoxes; counter++){
itemProperty.Add(getProperty());
}
}
}
}
Парсим строки правильно...
+141
http://habrahabr.ru/post/168723/
Я даже копипастить всё не буду.
+86
Function TMainForm.PrimGenerateMaze(Width, Height: Integer): Maze;
Type Point = record
x, y: Integer;
end;
Var
TehMaze: Maze;
Todo: array of Point;
todonum: integer;
x,y,n,d: integer;
Const
dx: array [0..3] of Integer = (0, 0, -1, 1);
dy: array [0..3] of Integer = (-1, 1, 0, 0);
BEGIN
SetLength(TehMaze, Width, Height);
SetLength(Todo, (Width * Height) - 1);
For x:=0 to Width-1 do
For y:=0 to Height-1 do
If (x = 0) or (x = Width-1) or (y = 0) or (y = Height-1) then
TehMaze[x][y]:=32
Else TehMaze[x][y]:=63;
Randomize;
x := Random(Width-2)+1;
y := Random(Height-2)+1;
todonum := 0;
TehMaze[x][y]:= TehMaze[x][y] and not 48; // Пометить клетку как принадлежащую лабиринту
// Пока не обработаны все клетки
Repeat
Begin
// Занести в список todo все ближайшие необработанные клетки
For d:=0 to 3 do
if (TehMaze[x + dx[d]][y + dy[d]] and 16) <> 0 then
Begin
todo[todonum].x := x + dx[d];
todo[todonum].y := y + dy[d];
Inc(todonum);
TehMaze[x + dx[d]][y + dy[d]] := TehMaze[x + dx[d]][y + dy[d]] and not 16;
End;
// Выбрать из списка todo произвольную клетку
n:= Random(todoNum);
x:= ToDo[n].x;
y:= ToDo[n].y;
// Удалить из списка обработанную клетку
Dec(todonum);
ToDo[n]:= todo[todonum];
// Выбрать направление, которое ведет к лабиринту
Repeat
d:=Random(4);
Until ((TehMaze[x + dx[d]][y + dy[d]] and 32) = 0);
// Присоединить выбранную клетку к лабиринту
TehMaze[x][y] := TehMaze[x][y] and not ((1 shl d) or 32);
TehMaze[x + dx[d]][y + dy[d]] := TehMaze[x + dx[d]][y + dy[d]] and not (1 shl (d xor 1));
End;
Until (todonum = 0);
TehMaze[1][1] := TehMaze[1][1] and -2; // начало лабиринта - в левом верхнем углу
TehMaze[Width-2][Height-2] := TehMaze[Width-2][Height-2] and not 2; // конец лабиринта - в правом нижнем углу
Result := TehMaze;
END;
Генерация лабиринтов по алгоритму Прима.
+12
class Thread
{
public:
Thread(const Thread&);
Thread() : handle(NULL), running(false), finished(false)
{
handle = (HANDLE)(_beginthreadex(NULL, 0, &(Thread::threadRun), this, CREATE_SUSPENDED, NULL));
}
~Thread()
{
if(isRunning()) {
TerminateThread(handle, 0);
}
CloseHandle(handle);
}
void start(void* arg)
{
if(isRunning() || isFinished()) {
throw Exception("Thread is running or finished!");
} else {
this->arg = arg;
ResumeThread(handle);
}
}
void pause()
{
if(isRunning()) {
SuspendThread(handle);
} else {
throw Exception("Thread is not running or finished!");
}
}
void resume()
{
if(!(isRunning())) {
throw Exception("Thread is finished!");
} else {
ResumeThread(handle);
}
}
void stop()
{
if(isRunning()) {
TerminateThread(handle, 0);
running = false;
finished = true;
throw Exception("Thread stopped!");
} else {
throw Exception("Thread is not running or finished!");
}
}
void setPriority(ThreadPriority priority)
{
if(isFinished()) {
throw Exception("Thread is finished!");
} else {
switch(priority) {
case ThreadPriorityLow:
SetThreadPriority(handle, THREAD_PRIORITY_LOWEST);
break;
case ThreadPriorityNormal:
SetThreadPriority(handle, THREAD_PRIORITY_NORMAL);
break;
case ThreadPriorityHigh:
SetThreadPriority(handle, THREAD_PRIORITY_HIGHEST);
break;
default:
throw Exception("Invalid priority!");
break;
}
}
}
bool isRunning()
{
return (running);
}
bool isFinished()
{
return (finished);
}
protected:
virtual void run(void *arg) = 0;
private:
static unsigned int __stdcall threadRun(void *arg)
{
Thread *thread = static_cast<Thread*>(arg);
thread->running = true;
thread->run(thread->arg);
thread->running = false;
thread->finished = true;
_endthreadex(0);
return (0);
}
void *arg;
HANDLE handle;
bool running;
bool finished;
};
Из предыдущей оперы.
+7
template<typename T>
class Enumerable
{
public:
Enumerable() : enumerableInProcess(false) { };
virtual void begin() = 0;
virtual void end() = 0;
virtual bool enumeration(T* item) = 0;
protected:
bool enumerableInProcess;
};
template<typename T>
class List : Enumerable<T*>
{
public:
class ListItem
{
public:
friend class List;
T item;
ListItem(T item) : item(item), next(nullptr), previous(nullptr)
{
}
private:
class ListItem* next;
class ListItem* previous;
};
/* ... */
void begin()
{
if(enumerableInProcess) {
throw Exception("Error Enumerable!");
}
enumerableInProcess = true;
enumerationItem = first;
}
bool enumeration(T** item)
{
if(enumerableInProcess) {
if(enumerationItem != nullptr) {
(*item) = &(enumerationItem->item);
enumerationItem = enumerationItem->next;
return (true);
} else {
(*item) = nullptr;
return (false);
}
} else {
throw Exception("Error Enumerable!");
}
}
bool enumeration(ListItem **listItem)
{
if(enumerableInProcess) {
if(enumerationItem != nullptr) {
(*listItem) = enumerationItem;
enumerationItem = enumerationItem->next;
return (true);
} else {
(*listItem) = nullptr;
return (false);
}
} else {
throw Exception("Error Enumerable!");
}
}
void end()
{
if(!enumerableInProcess) {
throw Exception("Error Enumerable!");
}
enumerableInProcess = false;
}
private:
const int size;
int count;
ListItem *first;
ListItem *last;
ListItem *enumerationItem;
};
void list_t_1()
{
List<int> list(8);
List<int>::ListItem *item;
list.add(1);
list.add(2);
list.add(4);
list.add(8);
list.add(16);
list.begin();
while(list.enumeration(&item))
{
printf("%i\n", (item->item));
}
list.end();
}
+75
public class ExtractSubstrings {
public static void main(String[] args) {
String text = “To be or not to be”;
int count = 0;
char separator = ‘ ‘;
int index = 0;
do {
++count;
++index;
index = text.indexOf(separator, index);
} while (index != -1);
String[] subStr = new String[count];
index = 0;
int endIndex = 0;
for(int i = 0; i < count; ++i) {
endIndex = text.indexOf(separator,index);
if(endIndex == -1) {
subStr[i] = text.substring(index);
} else {
subStr[i] = text.substring(index, endIndex);
}
index = endIndex + 1;
}
for(String s : subStr) {
System.out.println(s);
}
}
}
Очень чёткий, простой и с первого взгляда сразу понятный способ сделатЬ сплит строки.
+140
string num = number.ToString();
num = num.Replace(',', '.');
string num2 = number2.ToString();
num2 = num2.Replace(',', '.');
int displace = 0;
int i = 0;
for (i = 0; i <= num.Length - 1; i++)
{
if (num.Substring(i, 1) != ".")
{
int curNum = Convert.ToInt16(num.Substring(i, 1));
Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(curNum * 46, 0, 46, 64);
sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24), (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
}
else
{
Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(10 * 46, 0, 46, 64);
sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24), (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
}
displace += (int)(46.0f * scale);
}
Microsoft.Xna.Framework.Rectangle src = new Microsoft.Xna.Framework.Rectangle(11 * 46, 0, 46, 64);
sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + displace, (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), src, color);
displace += (int)(46.0f * scale);
for (i = 0; i <= num2.Length - 1; i++)
{
if (num2.Substring(i, 1) != ".")
{
int curNum = Convert.ToInt16(num2.Substring(i, 1));
Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(curNum * 46, 0, 46, 64);
sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24) + displace, (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
}
else
{
Microsoft.Xna.Framework.Rectangle source = new Microsoft.Xna.Framework.Rectangle(10 * 46, 0, 46, 64);
sb.Draw(numbers, new Microsoft.Xna.Framework.Rectangle((int)position.X + (i * 24) + displace, (int)position.Y - 5, (int)(46.0f * scale), (int)(64.0f * scale)), source, color);
}
}
Nuff said.
Как я тогда давным давно поленился импортировать неймспейс XNA - чёрт его знает.