content
stringlengths
228
999k
pred_label
stringclasses
1 value
pred_score
float64
0.5
1
Index: llvm/trunk/test/Transforms/InstCombine/mul.ll =================================================================== --- llvm/trunk/test/Transforms/InstCombine/mul.ll (revision 351186) +++ llvm/trunk/test/Transforms/InstCombine/mul.ll (revision 351187) @@ -1,503 +1,519 @@ ; NOTE: Assertions have been autogenerated by utils/update_test_checks.py ; RUN: opt < %s -instcombine -S | FileCheck %s define i32 @pow2_multiplier(i32 %A) { ; CHECK-LABEL: @pow2_multiplier( ; CHECK-NEXT: [[B:%.*]] = shl i32 [[A:%.*]], 1 ; CHECK-NEXT: ret i32 [[B]] ; %B = mul i32 %A, 2 ret i32 %B } define <2 x i32> @pow2_multiplier_vec(<2 x i32> %A) { ; CHECK-LABEL: @pow2_multiplier_vec( ; CHECK-NEXT: [[B:%.*]] = shl <2 x i32> [[A:%.*]], ; CHECK-NEXT: ret <2 x i32> [[B]] ; %B = mul <2 x i32> %A, ret <2 x i32> %B } define i8 @combine_shl(i8 %A) { ; CHECK-LABEL: @combine_shl( ; CHECK-NEXT: [[C:%.*]] = shl i8 [[A:%.*]], 6 ; CHECK-NEXT: ret i8 [[C]] ; %B = mul i8 %A, 8 %C = mul i8 %B, 8 ret i8 %C } define i32 @neg(i32 %i) { ; CHECK-LABEL: @neg( ; CHECK-NEXT: [[TMP:%.*]] = sub i32 0, [[I:%.*]] ; CHECK-NEXT: ret i32 [[TMP]] ; %tmp = mul i32 %i, -1 ret i32 %tmp } ; Use the sign-bit as a mask: ; (zext (A < 0)) * B --> (A >> 31) & B define i32 @test10(i32 %a, i32 %b) { ; CHECK-LABEL: @test10( ; CHECK-NEXT: [[TMP1:%.*]] = ashr i32 [[A:%.*]], 31 ; CHECK-NEXT: [[E:%.*]] = and i32 [[TMP1]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[E]] ; %c = icmp slt i32 %a, 0 %d = zext i1 %c to i32 %e = mul i32 %d, %b ret i32 %e } define i32 @test11(i32 %a, i32 %b) { ; CHECK-LABEL: @test11( ; CHECK-NEXT: [[TMP1:%.*]] = ashr i32 [[A:%.*]], 31 ; CHECK-NEXT: [[E:%.*]] = and i32 [[TMP1]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[E]] ; %c = icmp sle i32 %a, -1 %d = zext i1 %c to i32 %e = mul i32 %d, %b ret i32 %e } declare void @use32(i32) define i32 @test12(i32 %a, i32 %b) { ; CHECK-LABEL: @test12( ; CHECK-NEXT: [[A_LOBIT:%.*]] = lshr i32 [[A:%.*]], 31 ; CHECK-NEXT: [[TMP1:%.*]] = ashr i32 [[A]], 31 ; CHECK-NEXT: [[E:%.*]] = and i32 [[TMP1]], [[B:%.*]] ; CHECK-NEXT: call void @use32(i32 [[A_LOBIT]]) ; CHECK-NEXT: ret i32 [[E]] ; %c = icmp ugt i32 %a, 2147483647 %d = zext i1 %c to i32 %e = mul i32 %d, %b call void @use32(i32 %d) ret i32 %e } ; rdar://7293527 define i32 @test15(i32 %A, i32 %B) { ; CHECK-LABEL: @test15( ; CHECK-NEXT: [[M:%.*]] = shl i32 [[A:%.*]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[M]] ; %shl = shl i32 1, %B %m = mul i32 %shl, %A ret i32 %m } ; X * Y (when Y is a boolean) --> Y ? X : 0 define i32 @mul_bool(i32 %x, i1 %y) { ; CHECK-LABEL: @mul_bool( ; CHECK-NEXT: [[M:%.*]] = select i1 [[Y:%.*]], i32 [[X:%.*]], i32 0 ; CHECK-NEXT: ret i32 [[M]] ; %z = zext i1 %y to i32 %m = mul i32 %x, %z ret i32 %m } ; Commute and test vector type. define <2 x i32> @mul_bool_vec(<2 x i32> %x, <2 x i1> %y) { ; CHECK-LABEL: @mul_bool_vec( ; CHECK-NEXT: [[M:%.*]] = select <2 x i1> [[Y:%.*]], <2 x i32> [[X:%.*]], <2 x i32> zeroinitializer ; CHECK-NEXT: ret <2 x i32> [[M]] ; %z = zext <2 x i1> %y to <2 x i32> %m = mul <2 x i32> %x, %z ret <2 x i32> %m } define <2 x i32> @mul_bool_vec_commute(<2 x i32> %x, <2 x i1> %y) { ; CHECK-LABEL: @mul_bool_vec_commute( ; CHECK-NEXT: [[M:%.*]] = select <2 x i1> [[Y:%.*]], <2 x i32> [[X:%.*]], <2 x i32> zeroinitializer ; CHECK-NEXT: ret <2 x i32> [[M]] ; %z = zext <2 x i1> %y to <2 x i32> %m = mul <2 x i32> %z, %x ret <2 x i32> %m } ; (A >>u 31) * B --> (A >>s 31) & B define i32 @signbit_mul(i32 %a, i32 %b) { ; CHECK-LABEL: @signbit_mul( ; CHECK-NEXT: [[TMP1:%.*]] = ashr i32 [[A:%.*]], 31 ; CHECK-NEXT: [[E:%.*]] = and i32 [[TMP1]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[E]] ; %d = lshr i32 %a, 31 %e = mul i32 %d, %b ret i32 %e } define i32 @signbit_mul_commute_extra_use(i32 %a, i32 %b) { ; CHECK-LABEL: @signbit_mul_commute_extra_use( ; CHECK-NEXT: [[D:%.*]] = lshr i32 [[A:%.*]], 31 ; CHECK-NEXT: [[TMP1:%.*]] = ashr i32 [[A]], 31 ; CHECK-NEXT: [[E:%.*]] = and i32 [[TMP1]], [[B:%.*]] ; CHECK-NEXT: call void @use32(i32 [[D]]) ; CHECK-NEXT: ret i32 [[E]] ; %d = lshr i32 %a, 31 %e = mul i32 %b, %d call void @use32(i32 %d) ret i32 %e } ; (A >>u 31)) * B --> (A >>s 31) & B define <2 x i32> @signbit_mul_vec(<2 x i32> %a, <2 x i32> %b) { ; CHECK-LABEL: @signbit_mul_vec( ; CHECK-NEXT: [[TMP1:%.*]] = ashr <2 x i32> [[A:%.*]], ; CHECK-NEXT: [[E:%.*]] = and <2 x i32> [[TMP1]], [[B:%.*]] ; CHECK-NEXT: ret <2 x i32> [[E]] ; %d = lshr <2 x i32> %a, %e = mul <2 x i32> %d, %b ret <2 x i32> %e } define <2 x i32> @signbit_mul_vec_commute(<2 x i32> %a, <2 x i32> %b) { ; CHECK-LABEL: @signbit_mul_vec_commute( ; CHECK-NEXT: [[TMP1:%.*]] = ashr <2 x i32> [[A:%.*]], ; CHECK-NEXT: [[E:%.*]] = and <2 x i32> [[TMP1]], [[B:%.*]] ; CHECK-NEXT: ret <2 x i32> [[E]] ; %d = lshr <2 x i32> %a, %e = mul <2 x i32> %b, %d ret <2 x i32> %e } define i32 @test18(i32 %A, i32 %B) { ; CHECK-LABEL: @test18( ; CHECK-NEXT: ret i32 0 ; %C = and i32 %A, 1 %D = and i32 %B, 1 %E = mul i32 %C, %D %F = and i32 %E, 16 ret i32 %F } declare {i32, i1} @llvm.smul.with.overflow.i32(i32, i32) declare void @use(i1) define i32 @test19(i32 %A, i32 %B) { ; CHECK-LABEL: @test19( ; CHECK-NEXT: call void @use(i1 false) ; CHECK-NEXT: ret i32 0 ; %C = and i32 %A, 1 %D = and i32 %B, 1 ; It would be nice if we also started proving that this doesn't overflow. %E = call {i32, i1} @llvm.smul.with.overflow.i32(i32 %C, i32 %D) %F = extractvalue {i32, i1} %E, 0 %G = extractvalue {i32, i1} %E, 1 call void @use(i1 %G) %H = and i32 %F, 16 ret i32 %H } define <2 x i64> @test20(<2 x i64> %A) { ; CHECK-LABEL: @test20( ; CHECK-NEXT: [[TMP1:%.*]] = mul <2 x i64> [[A:%.*]], ; CHECK-NEXT: [[C:%.*]] = add <2 x i64> [[TMP1]], ; CHECK-NEXT: ret <2 x i64> [[C]] ; %B = add <2 x i64> %A, %C = mul <2 x i64> %B, ret <2 x i64> %C } define <2 x i1> @test21(<2 x i1> %A, <2 x i1> %B) { ; CHECK-LABEL: @test21( ; CHECK-NEXT: [[C:%.*]] = and <2 x i1> [[A:%.*]], [[B:%.*]] ; CHECK-NEXT: ret <2 x i1> [[C]] ; %C = mul <2 x i1> %A, %B ret <2 x i1> %C } define i32 @test22(i32 %A) { ; CHECK-LABEL: @test22( ; CHECK-NEXT: [[B:%.*]] = sub nsw i32 0, [[A:%.*]] ; CHECK-NEXT: ret i32 [[B]] ; %B = mul nsw i32 %A, -1 ret i32 %B } define i32 @test23(i32 %A) { ; CHECK-LABEL: @test23( ; CHECK-NEXT: [[C:%.*]] = mul nuw i32 [[A:%.*]], 6 ; CHECK-NEXT: ret i32 [[C]] ; %B = shl nuw i32 %A, 1 %C = mul nuw i32 %B, 3 ret i32 %C } define i32 @test24(i32 %A) { ; CHECK-LABEL: @test24( ; CHECK-NEXT: [[C:%.*]] = mul nsw i32 [[A:%.*]], 6 ; CHECK-NEXT: ret i32 [[C]] ; %B = shl nsw i32 %A, 1 %C = mul nsw i32 %B, 3 ret i32 %C } define i32 @neg_neg_mul(i32 %A, i32 %B) { ; CHECK-LABEL: @neg_neg_mul( ; CHECK-NEXT: [[E:%.*]] = mul i32 [[A:%.*]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[E]] ; %C = sub i32 0, %A %D = sub i32 0, %B %E = mul i32 %C, %D ret i32 %E } define i32 @neg_neg_mul_nsw(i32 %A, i32 %B) { ; CHECK-LABEL: @neg_neg_mul_nsw( ; CHECK-NEXT: [[E:%.*]] = mul nsw i32 [[A:%.*]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[E]] ; %C = sub nsw i32 0, %A %D = sub nsw i32 0, %B %E = mul nsw i32 %C, %D ret i32 %E } define i124 @neg_neg_mul_apint(i124 %A, i124 %B) { ; CHECK-LABEL: @neg_neg_mul_apint( ; CHECK-NEXT: [[E:%.*]] = mul i124 [[A:%.*]], [[B:%.*]] ; CHECK-NEXT: ret i124 [[E]] ; %C = sub i124 0, %A %D = sub i124 0, %B %E = mul i124 %C, %D ret i124 %E } define i32 @neg_mul_constant(i32 %A) { ; CHECK-LABEL: @neg_mul_constant( ; CHECK-NEXT: [[E:%.*]] = mul i32 [[A:%.*]], -7 ; CHECK-NEXT: ret i32 [[E]] ; %C = sub i32 0, %A %E = mul i32 %C, 7 ret i32 %E } define i55 @neg_mul_constant_apint(i55 %A) { ; CHECK-LABEL: @neg_mul_constant_apint( ; CHECK-NEXT: [[E:%.*]] = mul i55 [[A:%.*]], -7 ; CHECK-NEXT: ret i55 [[E]] ; %C = sub i55 0, %A %E = mul i55 %C, 7 ret i55 %E } define <3 x i8> @neg_mul_constant_vec(<3 x i8> %a) { ; CHECK-LABEL: @neg_mul_constant_vec( ; CHECK-NEXT: [[B:%.*]] = mul <3 x i8> [[A:%.*]], ; CHECK-NEXT: ret <3 x i8> [[B]] ; %A = sub <3 x i8> zeroinitializer, %a %B = mul <3 x i8> %A, ret <3 x i8> %B } define <3 x i4> @neg_mul_constant_vec_weird(<3 x i4> %a) { ; CHECK-LABEL: @neg_mul_constant_vec_weird( ; CHECK-NEXT: [[B:%.*]] = mul <3 x i4> [[A:%.*]], ; CHECK-NEXT: ret <3 x i4> [[B]] ; %A = sub <3 x i4> zeroinitializer, %a %B = mul <3 x i4> %A, ret <3 x i4> %B } define i32 @test26(i32 %A, i32 %B) { ; CHECK-LABEL: @test26( ; CHECK-NEXT: [[D:%.*]] = shl nsw i32 [[A:%.*]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[D]] ; %C = shl nsw i32 1, %B %D = mul nsw i32 %A, %C ret i32 %D } define i32 @test27(i32 %A, i32 %B) { ; CHECK-LABEL: @test27( ; CHECK-NEXT: [[D:%.*]] = shl nuw i32 [[A:%.*]], [[B:%.*]] ; CHECK-NEXT: ret i32 [[D]] ; %C = shl i32 1, %B %D = mul nuw i32 %A, %C ret i32 %D } define i32 @test28(i32 %A) { ; CHECK-LABEL: @test28( ; CHECK-NEXT: [[B:%.*]] = shl i32 1, [[A:%.*]] ; CHECK-NEXT: [[C:%.*]] = shl i32 [[B]], [[A]] ; CHECK-NEXT: ret i32 [[C]] ; %B = shl i32 1, %A %C = mul nsw i32 %B, %B ret i32 %C } define i64 @test29(i31 %A, i31 %B) { ; CHECK-LABEL: @test29( ; CHECK-NEXT: [[C:%.*]] = sext i31 [[A:%.*]] to i64 ; CHECK-NEXT: [[D:%.*]] = sext i31 [[B:%.*]] to i64 ; CHECK-NEXT: [[E:%.*]] = mul nsw i64 [[C]], [[D]] ; CHECK-NEXT: ret i64 [[E]] ; %C = sext i31 %A to i64 %D = sext i31 %B to i64 %E = mul i64 %C, %D ret i64 %E } define i64 @test30(i32 %A, i32 %B) { ; CHECK-LABEL: @test30( ; CHECK-NEXT: [[C:%.*]] = zext i32 [[A:%.*]] to i64 ; CHECK-NEXT: [[D:%.*]] = zext i32 [[B:%.*]] to i64 ; CHECK-NEXT: [[E:%.*]] = mul nuw i64 [[C]], [[D]] ; CHECK-NEXT: ret i64 [[E]] ; %C = zext i32 %A to i64 %D = zext i32 %B to i64 %E = mul i64 %C, %D ret i64 %E } @PR22087 = external global i32 define i32 @test31(i32 %V) { ; CHECK-LABEL: @test31( ; CHECK-NEXT: [[MUL:%.*]] = shl i32 [[V:%.*]], zext (i1 icmp ne (i32* inttoptr (i64 1 to i32*), i32* @PR22087) to i32) ; CHECK-NEXT: ret i32 [[MUL]] ; %mul = mul i32 %V, shl (i32 1, i32 zext (i1 icmp ne (i32* inttoptr (i64 1 to i32*), i32* @PR22087) to i32)) ret i32 %mul } define i32 @test32(i32 %X) { ; CHECK-LABEL: @test32( ; CHECK-NEXT: [[MUL:%.*]] = shl i32 [[X:%.*]], 31 ; CHECK-NEXT: ret i32 [[MUL]] ; %mul = mul nsw i32 %X, -2147483648 ret i32 %mul } define <2 x i32> @test32vec(<2 x i32> %X) { ; CHECK-LABEL: @test32vec( ; CHECK-NEXT: [[MUL:%.*]] = shl <2 x i32> [[X:%.*]], ; CHECK-NEXT: ret <2 x i32> [[MUL]] ; %mul = mul nsw <2 x i32> %X, ret <2 x i32> %mul } define i32 @test33(i32 %X) { ; CHECK-LABEL: @test33( ; CHECK-NEXT: [[MUL:%.*]] = shl nsw i32 [[X:%.*]], 30 ; CHECK-NEXT: ret i32 [[MUL]] ; %mul = mul nsw i32 %X, 1073741824 ret i32 %mul } define <2 x i32> @test33vec(<2 x i32> %X) { ; CHECK-LABEL: @test33vec( ; CHECK-NEXT: [[MUL:%.*]] = shl nsw <2 x i32> [[X:%.*]], ; CHECK-NEXT: ret <2 x i32> [[MUL]] ; %mul = mul nsw <2 x i32> %X, ret <2 x i32> %mul } define i128 @test34(i128 %X) { ; CHECK-LABEL: @test34( ; CHECK-NEXT: [[MUL:%.*]] = shl nsw i128 [[X:%.*]], 1 ; CHECK-NEXT: ret i128 [[MUL]] ; %mul = mul nsw i128 %X, 2 ret i128 %mul } define i32 @test_mul_canonicalize_op0(i32 %x, i32 %y) { ; CHECK-LABEL: @test_mul_canonicalize_op0( -; CHECK-NEXT: [[MUL:%.*]] = mul i32 [[X:%.*]], [[Y:%.*]] -; CHECK-NEXT: [[NEG:%.*]] = sub i32 0, [[MUL]] -; CHECK-NEXT: ret i32 [[NEG]] +; CHECK-NEXT: [[TMP1:%.*]] = mul i32 [[X:%.*]], [[Y:%.*]] +; CHECK-NEXT: [[MUL:%.*]] = sub i32 0, [[TMP1]] +; CHECK-NEXT: ret i32 [[MUL]] ; %neg = sub i32 0, %x %mul = mul i32 %neg, %y ret i32 %mul } define i32 @test_mul_canonicalize_op1(i32 %x, i32 %z) { ; CHECK-LABEL: @test_mul_canonicalize_op1( ; CHECK-NEXT: [[Y:%.*]] = mul i32 [[Z:%.*]], 3 -; CHECK-NEXT: [[MUL:%.*]] = mul i32 [[X:%.*]], [[Y:%.*]] -; CHECK-NEXT: [[NEG:%.*]] = sub i32 0, [[MUL]] -; CHECK-NEXT: ret i32 [[NEG]] +; CHECK-NEXT: [[TMP1:%.*]] = mul i32 [[Y]], [[X:%.*]] +; CHECK-NEXT: [[MUL:%.*]] = sub i32 0, [[TMP1]] +; CHECK-NEXT: ret i32 [[MUL]] ; - %y = mul i32 %z, 3 + %y = mul i32 %z, 3 %neg = sub i32 0, %x %mul = mul i32 %y, %neg ret i32 %mul } define i32 @test_mul_canonicalize_nsw(i32 %x, i32 %y) { ; CHECK-LABEL: @test_mul_canonicalize_nsw( -; CHECK-NEXT: [[MUL:%.*]] = mul i32 [[X:%.*]], [[Y:%.*]] -; CHECK-NEXT: [[NEG:%.*]] = sub i32 0, [[MUL]] -; CHECK-NEXT: ret i32 [[NEG]] +; CHECK-NEXT: [[TMP1:%.*]] = mul i32 [[X:%.*]], [[Y:%.*]] +; CHECK-NEXT: [[MUL:%.*]] = sub i32 0, [[TMP1]] +; CHECK-NEXT: ret i32 [[MUL]] ; %neg = sub nsw i32 0, %x %mul = mul nsw i32 %neg, %y ret i32 %mul } define <2 x i32> @test_mul_canonicalize_vec(<2 x i32> %x, <2 x i32> %y) { ; CHECK-LABEL: @test_mul_canonicalize_vec( -; CHECK-NEXT: [[MUL:%.*]] = mul <2 x i32> [[X:%.*]], [[Y:%.*]] -; CHECK-NEXT: [[NEG:%.*]] = sub <2 x i32> zeroinitializer, [[MUL]] -; CHECK-NEXT: ret <2 x i32> [[NEG]] +; CHECK-NEXT: [[TMP1:%.*]] = mul <2 x i32> [[X:%.*]], [[Y:%.*]] +; CHECK-NEXT: [[MUL:%.*]] = sub <2 x i32> zeroinitializer, [[TMP1]] +; CHECK-NEXT: ret <2 x i32> [[MUL]] ; %neg = sub <2 x i32> , %x %mul = mul <2 x i32> %neg, %y ret <2 x i32> %mul } define i32 @test_mul_canonicalize_multiple_uses(i32 %x, i32 %y) { ; CHECK-LABEL: @test_mul_canonicalize_multiple_uses( ; CHECK-NEXT: [[NEG:%.*]] = sub i32 0, [[X:%.*]] ; CHECK-NEXT: [[MUL:%.*]] = mul i32 [[NEG]], [[Y:%.*]] ; CHECK-NEXT: [[MUL2:%.*]] = mul i32 [[MUL]], [[NEG]] ; CHECK-NEXT: ret i32 [[MUL2]] ; %neg = sub i32 0, %x %mul = mul i32 %neg, %y %mul2 = mul i32 %mul, %neg ret i32 %mul2 } + +@X = global i32 5 + +define i64 @test_mul_canonicalize_neg_is_not_undone(i64 %L1) { +; Check we do not undo the canonicalization of 0 - (X * Y), if Y is a constant +; expr. +; CHECK-LABEL: @test_mul_canonicalize_neg_is_not_undone( +; CHECK-NEXT: [[TMP1:%.*]] = mul i64 [[L1:%.*]], ptrtoint (i32* @X to i64) +; CHECK-NEXT: [[B4:%.*]] = sub i64 0, [[TMP1]] +; CHECK-NEXT: ret i64 [[B4]] +; + %v1 = ptrtoint i32* @X to i64 + %B8 = sub i64 0, %v1 + %B4 = mul i64 %B8, %L1 + ret i64 %B4 +} Index: llvm/trunk/lib/Transforms/InstCombine/InstCombineAddSub.cpp =================================================================== --- llvm/trunk/lib/Transforms/InstCombine/InstCombineAddSub.cpp (revision 351186) +++ llvm/trunk/lib/Transforms/InstCombine/InstCombineAddSub.cpp (revision 351187) @@ -1,1854 +1,1853 @@ //===- InstCombineAddSub.cpp ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the visit functions for add, fadd, sub, and fsub. // //===----------------------------------------------------------------------===// #include "InstCombineInternal.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Analysis/InstructionSimplify.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/Constant.h" #include "llvm/IR/Constants.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Operator.h" #include "llvm/IR/PatternMatch.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #include "llvm/Support/AlignOf.h" #include "llvm/Support/Casting.h" #include "llvm/Support/KnownBits.h" #include #include using namespace llvm; using namespace PatternMatch; #define DEBUG_TYPE "instcombine" namespace { /// Class representing coefficient of floating-point addend. /// This class needs to be highly efficient, which is especially true for /// the constructor. As of I write this comment, the cost of the default /// constructor is merely 4-byte-store-zero (Assuming compiler is able to /// perform write-merging). /// class FAddendCoef { public: // The constructor has to initialize a APFloat, which is unnecessary for // most addends which have coefficient either 1 or -1. So, the constructor // is expensive. In order to avoid the cost of the constructor, we should // reuse some instances whenever possible. The pre-created instances // FAddCombine::Add[0-5] embodies this idea. FAddendCoef() = default; ~FAddendCoef(); // If possible, don't define operator+/operator- etc because these // operators inevitably call FAddendCoef's constructor which is not cheap. void operator=(const FAddendCoef &A); void operator+=(const FAddendCoef &A); void operator*=(const FAddendCoef &S); void set(short C) { assert(!insaneIntVal(C) && "Insane coefficient"); IsFp = false; IntVal = C; } void set(const APFloat& C); void negate(); bool isZero() const { return isInt() ? !IntVal : getFpVal().isZero(); } Value *getValue(Type *) const; bool isOne() const { return isInt() && IntVal == 1; } bool isTwo() const { return isInt() && IntVal == 2; } bool isMinusOne() const { return isInt() && IntVal == -1; } bool isMinusTwo() const { return isInt() && IntVal == -2; } private: bool insaneIntVal(int V) { return V > 4 || V < -4; } APFloat *getFpValPtr() { return reinterpret_cast(&FpValBuf.buffer[0]); } const APFloat *getFpValPtr() const { return reinterpret_cast(&FpValBuf.buffer[0]); } const APFloat &getFpVal() const { assert(IsFp && BufHasFpVal && "Incorret state"); return *getFpValPtr(); } APFloat &getFpVal() { assert(IsFp && BufHasFpVal && "Incorret state"); return *getFpValPtr(); } bool isInt() const { return !IsFp; } // If the coefficient is represented by an integer, promote it to a // floating point. void convertToFpType(const fltSemantics &Sem); // Construct an APFloat from a signed integer. // TODO: We should get rid of this function when APFloat can be constructed // from an *SIGNED* integer. APFloat createAPFloatFromInt(const fltSemantics &Sem, int Val); bool IsFp = false; // True iff FpValBuf contains an instance of APFloat. bool BufHasFpVal = false; // The integer coefficient of an individual addend is either 1 or -1, // and we try to simplify at most 4 addends from neighboring at most // two instructions. So the range of falls in [-4, 4]. APInt // is overkill of this end. short IntVal = 0; AlignedCharArrayUnion FpValBuf; }; /// FAddend is used to represent floating-point addend. An addend is /// represented as , where the V is a symbolic value, and C is a /// constant coefficient. A constant addend is represented as . class FAddend { public: FAddend() = default; void operator+=(const FAddend &T) { assert((Val == T.Val) && "Symbolic-values disagree"); Coeff += T.Coeff; } Value *getSymVal() const { return Val; } const FAddendCoef &getCoef() const { return Coeff; } bool isConstant() const { return Val == nullptr; } bool isZero() const { return Coeff.isZero(); } void set(short Coefficient, Value *V) { Coeff.set(Coefficient); Val = V; } void set(const APFloat &Coefficient, Value *V) { Coeff.set(Coefficient); Val = V; } void set(const ConstantFP *Coefficient, Value *V) { Coeff.set(Coefficient->getValueAPF()); Val = V; } void negate() { Coeff.negate(); } /// Drill down the U-D chain one step to find the definition of V, and /// try to break the definition into one or two addends. static unsigned drillValueDownOneStep(Value* V, FAddend &A0, FAddend &A1); /// Similar to FAddend::drillDownOneStep() except that the value being /// splitted is the addend itself. unsigned drillAddendDownOneStep(FAddend &Addend0, FAddend &Addend1) const; private: void Scale(const FAddendCoef& ScaleAmt) { Coeff *= ScaleAmt; } // This addend has the value of "Coeff * Val". Value *Val = nullptr; FAddendCoef Coeff; }; /// FAddCombine is the class for optimizing an unsafe fadd/fsub along /// with its neighboring at most two instructions. /// class FAddCombine { public: FAddCombine(InstCombiner::BuilderTy &B) : Builder(B) {} Value *simplify(Instruction *FAdd); private: using AddendVect = SmallVector; Value *simplifyFAdd(AddendVect& V, unsigned InstrQuota); /// Convert given addend to a Value Value *createAddendVal(const FAddend &A, bool& NeedNeg); /// Return the number of instructions needed to emit the N-ary addition. unsigned calcInstrNumber(const AddendVect& Vect); Value *createFSub(Value *Opnd0, Value *Opnd1); Value *createFAdd(Value *Opnd0, Value *Opnd1); Value *createFMul(Value *Opnd0, Value *Opnd1); Value *createFNeg(Value *V); Value *createNaryFAdd(const AddendVect& Opnds, unsigned InstrQuota); void createInstPostProc(Instruction *NewInst, bool NoNumber = false); // Debugging stuff are clustered here. #ifndef NDEBUG unsigned CreateInstrNum; void initCreateInstNum() { CreateInstrNum = 0; } void incCreateInstNum() { CreateInstrNum++; } #else void initCreateInstNum() {} void incCreateInstNum() {} #endif InstCombiner::BuilderTy &Builder; Instruction *Instr = nullptr; }; } // end anonymous namespace //===----------------------------------------------------------------------===// // // Implementation of // {FAddendCoef, FAddend, FAddition, FAddCombine}. // //===----------------------------------------------------------------------===// FAddendCoef::~FAddendCoef() { if (BufHasFpVal) getFpValPtr()->~APFloat(); } void FAddendCoef::set(const APFloat& C) { APFloat *P = getFpValPtr(); if (isInt()) { // As the buffer is meanless byte stream, we cannot call // APFloat::operator=(). new(P) APFloat(C); } else *P = C; IsFp = BufHasFpVal = true; } void FAddendCoef::convertToFpType(const fltSemantics &Sem) { if (!isInt()) return; APFloat *P = getFpValPtr(); if (IntVal > 0) new(P) APFloat(Sem, IntVal); else { new(P) APFloat(Sem, 0 - IntVal); P->changeSign(); } IsFp = BufHasFpVal = true; } APFloat FAddendCoef::createAPFloatFromInt(const fltSemantics &Sem, int Val) { if (Val >= 0) return APFloat(Sem, Val); APFloat T(Sem, 0 - Val); T.changeSign(); return T; } void FAddendCoef::operator=(const FAddendCoef &That) { if (That.isInt()) set(That.IntVal); else set(That.getFpVal()); } void FAddendCoef::operator+=(const FAddendCoef &That) { enum APFloat::roundingMode RndMode = APFloat::rmNearestTiesToEven; if (isInt() == That.isInt()) { if (isInt()) IntVal += That.IntVal; else getFpVal().add(That.getFpVal(), RndMode); return; } if (isInt()) { const APFloat &T = That.getFpVal(); convertToFpType(T.getSemantics()); getFpVal().add(T, RndMode); return; } APFloat &T = getFpVal(); T.add(createAPFloatFromInt(T.getSemantics(), That.IntVal), RndMode); } void FAddendCoef::operator*=(const FAddendCoef &That) { if (That.isOne()) return; if (That.isMinusOne()) { negate(); return; } if (isInt() && That.isInt()) { int Res = IntVal * (int)That.IntVal; assert(!insaneIntVal(Res) && "Insane int value"); IntVal = Res; return; } const fltSemantics &Semantic = isInt() ? That.getFpVal().getSemantics() : getFpVal().getSemantics(); if (isInt()) convertToFpType(Semantic); APFloat &F0 = getFpVal(); if (That.isInt()) F0.multiply(createAPFloatFromInt(Semantic, That.IntVal), APFloat::rmNearestTiesToEven); else F0.multiply(That.getFpVal(), APFloat::rmNearestTiesToEven); } void FAddendCoef::negate() { if (isInt()) IntVal = 0 - IntVal; else getFpVal().changeSign(); } Value *FAddendCoef::getValue(Type *Ty) const { return isInt() ? ConstantFP::get(Ty, float(IntVal)) : ConstantFP::get(Ty->getContext(), getFpVal()); } // The definition of Addends // ========================================= // A + B <1, A>, <1,B> // A - B <1, A>, <1,B> // 0 - B <-1, B> // C * A, // A + C <1, A> // 0 +/- 0 <0, NULL> (corner case) // // Legend: A and B are not constant, C is constant unsigned FAddend::drillValueDownOneStep (Value *Val, FAddend &Addend0, FAddend &Addend1) { Instruction *I = nullptr; if (!Val || !(I = dyn_cast(Val))) return 0; unsigned Opcode = I->getOpcode(); if (Opcode == Instruction::FAdd || Opcode == Instruction::FSub) { ConstantFP *C0, *C1; Value *Opnd0 = I->getOperand(0); Value *Opnd1 = I->getOperand(1); if ((C0 = dyn_cast(Opnd0)) && C0->isZero()) Opnd0 = nullptr; if ((C1 = dyn_cast(Opnd1)) && C1->isZero()) Opnd1 = nullptr; if (Opnd0) { if (!C0) Addend0.set(1, Opnd0); else Addend0.set(C0, nullptr); } if (Opnd1) { FAddend &Addend = Opnd0 ? Addend1 : Addend0; if (!C1) Addend.set(1, Opnd1); else Addend.set(C1, nullptr); if (Opcode == Instruction::FSub) Addend.negate(); } if (Opnd0 || Opnd1) return Opnd0 && Opnd1 ? 2 : 1; // Both operands are zero. Weird! Addend0.set(APFloat(C0->getValueAPF().getSemantics()), nullptr); return 1; } if (I->getOpcode() == Instruction::FMul) { Value *V0 = I->getOperand(0); Value *V1 = I->getOperand(1); if (ConstantFP *C = dyn_cast(V0)) { Addend0.set(C, V1); return 1; } if (ConstantFP *C = dyn_cast(V1)) { Addend0.set(C, V0); return 1; } } return 0; } // Try to break *this* addend into two addends. e.g. Suppose this addend is // <2.3, V>, and V = X + Y, by calling this function, we obtain two addends, // i.e. <2.3, X> and <2.3, Y>. unsigned FAddend::drillAddendDownOneStep (FAddend &Addend0, FAddend &Addend1) const { if (isConstant()) return 0; unsigned BreakNum = FAddend::drillValueDownOneStep(Val, Addend0, Addend1); if (!BreakNum || Coeff.isOne()) return BreakNum; Addend0.Scale(Coeff); if (BreakNum == 2) Addend1.Scale(Coeff); return BreakNum; } Value *FAddCombine::simplify(Instruction *I) { assert(I->hasAllowReassoc() && I->hasNoSignedZeros() && "Expected 'reassoc'+'nsz' instruction"); // Currently we are not able to handle vector type. if (I->getType()->isVectorTy()) return nullptr; assert((I->getOpcode() == Instruction::FAdd || I->getOpcode() == Instruction::FSub) && "Expect add/sub"); // Save the instruction before calling other member-functions. Instr = I; FAddend Opnd0, Opnd1, Opnd0_0, Opnd0_1, Opnd1_0, Opnd1_1; unsigned OpndNum = FAddend::drillValueDownOneStep(I, Opnd0, Opnd1); // Step 1: Expand the 1st addend into Opnd0_0 and Opnd0_1. unsigned Opnd0_ExpNum = 0; unsigned Opnd1_ExpNum = 0; if (!Opnd0.isConstant()) Opnd0_ExpNum = Opnd0.drillAddendDownOneStep(Opnd0_0, Opnd0_1); // Step 2: Expand the 2nd addend into Opnd1_0 and Opnd1_1. if (OpndNum == 2 && !Opnd1.isConstant()) Opnd1_ExpNum = Opnd1.drillAddendDownOneStep(Opnd1_0, Opnd1_1); // Step 3: Try to optimize Opnd0_0 + Opnd0_1 + Opnd1_0 + Opnd1_1 if (Opnd0_ExpNum && Opnd1_ExpNum) { AddendVect AllOpnds; AllOpnds.push_back(&Opnd0_0); AllOpnds.push_back(&Opnd1_0); if (Opnd0_ExpNum == 2) AllOpnds.push_back(&Opnd0_1); if (Opnd1_ExpNum == 2) AllOpnds.push_back(&Opnd1_1); // Compute instruction quota. We should save at least one instruction. unsigned InstQuota = 0; Value *V0 = I->getOperand(0); Value *V1 = I->getOperand(1); InstQuota = ((!isa(V0) && V0->hasOneUse()) && (!isa(V1) && V1->hasOneUse())) ? 2 : 1; if (Value *R = simplifyFAdd(AllOpnds, InstQuota)) return R; } if (OpndNum != 2) { // The input instruction is : "I=0.0 +/- V". If the "V" were able to be // splitted into two addends, say "V = X - Y", the instruction would have // been optimized into "I = Y - X" in the previous steps. // const FAddendCoef &CE = Opnd0.getCoef(); return CE.isOne() ? Opnd0.getSymVal() : nullptr; } // step 4: Try to optimize Opnd0 + Opnd1_0 [+ Opnd1_1] if (Opnd1_ExpNum) { AddendVect AllOpnds; AllOpnds.push_back(&Opnd0); AllOpnds.push_back(&Opnd1_0); if (Opnd1_ExpNum == 2) AllOpnds.push_back(&Opnd1_1); if (Value *R = simplifyFAdd(AllOpnds, 1)) return R; } // step 5: Try to optimize Opnd1 + Opnd0_0 [+ Opnd0_1] if (Opnd0_ExpNum) { AddendVect AllOpnds; AllOpnds.push_back(&Opnd1); AllOpnds.push_back(&Opnd0_0); if (Opnd0_ExpNum == 2) AllOpnds.push_back(&Opnd0_1); if (Value *R = simplifyFAdd(AllOpnds, 1)) return R; } return nullptr; } Value *FAddCombine::simplifyFAdd(AddendVect& Addends, unsigned InstrQuota) { unsigned AddendNum = Addends.size(); assert(AddendNum <= 4 && "Too many addends"); // For saving intermediate results; unsigned NextTmpIdx = 0; FAddend TmpResult[3]; // Points to the constant addend of the resulting simplified expression. // If the resulting expr has constant-addend, this constant-addend is // desirable to reside at the top of the resulting expression tree. Placing // constant close to supper-expr(s) will potentially reveal some optimization // opportunities in super-expr(s). const FAddend *ConstAdd = nullptr; // Simplified addends are placed . AddendVect SimpVect; // The outer loop works on one symbolic-value at a time. Suppose the input // addends are : , , , , , ... // The symbolic-values will be processed in this order: x, y, z. for (unsigned SymIdx = 0; SymIdx < AddendNum; SymIdx++) { const FAddend *ThisAddend = Addends[SymIdx]; if (!ThisAddend) { // This addend was processed before. continue; } Value *Val = ThisAddend->getSymVal(); unsigned StartIdx = SimpVect.size(); SimpVect.push_back(ThisAddend); // The inner loop collects addends sharing same symbolic-value, and these // addends will be later on folded into a single addend. Following above // example, if the symbolic value "y" is being processed, the inner loop // will collect two addends "" and "". These two addends will // be later on folded into "". for (unsigned SameSymIdx = SymIdx + 1; SameSymIdx < AddendNum; SameSymIdx++) { const FAddend *T = Addends[SameSymIdx]; if (T && T->getSymVal() == Val) { // Set null such that next iteration of the outer loop will not process // this addend again. Addends[SameSymIdx] = nullptr; SimpVect.push_back(T); } } // If multiple addends share same symbolic value, fold them together. if (StartIdx + 1 != SimpVect.size()) { FAddend &R = TmpResult[NextTmpIdx ++]; R = *SimpVect[StartIdx]; for (unsigned Idx = StartIdx + 1; Idx < SimpVect.size(); Idx++) R += *SimpVect[Idx]; // Pop all addends being folded and push the resulting folded addend. SimpVect.resize(StartIdx); if (Val) { if (!R.isZero()) { SimpVect.push_back(&R); } } else { // Don't push constant addend at this time. It will be the last element // of . ConstAdd = &R; } } } assert((NextTmpIdx <= array_lengthof(TmpResult) + 1) && "out-of-bound access"); if (ConstAdd) SimpVect.push_back(ConstAdd); Value *Result; if (!SimpVect.empty()) Result = createNaryFAdd(SimpVect, InstrQuota); else { // The addition is folded to 0.0. Result = ConstantFP::get(Instr->getType(), 0.0); } return Result; } Value *FAddCombine::createNaryFAdd (const AddendVect &Opnds, unsigned InstrQuota) { assert(!Opnds.empty() && "Expect at least one addend"); // Step 1: Check if the # of instructions needed exceeds the quota. unsigned InstrNeeded = calcInstrNumber(Opnds); if (InstrNeeded > InstrQuota) return nullptr; initCreateInstNum(); // step 2: Emit the N-ary addition. // Note that at most three instructions are involved in Fadd-InstCombine: the // addition in question, and at most two neighboring instructions. // The resulting optimized addition should have at least one less instruction // than the original addition expression tree. This implies that the resulting // N-ary addition has at most two instructions, and we don't need to worry // about tree-height when constructing the N-ary addition. Value *LastVal = nullptr; bool LastValNeedNeg = false; // Iterate the addends, creating fadd/fsub using adjacent two addends. for (const FAddend *Opnd : Opnds) { bool NeedNeg; Value *V = createAddendVal(*Opnd, NeedNeg); if (!LastVal) { LastVal = V; LastValNeedNeg = NeedNeg; continue; } if (LastValNeedNeg == NeedNeg) { LastVal = createFAdd(LastVal, V); continue; } if (LastValNeedNeg) LastVal = createFSub(V, LastVal); else LastVal = createFSub(LastVal, V); LastValNeedNeg = false; } if (LastValNeedNeg) { LastVal = createFNeg(LastVal); } #ifndef NDEBUG assert(CreateInstrNum == InstrNeeded && "Inconsistent in instruction numbers"); #endif return LastVal; } Value *FAddCombine::createFSub(Value *Opnd0, Value *Opnd1) { Value *V = Builder.CreateFSub(Opnd0, Opnd1); if (Instruction *I = dyn_cast(V)) createInstPostProc(I); return V; } Value *FAddCombine::createFNeg(Value *V) { Value *Zero = cast(ConstantFP::getZeroValueForNegation(V->getType())); Value *NewV = createFSub(Zero, V); if (Instruction *I = dyn_cast(NewV)) createInstPostProc(I, true); // fneg's don't receive instruction numbers. return NewV; } Value *FAddCombine::createFAdd(Value *Opnd0, Value *Opnd1) { Value *V = Builder.CreateFAdd(Opnd0, Opnd1); if (Instruction *I = dyn_cast(V)) createInstPostProc(I); return V; } Value *FAddCombine::createFMul(Value *Opnd0, Value *Opnd1) { Value *V = Builder.CreateFMul(Opnd0, Opnd1); if (Instruction *I = dyn_cast(V)) createInstPostProc(I); return V; } void FAddCombine::createInstPostProc(Instruction *NewInstr, bool NoNumber) { NewInstr->setDebugLoc(Instr->getDebugLoc()); // Keep track of the number of instruction created. if (!NoNumber) incCreateInstNum(); // Propagate fast-math flags NewInstr->setFastMathFlags(Instr->getFastMathFlags()); } // Return the number of instruction needed to emit the N-ary addition. // NOTE: Keep this function in sync with createAddendVal(). unsigned FAddCombine::calcInstrNumber(const AddendVect &Opnds) { unsigned OpndNum = Opnds.size(); unsigned InstrNeeded = OpndNum - 1; // The number of addends in the form of "(-1)*x". unsigned NegOpndNum = 0; // Adjust the number of instructions needed to emit the N-ary add. for (const FAddend *Opnd : Opnds) { if (Opnd->isConstant()) continue; // The constant check above is really for a few special constant // coefficients. if (isa(Opnd->getSymVal())) continue; const FAddendCoef &CE = Opnd->getCoef(); if (CE.isMinusOne() || CE.isMinusTwo()) NegOpndNum++; // Let the addend be "c * x". If "c == +/-1", the value of the addend // is immediately available; otherwise, it needs exactly one instruction // to evaluate the value. if (!CE.isMinusOne() && !CE.isOne()) InstrNeeded++; } if (NegOpndNum == OpndNum) InstrNeeded++; return InstrNeeded; } // Input Addend Value NeedNeg(output) // ================================================================ // Constant C C false // <+/-1, V> V coefficient is -1 // <2/-2, V> "fadd V, V" coefficient is -2 // "fmul V, C" false // // NOTE: Keep this function in sync with FAddCombine::calcInstrNumber. Value *FAddCombine::createAddendVal(const FAddend &Opnd, bool &NeedNeg) { const FAddendCoef &Coeff = Opnd.getCoef(); if (Opnd.isConstant()) { NeedNeg = false; return Coeff.getValue(Instr->getType()); } Value *OpndVal = Opnd.getSymVal(); if (Coeff.isMinusOne() || Coeff.isOne()) { NeedNeg = Coeff.isMinusOne(); return OpndVal; } if (Coeff.isTwo() || Coeff.isMinusTwo()) { NeedNeg = Coeff.isMinusTwo(); return createFAdd(OpndVal, OpndVal); } NeedNeg = false; return createFMul(OpndVal, Coeff.getValue(Instr->getType())); } // Checks if any operand is negative and we can convert add to sub. // This function checks for following negative patterns // ADD(XOR(OR(Z, NOT(C)), C)), 1) == NEG(AND(Z, C)) // ADD(XOR(AND(Z, C), C), 1) == NEG(OR(Z, ~C)) // XOR(AND(Z, C), (C + 1)) == NEG(OR(Z, ~C)) if C is even static Value *checkForNegativeOperand(BinaryOperator &I, InstCombiner::BuilderTy &Builder) { Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); // This function creates 2 instructions to replace ADD, we need at least one // of LHS or RHS to have one use to ensure benefit in transform. if (!LHS->hasOneUse() && !RHS->hasOneUse()) return nullptr; Value *X = nullptr, *Y = nullptr, *Z = nullptr; const APInt *C1 = nullptr, *C2 = nullptr; // if ONE is on other side, swap if (match(RHS, m_Add(m_Value(X), m_One()))) std::swap(LHS, RHS); if (match(LHS, m_Add(m_Value(X), m_One()))) { // if XOR on other side, swap if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1)))) std::swap(X, RHS); if (match(X, m_Xor(m_Value(Y), m_APInt(C1)))) { // X = XOR(Y, C1), Y = OR(Z, C2), C2 = NOT(C1) ==> X == NOT(AND(Z, C1)) // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, AND(Z, C1)) if (match(Y, m_Or(m_Value(Z), m_APInt(C2))) && (*C2 == ~(*C1))) { Value *NewAnd = Builder.CreateAnd(Z, *C1); return Builder.CreateSub(RHS, NewAnd, "sub"); } else if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && (*C1 == *C2)) { // X = XOR(Y, C1), Y = AND(Z, C2), C2 == C1 ==> X == NOT(OR(Z, ~C1)) // ADD(ADD(X, 1), RHS) == ADD(X, ADD(RHS, 1)) == SUB(RHS, OR(Z, ~C1)) Value *NewOr = Builder.CreateOr(Z, ~(*C1)); return Builder.CreateSub(RHS, NewOr, "sub"); } } } // Restore LHS and RHS LHS = I.getOperand(0); RHS = I.getOperand(1); // if XOR is on other side, swap if (match(RHS, m_Xor(m_Value(Y), m_APInt(C1)))) std::swap(LHS, RHS); // C2 is ODD // LHS = XOR(Y, C1), Y = AND(Z, C2), C1 == (C2 + 1) => LHS == NEG(OR(Z, ~C2)) // ADD(LHS, RHS) == SUB(RHS, OR(Z, ~C2)) if (match(LHS, m_Xor(m_Value(Y), m_APInt(C1)))) if (C1->countTrailingZeros() == 0) if (match(Y, m_And(m_Value(Z), m_APInt(C2))) && *C1 == (*C2 + 1)) { Value *NewOr = Builder.CreateOr(Z, ~(*C2)); return Builder.CreateSub(RHS, NewOr, "sub"); } return nullptr; } Instruction *InstCombiner::foldAddWithConstant(BinaryOperator &Add) { Value *Op0 = Add.getOperand(0), *Op1 = Add.getOperand(1); Constant *Op1C; if (!match(Op1, m_Constant(Op1C))) return nullptr; if (Instruction *NV = foldBinOpIntoSelectOrPhi(Add)) return NV; Value *X, *Y; // add (sub X, Y), -1 --> add (not Y), X if (match(Op0, m_OneUse(m_Sub(m_Value(X), m_Value(Y)))) && match(Op1, m_AllOnes())) return BinaryOperator::CreateAdd(Builder.CreateNot(Y), X); // zext(bool) + C -> bool ? C + 1 : C if (match(Op0, m_ZExt(m_Value(X))) && X->getType()->getScalarSizeInBits() == 1) return SelectInst::Create(X, AddOne(Op1C), Op1); // ~X + C --> (C-1) - X if (match(Op0, m_Not(m_Value(X)))) return BinaryOperator::CreateSub(SubOne(Op1C), X); const APInt *C; if (!match(Op1, m_APInt(C))) return nullptr; if (C->isSignMask()) { // If wrapping is not allowed, then the addition must set the sign bit: // X + (signmask) --> X | signmask if (Add.hasNoSignedWrap() || Add.hasNoUnsignedWrap()) return BinaryOperator::CreateOr(Op0, Op1); // If wrapping is allowed, then the addition flips the sign bit of LHS: // X + (signmask) --> X ^ signmask return BinaryOperator::CreateXor(Op0, Op1); } // Is this add the last step in a convoluted sext? // add(zext(xor i16 X, -32768), -32768) --> sext X Type *Ty = Add.getType(); const APInt *C2; if (match(Op0, m_ZExt(m_Xor(m_Value(X), m_APInt(C2)))) && C2->isMinSignedValue() && C2->sext(Ty->getScalarSizeInBits()) == *C) return CastInst::Create(Instruction::SExt, X, Ty); // (add (zext (add nuw X, C2)), C) --> (zext (add nuw X, C2 + C)) if (match(Op0, m_OneUse(m_ZExt(m_NUWAdd(m_Value(X), m_APInt(C2))))) && C->isNegative() && C->sge(-C2->sext(C->getBitWidth()))) { Constant *NewC = ConstantInt::get(X->getType(), *C2 + C->trunc(C2->getBitWidth())); return new ZExtInst(Builder.CreateNUWAdd(X, NewC), Ty); } if (C->isOneValue() && Op0->hasOneUse()) { // add (sext i1 X), 1 --> zext (not X) // TODO: The smallest IR representation is (select X, 0, 1), and that would // not require the one-use check. But we need to remove a transform in // visitSelect and make sure that IR value tracking for select is equal or // better than for these ops. if (match(Op0, m_SExt(m_Value(X))) && X->getType()->getScalarSizeInBits() == 1) return new ZExtInst(Builder.CreateNot(X), Ty); // Shifts and add used to flip and mask off the low bit: // add (ashr (shl i32 X, 31), 31), 1 --> and (not X), 1 const APInt *C3; if (match(Op0, m_AShr(m_Shl(m_Value(X), m_APInt(C2)), m_APInt(C3))) && C2 == C3 && *C2 == Ty->getScalarSizeInBits() - 1) { Value *NotX = Builder.CreateNot(X); return BinaryOperator::CreateAnd(NotX, ConstantInt::get(Ty, 1)); } } return nullptr; } // Matches multiplication expression Op * C where C is a constant. Returns the // constant value in C and the other operand in Op. Returns true if such a // match is found. static bool MatchMul(Value *E, Value *&Op, APInt &C) { const APInt *AI; if (match(E, m_Mul(m_Value(Op), m_APInt(AI)))) { C = *AI; return true; } if (match(E, m_Shl(m_Value(Op), m_APInt(AI)))) { C = APInt(AI->getBitWidth(), 1); C <<= *AI; return true; } return false; } // Matches remainder expression Op % C where C is a constant. Returns the // constant value in C and the other operand in Op. Returns the signedness of // the remainder operation in IsSigned. Returns true if such a match is // found. static bool MatchRem(Value *E, Value *&Op, APInt &C, bool &IsSigned) { const APInt *AI; IsSigned = false; if (match(E, m_SRem(m_Value(Op), m_APInt(AI)))) { IsSigned = true; C = *AI; return true; } if (match(E, m_URem(m_Value(Op), m_APInt(AI)))) { C = *AI; return true; } if (match(E, m_And(m_Value(Op), m_APInt(AI))) && (*AI + 1).isPowerOf2()) { C = *AI + 1; return true; } return false; } // Matches division expression Op / C with the given signedness as indicated // by IsSigned, where C is a constant. Returns the constant value in C and the // other operand in Op. Returns true if such a match is found. static bool MatchDiv(Value *E, Value *&Op, APInt &C, bool IsSigned) { const APInt *AI; if (IsSigned && match(E, m_SDiv(m_Value(Op), m_APInt(AI)))) { C = *AI; return true; } if (!IsSigned) { if (match(E, m_UDiv(m_Value(Op), m_APInt(AI)))) { C = *AI; return true; } if (match(E, m_LShr(m_Value(Op), m_APInt(AI)))) { C = APInt(AI->getBitWidth(), 1); C <<= *AI; return true; } } return false; } // Returns whether C0 * C1 with the given signedness overflows. static bool MulWillOverflow(APInt &C0, APInt &C1, bool IsSigned) { bool overflow; if (IsSigned) (void)C0.smul_ov(C1, overflow); else (void)C0.umul_ov(C1, overflow); return overflow; } // Simplifies X % C0 + (( X / C0 ) % C1) * C0 to X % (C0 * C1), where (C0 * C1) // does not overflow. Value *InstCombiner::SimplifyAddWithRemainder(BinaryOperator &I) { Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); Value *X, *MulOpV; APInt C0, MulOpC; bool IsSigned; // Match I = X % C0 + MulOpV * C0 if (((MatchRem(LHS, X, C0, IsSigned) && MatchMul(RHS, MulOpV, MulOpC)) || (MatchRem(RHS, X, C0, IsSigned) && MatchMul(LHS, MulOpV, MulOpC))) && C0 == MulOpC) { Value *RemOpV; APInt C1; bool Rem2IsSigned; // Match MulOpC = RemOpV % C1 if (MatchRem(MulOpV, RemOpV, C1, Rem2IsSigned) && IsSigned == Rem2IsSigned) { Value *DivOpV; APInt DivOpC; // Match RemOpV = X / C0 if (MatchDiv(RemOpV, DivOpV, DivOpC, IsSigned) && X == DivOpV && C0 == DivOpC && !MulWillOverflow(C0, C1, IsSigned)) { Value *NewDivisor = ConstantInt::get(X->getType()->getContext(), C0 * C1); return IsSigned ? Builder.CreateSRem(X, NewDivisor, "srem") : Builder.CreateURem(X, NewDivisor, "urem"); } } } return nullptr; } /// Fold /// (1 << NBits) - 1 /// Into: /// ~(-(1 << NBits)) /// Because a 'not' is better for bit-tracking analysis and other transforms /// than an 'add'. The new shl is always nsw, and is nuw if old `and` was. static Instruction *canonicalizeLowbitMask(BinaryOperator &I, InstCombiner::BuilderTy &Builder) { Value *NBits; if (!match(&I, m_Add(m_OneUse(m_Shl(m_One(), m_Value(NBits))), m_AllOnes()))) return nullptr; Constant *MinusOne = Constant::getAllOnesValue(NBits->getType()); Value *NotMask = Builder.CreateShl(MinusOne, NBits, "notmask"); // Be wary of constant folding. if (auto *BOp = dyn_cast(NotMask)) { // Always NSW. But NUW propagates from `add`. BOp->setHasNoSignedWrap(); BOp->setHasNoUnsignedWrap(I.hasNoUnsignedWrap()); } return BinaryOperator::CreateNot(NotMask, I.getName()); } Instruction *InstCombiner::visitAdd(BinaryOperator &I) { if (Value *V = SimplifyAddInst(I.getOperand(0), I.getOperand(1), I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), SQ.getWithInstruction(&I))) return replaceInstUsesWith(I, V); if (SimplifyAssociativeOrCommutative(I)) return &I; if (Instruction *X = foldVectorBinop(I)) return X; // (A*B)+(A*C) -> A*(B+C) etc if (Value *V = SimplifyUsingDistributiveLaws(I)) return replaceInstUsesWith(I, V); if (Instruction *X = foldAddWithConstant(I)) return X; // FIXME: This should be moved into the above helper function to allow these // transforms for general constant or constant splat vectors. Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); Type *Ty = I.getType(); if (ConstantInt *CI = dyn_cast(RHS)) { Value *XorLHS = nullptr; ConstantInt *XorRHS = nullptr; if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) { unsigned TySizeBits = Ty->getScalarSizeInBits(); const APInt &RHSVal = CI->getValue(); unsigned ExtendAmt = 0; // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext. // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext. if (XorRHS->getValue() == -RHSVal) { if (RHSVal.isPowerOf2()) ExtendAmt = TySizeBits - RHSVal.logBase2() - 1; else if (XorRHS->getValue().isPowerOf2()) ExtendAmt = TySizeBits - XorRHS->getValue().logBase2() - 1; } if (ExtendAmt) { APInt Mask = APInt::getHighBitsSet(TySizeBits, ExtendAmt); if (!MaskedValueIsZero(XorLHS, Mask, 0, &I)) ExtendAmt = 0; } if (ExtendAmt) { Constant *ShAmt = ConstantInt::get(Ty, ExtendAmt); Value *NewShl = Builder.CreateShl(XorLHS, ShAmt, "sext"); return BinaryOperator::CreateAShr(NewShl, ShAmt); } // If this is a xor that was canonicalized from a sub, turn it back into // a sub and fuse this add with it. if (LHS->hasOneUse() && (XorRHS->getValue()+1).isPowerOf2()) { KnownBits LHSKnown = computeKnownBits(XorLHS, 0, &I); if ((XorRHS->getValue() | LHSKnown.Zero).isAllOnesValue()) return BinaryOperator::CreateSub(ConstantExpr::getAdd(XorRHS, CI), XorLHS); } // (X + signmask) + C could have gotten canonicalized to (X^signmask) + C, // transform them into (X + (signmask ^ C)) if (XorRHS->getValue().isSignMask()) return BinaryOperator::CreateAdd(XorLHS, ConstantExpr::getXor(XorRHS, CI)); } } if (Ty->isIntOrIntVectorTy(1)) return BinaryOperator::CreateXor(LHS, RHS); // X + X --> X << 1 if (LHS == RHS) { auto *Shl = BinaryOperator::CreateShl(LHS, ConstantInt::get(Ty, 1)); Shl->setHasNoSignedWrap(I.hasNoSignedWrap()); Shl->setHasNoUnsignedWrap(I.hasNoUnsignedWrap()); return Shl; } Value *A, *B; if (match(LHS, m_Neg(m_Value(A)))) { // -A + -B --> -(A + B) if (match(RHS, m_Neg(m_Value(B)))) return BinaryOperator::CreateNeg(Builder.CreateAdd(A, B)); // -A + B --> B - A return BinaryOperator::CreateSub(RHS, A); } // A + -B --> A - B if (match(RHS, m_Neg(m_Value(B)))) return BinaryOperator::CreateSub(LHS, B); if (Value *V = checkForNegativeOperand(I, Builder)) return replaceInstUsesWith(I, V); // (A + 1) + ~B --> A - B // ~B + (A + 1) --> A - B if (match(&I, m_c_BinOp(m_Add(m_Value(A), m_One()), m_Not(m_Value(B))))) return BinaryOperator::CreateSub(A, B); // X % C0 + (( X / C0 ) % C1) * C0 => X % (C0 * C1) if (Value *V = SimplifyAddWithRemainder(I)) return replaceInstUsesWith(I, V); // A+B --> A|B iff A and B have no bits set in common. if (haveNoCommonBitsSet(LHS, RHS, DL, &AC, &I, &DT)) return BinaryOperator::CreateOr(LHS, RHS); // FIXME: We already did a check for ConstantInt RHS above this. // FIXME: Is this pattern covered by another fold? No regression tests fail on // removal. if (ConstantInt *CRHS = dyn_cast(RHS)) { // (X & FF00) + xx00 -> (X+xx00) & FF00 Value *X; ConstantInt *C2; if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2))) && CRHS->getValue() == (CRHS->getValue() & C2->getValue())) { // See if all bits from the first bit set in the Add RHS up are included // in the mask. First, get the rightmost bit. const APInt &AddRHSV = CRHS->getValue(); // Form a mask of all bits from the lowest bit added through the top. APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1)); // See if the and mask includes all of these bits. APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue()); if (AddRHSHighBits == AddRHSHighBitsAnd) { // Okay, the xform is safe. Insert the new add pronto. Value *NewAdd = Builder.CreateAdd(X, CRHS, LHS->getName()); return BinaryOperator::CreateAnd(NewAdd, C2); } } } // add (select X 0 (sub n A)) A --> select X A n { SelectInst *SI = dyn_cast(LHS); Value *A = RHS; if (!SI) { SI = dyn_cast(RHS); A = LHS; } if (SI && SI->hasOneUse()) { Value *TV = SI->getTrueValue(); Value *FV = SI->getFalseValue(); Value *N; // Can we fold the add into the argument of the select? // We check both true and false select arguments for a matching subtract. if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A)))) // Fold the add into the true select value. return SelectInst::Create(SI->getCondition(), N, A); if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A)))) // Fold the add into the false select value. return SelectInst::Create(SI->getCondition(), A, N); } } if (Instruction *Ext = narrowMathIfNoOverflow(I)) return Ext; // (add (xor A, B) (and A, B)) --> (or A, B) // (add (and A, B) (xor A, B)) --> (or A, B) if (match(&I, m_c_BinOp(m_Xor(m_Value(A), m_Value(B)), m_c_And(m_Deferred(A), m_Deferred(B))))) return BinaryOperator::CreateOr(A, B); // (add (or A, B) (and A, B)) --> (add A, B) // (add (and A, B) (or A, B)) --> (add A, B) if (match(&I, m_c_BinOp(m_Or(m_Value(A), m_Value(B)), m_c_And(m_Deferred(A), m_Deferred(B))))) { I.setOperand(0, A); I.setOperand(1, B); return &I; } // TODO(jingyue): Consider willNotOverflowSignedAdd and // willNotOverflowUnsignedAdd to reduce the number of invocations of // computeKnownBits. bool Changed = false; if (!I.hasNoSignedWrap() && willNotOverflowSignedAdd(LHS, RHS, I)) { Changed = true; I.setHasNoSignedWrap(true); } if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedAdd(LHS, RHS, I)) { Changed = true; I.setHasNoUnsignedWrap(true); } if (Instruction *V = canonicalizeLowbitMask(I, Builder)) return V; return Changed ? &I : nullptr; } /// Factor a common operand out of fadd/fsub of fmul/fdiv. static Instruction *factorizeFAddFSub(BinaryOperator &I, InstCombiner::BuilderTy &Builder) { assert((I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction::FSub) && "Expecting fadd/fsub"); assert(I.hasAllowReassoc() && I.hasNoSignedZeros() && "FP factorization requires FMF"); Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); Value *X, *Y, *Z; bool IsFMul; if ((match(Op0, m_OneUse(m_FMul(m_Value(X), m_Value(Z)))) && match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z))))) || (match(Op0, m_OneUse(m_FMul(m_Value(Z), m_Value(X)))) && match(Op1, m_OneUse(m_c_FMul(m_Value(Y), m_Specific(Z)))))) IsFMul = true; else if (match(Op0, m_OneUse(m_FDiv(m_Value(X), m_Value(Z)))) && match(Op1, m_OneUse(m_FDiv(m_Value(Y), m_Specific(Z))))) IsFMul = false; else return nullptr; // (X * Z) + (Y * Z) --> (X + Y) * Z // (X * Z) - (Y * Z) --> (X - Y) * Z // (X / Z) + (Y / Z) --> (X + Y) / Z // (X / Z) - (Y / Z) --> (X - Y) / Z bool IsFAdd = I.getOpcode() == Instruction::FAdd; Value *XY = IsFAdd ? Builder.CreateFAddFMF(X, Y, &I) : Builder.CreateFSubFMF(X, Y, &I); // Bail out if we just created a denormal constant. // TODO: This is copied from a previous implementation. Is it necessary? const APFloat *C; if (match(XY, m_APFloat(C)) && !C->isNormal()) return nullptr; return IsFMul ? BinaryOperator::CreateFMulFMF(XY, Z, &I) : BinaryOperator::CreateFDivFMF(XY, Z, &I); } Instruction *InstCombiner::visitFAdd(BinaryOperator &I) { if (Value *V = SimplifyFAddInst(I.getOperand(0), I.getOperand(1), I.getFastMathFlags(), SQ.getWithInstruction(&I))) return replaceInstUsesWith(I, V); if (SimplifyAssociativeOrCommutative(I)) return &I; if (Instruction *X = foldVectorBinop(I)) return X; if (Instruction *FoldedFAdd = foldBinOpIntoSelectOrPhi(I)) return FoldedFAdd; Value *LHS = I.getOperand(0), *RHS = I.getOperand(1); Value *X; // (-X) + Y --> Y - X if (match(LHS, m_FNeg(m_Value(X)))) return BinaryOperator::CreateFSubFMF(RHS, X, &I); // Y + (-X) --> Y - X if (match(RHS, m_FNeg(m_Value(X)))) return BinaryOperator::CreateFSubFMF(LHS, X, &I); // Check for (fadd double (sitofp x), y), see if we can merge this into an // integer add followed by a promotion. if (SIToFPInst *LHSConv = dyn_cast(LHS)) { Value *LHSIntVal = LHSConv->getOperand(0); Type *FPType = LHSConv->getType(); // TODO: This check is overly conservative. In many cases known bits // analysis can tell us that the result of the addition has less significant // bits than the integer type can hold. auto IsValidPromotion = [](Type *FTy, Type *ITy) { Type *FScalarTy = FTy->getScalarType(); Type *IScalarTy = ITy->getScalarType(); // Do we have enough bits in the significand to represent the result of // the integer addition? unsigned MaxRepresentableBits = APFloat::semanticsPrecision(FScalarTy->getFltSemantics()); return IScalarTy->getIntegerBitWidth() <= MaxRepresentableBits; }; // (fadd double (sitofp x), fpcst) --> (sitofp (add int x, intcst)) // ... if the constant fits in the integer value. This is useful for things // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer // requires a constant pool load, and generally allows the add to be better // instcombined. if (ConstantFP *CFP = dyn_cast(RHS)) if (IsValidPromotion(FPType, LHSIntVal->getType())) { Constant *CI = ConstantExpr::getFPToSI(CFP, LHSIntVal->getType()); if (LHSConv->hasOneUse() && ConstantExpr::getSIToFP(CI, I.getType()) == CFP && willNotOverflowSignedAdd(LHSIntVal, CI, I)) { // Insert the new integer add. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, CI, "addconv"); return new SIToFPInst(NewAdd, I.getType()); } } // (fadd double (sitofp x), (sitofp y)) --> (sitofp (add int x, y)) if (SIToFPInst *RHSConv = dyn_cast(RHS)) { Value *RHSIntVal = RHSConv->getOperand(0); // It's enough to check LHS types only because we require int types to // be the same for this transform. if (IsValidPromotion(FPType, LHSIntVal->getType())) { // Only do this if x/y have the same type, if at least one of them has a // single use (so we don't increase the number of int->fp conversions), // and if the integer add will not overflow. if (LHSIntVal->getType() == RHSIntVal->getType() && (LHSConv->hasOneUse() || RHSConv->hasOneUse()) && willNotOverflowSignedAdd(LHSIntVal, RHSIntVal, I)) { // Insert the new integer add. Value *NewAdd = Builder.CreateNSWAdd(LHSIntVal, RHSIntVal, "addconv"); return new SIToFPInst(NewAdd, I.getType()); } } } } // Handle specials cases for FAdd with selects feeding the operation if (Value *V = SimplifySelectsFeedingBinaryOp(I, LHS, RHS)) return replaceInstUsesWith(I, V); if (I.hasAllowReassoc() && I.hasNoSignedZeros()) { if (Instruction *F = factorizeFAddFSub(I, Builder)) return F; if (Value *V = FAddCombine(Builder).simplify(&I)) return replaceInstUsesWith(I, V); } return nullptr; } /// Optimize pointer differences into the same array into a size. Consider: /// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer /// operands to the ptrtoint instructions for the LHS/RHS of the subtract. Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty) { // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize // this. bool Swapped = false; GEPOperator *GEP1 = nullptr, *GEP2 = nullptr; // For now we require one side to be the base pointer "A" or a constant // GEP derived from it. if (GEPOperator *LHSGEP = dyn_cast(LHS)) { // (gep X, ...) - X if (LHSGEP->getOperand(0) == RHS) { GEP1 = LHSGEP; Swapped = false; } else if (GEPOperator *RHSGEP = dyn_cast(RHS)) { // (gep X, ...) - (gep X, ...) if (LHSGEP->getOperand(0)->stripPointerCasts() == RHSGEP->getOperand(0)->stripPointerCasts()) { GEP2 = RHSGEP; GEP1 = LHSGEP; Swapped = false; } } } if (GEPOperator *RHSGEP = dyn_cast(RHS)) { // X - (gep X, ...) if (RHSGEP->getOperand(0) == LHS) { GEP1 = RHSGEP; Swapped = true; } else if (GEPOperator *LHSGEP = dyn_cast(LHS)) { // (gep X, ...) - (gep X, ...) if (RHSGEP->getOperand(0)->stripPointerCasts() == LHSGEP->getOperand(0)->stripPointerCasts()) { GEP2 = LHSGEP; GEP1 = RHSGEP; Swapped = true; } } } if (!GEP1) // No GEP found. return nullptr; if (GEP2) { // (gep X, ...) - (gep X, ...) // // Avoid duplicating the arithmetic if there are more than one non-constant // indices between the two GEPs and either GEP has a non-constant index and // multiple users. If zero non-constant index, the result is a constant and // there is no duplication. If one non-constant index, the result is an add // or sub with a constant, which is no larger than the original code, and // there's no duplicated arithmetic, even if either GEP has multiple // users. If more than one non-constant indices combined, as long as the GEP // with at least one non-constant index doesn't have multiple users, there // is no duplication. unsigned NumNonConstantIndices1 = GEP1->countNonConstantIndices(); unsigned NumNonConstantIndices2 = GEP2->countNonConstantIndices(); if (NumNonConstantIndices1 + NumNonConstantIndices2 > 1 && ((NumNonConstantIndices1 > 0 && !GEP1->hasOneUse()) || (NumNonConstantIndices2 > 0 && !GEP2->hasOneUse()))) { return nullptr; } } // Emit the offset of the GEP and an intptr_t. Value *Result = EmitGEPOffset(GEP1); // If we had a constant expression GEP on the other side offsetting the // pointer, subtract it from the offset we have. if (GEP2) { Value *Offset = EmitGEPOffset(GEP2); Result = Builder.CreateSub(Result, Offset); } // If we have p - gep(p, ...) then we have to negate the result. if (Swapped) Result = Builder.CreateNeg(Result, "diff.neg"); return Builder.CreateIntCast(Result, Ty, true); } Instruction *InstCombiner::visitSub(BinaryOperator &I) { if (Value *V = SimplifySubInst(I.getOperand(0), I.getOperand(1), I.hasNoSignedWrap(), I.hasNoUnsignedWrap(), SQ.getWithInstruction(&I))) return replaceInstUsesWith(I, V); if (Instruction *X = foldVectorBinop(I)) return X; // (A*B)-(A*C) -> A*(B-C) etc if (Value *V = SimplifyUsingDistributiveLaws(I)) return replaceInstUsesWith(I, V); // If this is a 'B = x-(-A)', change to B = x+A. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); if (Value *V = dyn_castNegVal(Op1)) { BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V); if (const auto *BO = dyn_cast(Op1)) { assert(BO->getOpcode() == Instruction::Sub && "Expected a subtraction operator!"); if (BO->hasNoSignedWrap() && I.hasNoSignedWrap()) Res->setHasNoSignedWrap(true); } else { if (cast(Op1)->isNotMinSignedValue() && I.hasNoSignedWrap()) Res->setHasNoSignedWrap(true); } return Res; } if (I.getType()->isIntOrIntVectorTy(1)) return BinaryOperator::CreateXor(Op0, Op1); // Replace (-1 - A) with (~A). if (match(Op0, m_AllOnes())) return BinaryOperator::CreateNot(Op1); // (~X) - (~Y) --> Y - X Value *X, *Y; if (match(Op0, m_Not(m_Value(X))) && match(Op1, m_Not(m_Value(Y)))) return BinaryOperator::CreateSub(Y, X); // (X + -1) - Y --> ~Y + X if (match(Op0, m_OneUse(m_Add(m_Value(X), m_AllOnes())))) return BinaryOperator::CreateAdd(Builder.CreateNot(Op1), X); // Y - (X + 1) --> ~X + Y if (match(Op1, m_OneUse(m_Add(m_Value(X), m_One())))) return BinaryOperator::CreateAdd(Builder.CreateNot(X), Op0); if (Constant *C = dyn_cast(Op0)) { bool IsNegate = match(C, m_ZeroInt()); Value *X; if (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { // 0 - (zext bool) --> sext bool // C - (zext bool) --> bool ? C - 1 : C if (IsNegate) return CastInst::CreateSExtOrBitCast(X, I.getType()); return SelectInst::Create(X, SubOne(C), C); } if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) { // 0 - (sext bool) --> zext bool // C - (sext bool) --> bool ? C + 1 : C if (IsNegate) return CastInst::CreateZExtOrBitCast(X, I.getType()); return SelectInst::Create(X, AddOne(C), C); } // C - ~X == X + (1+C) if (match(Op1, m_Not(m_Value(X)))) return BinaryOperator::CreateAdd(X, AddOne(C)); // Try to fold constant sub into select arguments. if (SelectInst *SI = dyn_cast(Op1)) if (Instruction *R = FoldOpIntoSelect(I, SI)) return R; // Try to fold constant sub into PHI values. if (PHINode *PN = dyn_cast(Op1)) if (Instruction *R = foldOpIntoPhi(I, PN)) return R; // C-(X+C2) --> (C-C2)-X Constant *C2; if (match(Op1, m_Add(m_Value(X), m_Constant(C2)))) return BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X); } const APInt *Op0C; if (match(Op0, m_APInt(Op0C))) { unsigned BitWidth = I.getType()->getScalarSizeInBits(); // -(X >>u 31) -> (X >>s 31) // -(X >>s 31) -> (X >>u 31) if (Op0C->isNullValue()) { Value *X; const APInt *ShAmt; if (match(Op1, m_LShr(m_Value(X), m_APInt(ShAmt))) && *ShAmt == BitWidth - 1) { Value *ShAmtOp = cast(Op1)->getOperand(1); return BinaryOperator::CreateAShr(X, ShAmtOp); } if (match(Op1, m_AShr(m_Value(X), m_APInt(ShAmt))) && *ShAmt == BitWidth - 1) { Value *ShAmtOp = cast(Op1)->getOperand(1); return BinaryOperator::CreateLShr(X, ShAmtOp); } if (Op1->hasOneUse()) { Value *LHS, *RHS; SelectPatternFlavor SPF = matchSelectPattern(Op1, LHS, RHS).Flavor; if (SPF == SPF_ABS || SPF == SPF_NABS) { // This is a negate of an ABS/NABS pattern. Just swap the operands // of the select. SelectInst *SI = cast(Op1); Value *TrueVal = SI->getTrueValue(); Value *FalseVal = SI->getFalseValue(); SI->setTrueValue(FalseVal); SI->setFalseValue(TrueVal); // Don't swap prof metadata, we didn't change the branch behavior. return replaceInstUsesWith(I, SI); } } } // Turn this into a xor if LHS is 2^n-1 and the remaining bits are known // zero. if (Op0C->isMask()) { KnownBits RHSKnown = computeKnownBits(Op1, 0, &I); if ((*Op0C | RHSKnown.Zero).isAllOnesValue()) return BinaryOperator::CreateXor(Op1, Op0); } } { Value *Y; // X-(X+Y) == -Y X-(Y+X) == -Y if (match(Op1, m_c_Add(m_Specific(Op0), m_Value(Y)))) return BinaryOperator::CreateNeg(Y); // (X-Y)-X == -Y if (match(Op0, m_Sub(m_Specific(Op1), m_Value(Y)))) return BinaryOperator::CreateNeg(Y); } // (sub (or A, B), (xor A, B)) --> (and A, B) { Value *A, *B; if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && match(Op0, m_c_Or(m_Specific(A), m_Specific(B)))) return BinaryOperator::CreateAnd(A, B); } { Value *Y; // ((X | Y) - X) --> (~X & Y) if (match(Op0, m_OneUse(m_c_Or(m_Value(Y), m_Specific(Op1))))) return BinaryOperator::CreateAnd( Y, Builder.CreateNot(Op1, Op1->getName() + ".not")); } if (Op1->hasOneUse()) { Value *X = nullptr, *Y = nullptr, *Z = nullptr; Constant *C = nullptr; // (X - (Y - Z)) --> (X + (Z - Y)). if (match(Op1, m_Sub(m_Value(Y), m_Value(Z)))) return BinaryOperator::CreateAdd(Op0, Builder.CreateSub(Z, Y, Op1->getName())); // (X - (X & Y)) --> (X & ~Y) if (match(Op1, m_c_And(m_Value(Y), m_Specific(Op0)))) return BinaryOperator::CreateAnd(Op0, Builder.CreateNot(Y, Y->getName() + ".not")); // 0 - (X sdiv C) -> (X sdiv -C) provided the negation doesn't overflow. if (match(Op1, m_SDiv(m_Value(X), m_Constant(C))) && match(Op0, m_Zero()) && C->isNotMinSignedValue() && !C->isOneValue()) return BinaryOperator::CreateSDiv(X, ConstantExpr::getNeg(C)); // 0 - (X << Y) -> (-X << Y) when X is freely negatable. if (match(Op1, m_Shl(m_Value(X), m_Value(Y))) && match(Op0, m_Zero())) if (Value *XNeg = dyn_castNegVal(X)) return BinaryOperator::CreateShl(XNeg, Y); // Subtracting -1/0 is the same as adding 1/0: // sub [nsw] Op0, sext(bool Y) -> add [nsw] Op0, zext(bool Y) // 'nuw' is dropped in favor of the canonical form. if (match(Op1, m_SExt(m_Value(Y))) && Y->getType()->getScalarSizeInBits() == 1) { Value *Zext = Builder.CreateZExt(Y, I.getType()); BinaryOperator *Add = BinaryOperator::CreateAdd(Op0, Zext); Add->setHasNoSignedWrap(I.hasNoSignedWrap()); return Add; } // X - A*-B -> X + A*B // X - -A*B -> X + A*B Value *A, *B; - Constant *CI; if (match(Op1, m_c_Mul(m_Value(A), m_Neg(m_Value(B))))) return BinaryOperator::CreateAdd(Op0, Builder.CreateMul(A, B)); - // X - A*CI -> X + A*-CI + // X - A*C -> X + A*-C // No need to handle commuted multiply because multiply handling will // ensure constant will be move to the right hand side. - if (match(Op1, m_Mul(m_Value(A), m_Constant(CI)))) { - Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(CI)); + if (match(Op1, m_Mul(m_Value(A), m_Constant(C))) && !isa(C)) { + Value *NewMul = Builder.CreateMul(A, ConstantExpr::getNeg(C)); return BinaryOperator::CreateAdd(Op0, NewMul); } } { // ~A - Min/Max(~A, O) -> Max/Min(A, ~O) - A // ~A - Min/Max(O, ~A) -> Max/Min(A, ~O) - A // Min/Max(~A, O) - ~A -> A - Max/Min(A, ~O) // Min/Max(O, ~A) - ~A -> A - Max/Min(A, ~O) // So long as O here is freely invertible, this will be neutral or a win. Value *LHS, *RHS, *A; Value *NotA = Op0, *MinMax = Op1; SelectPatternFlavor SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor; if (!SelectPatternResult::isMinOrMax(SPF)) { NotA = Op1; MinMax = Op0; SPF = matchSelectPattern(MinMax, LHS, RHS).Flavor; } if (SelectPatternResult::isMinOrMax(SPF) && match(NotA, m_Not(m_Value(A))) && (NotA == LHS || NotA == RHS)) { if (NotA == LHS) std::swap(LHS, RHS); // LHS is now O above and expected to have at least 2 uses (the min/max) // NotA is epected to have 2 uses from the min/max and 1 from the sub. if (IsFreeToInvert(LHS, !LHS->hasNUsesOrMore(3)) && !NotA->hasNUsesOrMore(4)) { // Note: We don't generate the inverse max/min, just create the not of // it and let other folds do the rest. Value *Not = Builder.CreateNot(MinMax); if (NotA == Op0) return BinaryOperator::CreateSub(Not, A); else return BinaryOperator::CreateSub(A, Not); } } } // Optimize pointer differences into the same array into a size. Consider: // &A[10] - &A[0]: we should compile this to "10". Value *LHSOp, *RHSOp; if (match(Op0, m_PtrToInt(m_Value(LHSOp))) && match(Op1, m_PtrToInt(m_Value(RHSOp)))) if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType())) return replaceInstUsesWith(I, Res); // trunc(p)-trunc(q) -> trunc(p-q) if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) && match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp))))) if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType())) return replaceInstUsesWith(I, Res); // Canonicalize a shifty way to code absolute value to the common pattern. // There are 2 potential commuted variants. // We're relying on the fact that we only do this transform when the shift has // exactly 2 uses and the xor has exactly 1 use (otherwise, we might increase // instructions). Value *A; const APInt *ShAmt; Type *Ty = I.getType(); if (match(Op1, m_AShr(m_Value(A), m_APInt(ShAmt))) && Op1->hasNUses(2) && *ShAmt == Ty->getScalarSizeInBits() - 1 && match(Op0, m_OneUse(m_c_Xor(m_Specific(A), m_Specific(Op1))))) { // B = ashr i32 A, 31 ; smear the sign bit // sub (xor A, B), B ; flip bits if negative and subtract -1 (add 1) // --> (A < 0) ? -A : A Value *Cmp = Builder.CreateICmpSLT(A, ConstantInt::getNullValue(Ty)); // Copy the nuw/nsw flags from the sub to the negate. Value *Neg = Builder.CreateNeg(A, "", I.hasNoUnsignedWrap(), I.hasNoSignedWrap()); return SelectInst::Create(Cmp, Neg, A); } if (Instruction *Ext = narrowMathIfNoOverflow(I)) return Ext; bool Changed = false; if (!I.hasNoSignedWrap() && willNotOverflowSignedSub(Op0, Op1, I)) { Changed = true; I.setHasNoSignedWrap(true); } if (!I.hasNoUnsignedWrap() && willNotOverflowUnsignedSub(Op0, Op1, I)) { Changed = true; I.setHasNoUnsignedWrap(true); } return Changed ? &I : nullptr; } Instruction *InstCombiner::visitFSub(BinaryOperator &I) { if (Value *V = SimplifyFSubInst(I.getOperand(0), I.getOperand(1), I.getFastMathFlags(), SQ.getWithInstruction(&I))) return replaceInstUsesWith(I, V); if (Instruction *X = foldVectorBinop(I)) return X; // Subtraction from -0.0 is the canonical form of fneg. // fsub nsz 0, X ==> fsub nsz -0.0, X Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1); if (I.hasNoSignedZeros() && match(Op0, m_PosZeroFP())) return BinaryOperator::CreateFNegFMF(Op1, &I); Value *X, *Y; Constant *C; // Fold negation into constant operand. This is limited with one-use because // fneg is assumed better for analysis and cheaper in codegen than fmul/fdiv. // -(X * C) --> X * (-C) if (match(&I, m_FNeg(m_OneUse(m_FMul(m_Value(X), m_Constant(C)))))) return BinaryOperator::CreateFMulFMF(X, ConstantExpr::getFNeg(C), &I); // -(X / C) --> X / (-C) if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Value(X), m_Constant(C)))))) return BinaryOperator::CreateFDivFMF(X, ConstantExpr::getFNeg(C), &I); // -(C / X) --> (-C) / X if (match(&I, m_FNeg(m_OneUse(m_FDiv(m_Constant(C), m_Value(X)))))) return BinaryOperator::CreateFDivFMF(ConstantExpr::getFNeg(C), X, &I); // If Op0 is not -0.0 or we can ignore -0.0: Z - (X - Y) --> Z + (Y - X) // Canonicalize to fadd to make analysis easier. // This can also help codegen because fadd is commutative. // Note that if this fsub was really an fneg, the fadd with -0.0 will get // killed later. We still limit that particular transform with 'hasOneUse' // because an fneg is assumed better/cheaper than a generic fsub. if (I.hasNoSignedZeros() || CannotBeNegativeZero(Op0, SQ.TLI)) { if (match(Op1, m_OneUse(m_FSub(m_Value(X), m_Value(Y))))) { Value *NewSub = Builder.CreateFSubFMF(Y, X, &I); return BinaryOperator::CreateFAddFMF(Op0, NewSub, &I); } } if (isa(Op0)) if (SelectInst *SI = dyn_cast(Op1)) if (Instruction *NV = FoldOpIntoSelect(I, SI)) return NV; // X - C --> X + (-C) // But don't transform constant expressions because there's an inverse fold // for X + (-Y) --> X - Y. if (match(Op1, m_Constant(C)) && !isa(Op1)) return BinaryOperator::CreateFAddFMF(Op0, ConstantExpr::getFNeg(C), &I); // X - (-Y) --> X + Y if (match(Op1, m_FNeg(m_Value(Y)))) return BinaryOperator::CreateFAddFMF(Op0, Y, &I); // Similar to above, but look through a cast of the negated value: // X - (fptrunc(-Y)) --> X + fptrunc(Y) Type *Ty = I.getType(); if (match(Op1, m_OneUse(m_FPTrunc(m_FNeg(m_Value(Y)))))) return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPTrunc(Y, Ty), &I); // X - (fpext(-Y)) --> X + fpext(Y) if (match(Op1, m_OneUse(m_FPExt(m_FNeg(m_Value(Y)))))) return BinaryOperator::CreateFAddFMF(Op0, Builder.CreateFPExt(Y, Ty), &I); // Handle special cases for FSub with selects feeding the operation if (Value *V = SimplifySelectsFeedingBinaryOp(I, Op0, Op1)) return replaceInstUsesWith(I, V); if (I.hasAllowReassoc() && I.hasNoSignedZeros()) { // (Y - X) - Y --> -X if (match(Op0, m_FSub(m_Specific(Op1), m_Value(X)))) return BinaryOperator::CreateFNegFMF(X, &I); // Y - (X + Y) --> -X // Y - (Y + X) --> -X if (match(Op1, m_c_FAdd(m_Specific(Op0), m_Value(X)))) return BinaryOperator::CreateFNegFMF(X, &I); // (X * C) - X --> X * (C - 1.0) if (match(Op0, m_FMul(m_Specific(Op1), m_Constant(C)))) { Constant *CSubOne = ConstantExpr::getFSub(C, ConstantFP::get(Ty, 1.0)); return BinaryOperator::CreateFMulFMF(Op1, CSubOne, &I); } // X - (X * C) --> X * (1.0 - C) if (match(Op1, m_FMul(m_Specific(Op0), m_Constant(C)))) { Constant *OneSubC = ConstantExpr::getFSub(ConstantFP::get(Ty, 1.0), C); return BinaryOperator::CreateFMulFMF(Op0, OneSubC, &I); } if (Instruction *F = factorizeFAddFSub(I, Builder)) return F; // TODO: This performs reassociative folds for FP ops. Some fraction of the // functionality has been subsumed by simple pattern matching here and in // InstSimplify. We should let a dedicated reassociation pass handle more // complex pattern matching and remove this from InstCombine. if (Value *V = FAddCombine(Builder).simplify(&I)) return replaceInstUsesWith(I, V); } return nullptr; }
__label__pos
0.893225
Bot Terminal Bot Terminal is a crossplatform utility that performs binary data exchange via serial port. It allows one to set up flexible rules about how to reply to different requests. So, it listens for data, parses it, and replies as necessary. I developed this tool in order to reverse-engineer various binary protocols of car ECUs (Engine Control Unit). I connect some car diagnostic tool (tester) to the computer with Bot Terminal running, and it pretends to be an ECU. By replying different responses on the tester's requests, and by analyzing tester's behavior, I can make some assumptions about the protocol. That's easy. I'm not sure whether it can be used for anything else. Anyway, it is published with the hope that it can. It is hosted at GitHub: https://github.com/dimonomid/bterm A couple of useful links: Here is an overview of the workflow: • New raw data comes from the serial port • Raw data is parsed into messages, by means of BTCore::Codec • For each received message, the sequence of the user-defined handlers is executed. Each handler may: • Analyze input request message • Build and send response message (which is usually, again, encoded with BTCore::Codec, but the handler is free to send raw data as well) • Stop further handlers execution (typically this is done when handler sends a response, but this is not mandatory) Handlers are written in JavaScript. Typical handler may look as follows: (function(inputMsg){ //-- inputMsg contains the received request data. // at the very least, it contains "byteArr" property // with actual received message.   var inputArr = inputMsg.byteArr; var handled = false; var outputArr = null;   //-- check if we should handle this request if (inputArr.getU08(0) === 0x07){ //-- yes, so, build the response outputArr = factory.createByteArr(); outputArr .putU08(0, 0xc7) .putU16(2, 0x1234) ; handled = true;   //-- encode and send response via serial port io.writeEncoded(outputArr); };   //-- if "handled" property in the returned object is true, // the rest of handlers won't be executed return { handled: handled }; }) The code is self-explanatory: we perform some arbitrary checks on received message, and generate and send the response if necessary. Why JavaScript? • Well, the first and main reason is that Qt has built-in first-class support of JavaScript: QJSEngine. Implementing support of other scripting language to the same degree of interconnection with Qt's meta object system would take a lot more effort. • Secondly, I know JavaScript very well and I even kind of like it. So, implementing handlers in JavaScript is a lot of fun. You don't have to have deep understanding of JavaScript in order to use the Bot Terminal. Just in case you're willing to actually learn JavaScript (for whatever reason), here's a couple of books that I personally recommend: • JavaScript: The Good Parts by Douglas Crockford. It focuses on a subset of JavaScript (a good subset), it teaches you very useful patterns, and it is very concise: lots of material in less than 200 pages. Great read. • JavaScript: The Definitive Guide by David Flanagan. It is much larger (1000+ pages), and it explains each and every detail of JavaScript. Great for getting deep understanding of the language. But, again, if the only JavaScript application you have is to use Bot Terminal, then you probably have something better to do rather than spending your valuable time on diving that deeply into JavaScript. Just read my brief overview. The graphics interface of the application looks like this: The GUI is actually very flexible: main window contains an application log, and a number of dock widgets, which can be moved around, shown docked or undocked, or hidden. For example, there are a couple of other dock widgets that are not shown at the screenshot above: the project settings (title and codec selection), and codec settings (which, of course, depend on codec). Check the doxygen-generated documentation (links are above) for details. Discussion Enter your comment (please, English only). Wiki syntax is allowed: ____ __ __ ____ ____ ______ / _/ / / / / / __/ / __//_ __/ _/ / / /_/ / _\ \ / _/ / / /___/ \____/ /___/ /___/ /_/   projects/bterm.txt · Last modified: 2016/12/25 11:19 by dfrank Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0
__label__pos
0.551323
simplexml_load_string (PHP 5, PHP 7) simplexml_load_string Interprets a string of XML into an object Descrierea SimpleXMLElement simplexml_load_string ( string $data [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] ) Takes a well-formed XML string and returns it as an object. Parametri data A well-formed XML string class_name You may use this optional parameter so that simplexml_load_string() will return an object of the specified class. That class should extend the SimpleXMLElement class. options Since PHP 5.1.0 and Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters. ns Namespace prefix or URI. is_prefix TRUE if ns is a prefix, FALSE if it's a URI; defaults to FALSE. Valorile întoarse Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, sau FALSE în cazul eșecului. Avertizare Această funcție poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evaluează în FALSE. Vă rugăm să citiți secțiunea despre tipul Boolean pentru informații suplimentare. Utilizați operatorul === pentru a verifica valoarea întoarsă de această funcție. Erori/Excepții Produces an E_WARNING error message for each error found in the XML data. Sfat Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards. Exemple Example #1 Interpret an XML string <?php $string  = <<<XML <?xml version='1.0'?>  <document>  <title>Forty What?</title>  <from>Joe</from>  <to>Jane</to>  <body>   I know that's the answer -- but what's the question?  </body> </document> XML; $xml simplexml_load_string($string); print_r($xml); ?> Exemplul de mai sus va afișa: SimpleXMLElement Object ( [title] => Forty What? [from] => Joe [to] => Jane [body] => I know that's the answer -- but what's the question? ) At this point, you can go about using $xml->body and such. A se vedea și add a note add a note User Contributed Notes 40 notes up 14 rowan dot collins at gmail dot com 7 years ago There seems to be a lot of talk about SimpleXML having a "problem" with CDATA, and writing functions to rip it out, etc. I thought so too, at first, but it's actually behaving just fine under PHP 5.2.6 The key is noted above example #6 here: http://uk2.php.net/manual/en/simplexml.examples.php "To compare an element or attribute with a string or pass it into a function that requires a string, you must cast it to a string using (string). Otherwise, PHP treats the element as an object." If a tag contains CDATA, SimpleXML remembers that fact, by representing it separately from the string content of the element. So some functions, including print_r(), might not show what you expect. But if you explicitly cast to a string, you get the whole content. <?php $xml = simplexml_load_string('<foo>Text1 &amp; XML entities</foo>'); print_r($xml); /* SimpleXMLElement Object (     [0] => Text1 & XML entities ) */ $xml2 = simplexml_load_string('<foo><![CDATA[Text2 & raw data]]></foo>'); print_r($xml2); /* SimpleXMLElement Object ( ) */ // Where's my CDATA? // Let's try explicit casts print_r( (string)$xml ); print_r( (string)$xml2 ); /* Text1 & XML entities Text2 & raw data */ // Much better ?> up 9 ascammon at hotmail dot com 5 years ago I had a hard time finding this documented, so posting it here in case it helps someone: If you want to use multiple libxml options, separate them with a pipe, like so: <?php $xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS); ?> up 6 Diego Araos, diego at klapmedia dot com 5 years ago A simpler way to transform the result into an array (requires json module). <?php function object2array($object) { return @json_decode(@json_encode($object),1); } ?> Example: <?php $xml_object =simplexml_load_string('<SOME XML DATA'); $xml_array=object2array($xml_object); ?> up 2 Bob 6 years ago Here is my simple SimpleXML wrapper function. As far as I can tell, it does the same as Julio Cesar Oliveira's (above). It parses an XML string into a multi-dimensional associative array. The second argument is a callback that is run on all data (so for example, if you want all data trimmed, like Julio does in his function, just pass 'trim' as the second arg). <?php function unserialize_xml($input, $callback = null, $recurse = false) /* bool/array unserialize_xml ( string $input [ , callback $callback ] ) * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data * Returns false on all failure * Notes:     * Root XML tags are stripped     * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input     * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info */ {     // Get input, loading an xml string with simplexml if its the top level of recursion     $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;     // Convert SimpleXMLElements to array     if ($data instanceof SimpleXMLElement) $data = (array) $data;     // Recurse into arrays     if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);     // Run callback and return     return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data; } ?> up 4 bojan 8 years ago As was said before don't use var_dump() or print_r() to see SimpleXML object structure as they do not returns always what you expect. Consider the following: <?php // data in xml $xml_txt = ' <root>   <folder ID="65" active="1" permission="1"><![CDATA[aaaa]]></folder>   <folder ID="65" active="1" permission="1"><![CDATA[bbbb]]></folder> </root>' ; // load xml into SimpleXML object $xml = simplexml_load_string($xml_txt, 'SimpleXMLElement', LIBXML_NOCDATA);//LIBXML_NOCDATA LIBXML_NOWARNING // see object structure print_r($xml); /* this prints SimpleXMLElement Object (     [folder] => Array         (             [0] => aaaa             [1] => bbbb         ) ) */ // but... foreach ($xml->folder as $value){     print_r($value); } /* prints complete structure of each folder element: SimpleXMLElement Object (     [@attributes] => Array         (             [ID] => 65             [active] => 1             [permission] => 1         )     [0] => aaaa ) SimpleXMLElement Object (     [@attributes] => Array         (             [ID] => 65             [active] => 1             [permission] => 1         )     [0] => bbbb ) */ ?> up 1 nbijnens at servs dot eu 8 years ago Please note that not all LIBXML options are supported with the options argument. For instance LIBXML_XINCLUDE does not work. But there is however a work around: <?php $xml = new DOMDocument(); $xml->loadXML ($XMLString);             $xml->xinclude(); $xml = simplexml_import_dom($xml); ?> up 1 Anonymous 3 years ago Use libxml_disable_entity_loader() to restrict loading of external files.  See http://www.idontplaydarts.com/2011/02/scanning-the-internal-network-using-simplexml/ up 1 AllenJB 3 years ago <?php $xml = json_decode(json_encode((array) simplexml_load_string($string)), 1); ?> A reminder that json_encode attempts to convert data to UTF-8 without specific knowledge of the source encoding. This method can cause encoding issues if you're not working in UTF-8. up 2 Julio Cesar Oliveira 6 years ago <?php function XML2Array ( $xml ) {     $array = simplexml_load_string ( $xml );     $newArray = array ( ) ;     $array = ( array ) $array ;     foreach ( $array as $key => $value )     {         $value = ( array ) $value ;         $newArray [ $key] = $value [ 0 ] ;     }     $newArray = array_map("trim", $newArray);   return $newArray ; } ?> up 2 Mark Omohundro, ajamyajax.com 7 years ago How about a recursive function to reduce the xml hard-coding in your apps?  Here is my simple listing routine as an example: <?php function list_xml($str) {   $root = simplexml_load_string($str);   list_node($root); } function list_node($node) {   foreach ( $node as $element) {     echo $element. "\n";     if ( $element->children()) {       echo "<br/>";       list_node($element);     }   } } ?> up 1 kyle at codeincarnate dot com 7 years ago A looked through a lot of the sample code for reading XML files with CDATA, but they didn't work out that well for me.  However, I found that the following piece of code worked perfectly for reading through a file using lots of CDATA. <?php $article_string = file_get_contents($path); $article_string = preg_replace_callback('/<!\[CDATA\[(.*)\]\]>/', 'filter_xml', $article_string); $article_xml = simplexml_load_string($article_string);  function filter_xml($matches) {     return trim(htmlspecialchars($matches[1])); } ?> up 0 artistan at gmail dot com 8 months ago Here is my update to Bob's simple SimpleXML wrapper function. I noticed his version would turn an empty SimpleXMLElement into an empty array. <?php     /**      * http://php.net/manual/en/function.simplexml-load-string.php#91564      *      * bool/array unserialize_xml ( string $input [ , callback $callback ] )      * Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on all non-array data      * Returns false on all failure      * Notes:      * Root XML tags are stripped      * Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input      * Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info      *      * @param $input      * @param null $callback      * @param bool $recurse      * @return array|mixed      *      */     function unserialize_xml($input, $callback = null, $recurse = false)     {         // Get input, loading an xml string with simplexml if its the top level of recursion         $data = ((!$recurse) && is_string($input))? simplexml_load_string($input): $input;         // Convert SimpleXMLElements to array         if ($data instanceof SimpleXMLElement){             if(!empty( $data)){                 $data = (array) $data;             } else {                 $data = '';             }         }         // Recurse into arrays         if (is_array($data)) foreach ($data as &$item) $item = unserialize_xml($item, $callback, true);         // Run callback and return         return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;     } ?> up 0 meustrus 9 months ago Be careful checking for parse errors. An empty SimpleXMLElement may resolve to FALSE, and if your XML contains no text or only contains namespaced elements your error check may be wrong. Always use `=== FALSE` when checking for parse errors. <?php $xml = <<<XML <?xml version="1.0" encoding="UTF-8"?> <ns1:Root xmlns:ns1="http://example.com/custom"> <ns1:Node>There's stuff here</ns1:Node> </ns1:Root> XML; $simplexml = simplexml_load_string($xml); // This prints "Parse Error". echo ($simplexml ? 'Valid XML' : 'Parse Error'), PHP_EOL; // But this prints "There's stuff here", proving that // the SimpleXML object was created successfully. echo $simplexml->children('http://example.com/custom')->Node, PHP_EOL; // Use this instead: echo ($simplexml !== FALSE ? 'Valid XML' : 'Parse Error'), PHP_EOL; ?> See: https://bugs.php.net/bug.php?id=31045 https://bugs.php.net/bug.php?id=30972 https://bugs.php.net/bug.php?id=69596 up 0 jeff at creabilis dot com 6 years ago If you want to set the charset of the outputed xml, simply set the encoding attribute like this : <?php simplexml_load_string('<?xml version="1.0" encoding="utf-8"?><xml/>'); ?> The generated xml outputed by $xml->asXML will containt accentuated characters like 'é' instead of &#xE9;. Hope this help up 0 Julio Cesar Oliveira 6 years ago The XML2Array func now Recursive! <?php function XML2Array ( $xml , $recursive = false ) {     if ( ! $recursive )     {         $array = simplexml_load_string ( $xml ) ;     }     else     {         $array = $xml ;     }         $newArray = array () ;     $array = ( array ) $array ;     foreach ( $array as $key => $value )     {         $value = ( array ) $value ;         if ( isset ( $value [ 0 ] ) )         {             $newArray [ $key ] = trim ( $value [ 0 ] ) ;         }         else         {             $newArray [ $key ] = XML2Array ( $value , true ) ;         }     }     return $newArray ; } ?> up 0 javalc6 at gmail dot com 7 years ago I wanted to convert an array containing strings and other arrays of the same type into a simplexml object. Here is the code of the function array2xml that I've developed to perform this conversion. Please note that this code is simple without any checks. <?php function array2xml($array, $tag) {     function ia2xml($array) {         $xml="";         foreach ( $array as $key=>$value) {             if ( is_array($value)) {                 $xml.="<$key>".ia2xml($value)."</$key>";             } else {                 $xml.="<$key>".$value."</$key>";             }         }         return $xml;     }     return simplexml_load_string("<$tag>".ia2xml($array)."</$tag>"); } $test['type']='lunch'; $test['time']='12:30'; $test['menu']=array('entree'=>'salad', 'maincourse'=>'steak'); echo array2xml($test,"meal")->asXML(); ?> up 0 SmartD 7 years ago A small 'n nice function to extract an XML and return it as an array. If there is a bug, please let me know here. I testet it for my purposes and it works. <?php public function extractXML($xml) {         if (!( $xml->children())) {     return (string) $xml; }         foreach ( $xml->children() as $child) {     $name=$child->getName();     if ( count($xml->$name)==1) {         $element[$name] = $this->extractXML($child);     } else {         $element[][$name] = $this->extractXML($child);     } } return $element;    } // you can call it this way $xml = false; $xml = @simplexml_load_string($xmlstring); // 1) if ($xml) {   $array = extractXML($xml); }  else {   $array = false; } // 2) if ($xml) {   $array[$xml->getName()] = extractXML($xml); }  else {   $array = false; } ?> up 0 paulyg76 at NOSPAM dot gmail dot com 7 years ago Be careful using nested SimpleXML objects in double quoted strings. <?php $xmlstring = '<root><node>123</node><foo><bar>456</bar></foo></root>'; $root = simplexml_load_string($xmlstring); echo "Node is: $root->node"; // Works: Node is 123 echo "Bar is: $root->foo->bar"; // Doesn't work, outputs: Bar is: ->bar // use curly brackets to fix echo "Bar is: {$root->foo->bar}"; // Works: Bar is 456 ?> up 0 amir_abiri at ipcmedia dot com 8 years ago It doesn't seem to be documented anywhere, but you can refer to an element "value" for the purpose of changing it like so: <?php $xml = simplexml_load_string('<root><number>1</number></root>'); echo $xml->asXml(). "\n\n"; $xml->number->{0} = $xml->number->{0} + 1; echo $xml->asXml(); ?> echos: <?xml version="1.0"?> <root><number>1</number></root> <?xml version="1.0"?> <root><number>2</number></root> However, this only works with a direct assignment, not with any of the other operators: <?php $xml = simplexml_load_string('<root><number>1</number></root>'); echo $xml->asXml(). "\n\n"; $xml->number->{0} += 1; // Or: $xml->number->{0}++; echo $xml->asXml(); ?> Both of the above cases would result in: <?xml version="1.0"?> <root><number>1</number></root> <?xml version="1.0"?> <root><number>1<0/></number></root> up 0 hattori at hanso dot com 8 years ago Theres a problem with the below workaround when serializing fields containing html CDATA. For any other content type then HTML try to modfiy function parseCDATA. Just add these lines before serializing. This is also a workaround for this bug http://bugs.php.net/bug.php?id=42001 <?PHP if(strpos($content, '<![CDATA[')) {    function parseCDATA($data) {       return htmlentities($data[1]);    }    $content = preg_replace_callback(       '#<!\[CDATA\[(.*)\]\]>#',       'parseCDATA',       str_replace("\n", " ", $content)    ); } ?> up 0 Pedro 8 years ago Attention: simplexml_load_string has a problem with entities other than (&lt;, &gt;, &amp;, &quot; and &apos;). Use numeric character references instead! up 0 php at teamhirsch dot com 8 years ago It's worth noting that in the example above, $xml->body will actually return an object of type SimpleXMLElement, not a string, e.g. SimpleXMLElement Object (        [0] => this is the text in the body tag   )  If you want to get a string out of it you must explicitly cast it using (string) or double quotes, or pass $xml->body (or whatever attribute you want to access) to any function that returns a string, such as urldecode() or trim(). up 0 m dot ament at mailcity dot com 8 years ago Warning: The parsing of XML-data will stop when reaching character 0. Please avoid this character in your XML-data. up 0 mindpower 9 years ago A simple extension that adds a method for retrieving a specific attribute: <?php class simple_xml_extended extends SimpleXMLElement {     public    function    Attribute($name)     {         foreach( $this->Attributes() as $key=>$val)         {             if( $key == $name)                 return (string) $val;         }     } } $xml = simplexml_load_string(' <xml>   <dog type="poodle" owner="Mrs Smith">Rover</dog> </xml>' , 'simple_xml_extended'); echo $xml->dog->Attribute('type'); ?> outputs 'poodle' I prefer to use this technique rather than typecasting attributes. up 0 h 9 years ago seems like simplexml has a line-length restriction - fails if a largeish XML doc with no linebreaks is passed as a string or file. h up 0 roy dot walter at nospam dot brookhouse dot co dot uk 9 years ago simplexml provides a neat way to do 'ini' files. Preferences for any number of users can be held in a single XML file having elements for each user name with user specific preferences as attributes of child elements. The separate <pref/>'s could of course be combined as multiple attributes of a single <pref/> element but this could get unwieldy. In the sample code below the makeXML() function uses the simplexml_load_string function to generate some XML to play with and the readPrefs() function parses the requested users preferences into an array. <?php function makeXML() { $xmlString = <<<XML <preferences>     <johndoe>         <pref color="#FFFFFF"/>         <pref size="14"/>         <pref font="Verdana"/>     </johndoe>     <janedoe>         <pref color="#000000"/>         <pref size="16"/>         <pref font="Georgia"/>     </janedoe>    </preferences> XML; return simplexml_load_string($xmlString); } function readPrefs($user, $xml) {         foreach( $xml->$user as $arr);         $n = count($arr);                 for( $i=0;$i<$n;$i++) {         foreach( $xml->$user->pref[$i]->attributes() as $a=>$b) {             $prefs[$a] = (string)$b;         }     }             print_r($prefs); } readPrefs('johndoe', makeXML()); ?> up 0 paul at santasoft dot com 9 years ago If you have PHP > 5.1 and LibXML > 2.6, use this function call to have simplexml convert CDATA into plain text. simplexml_load_string($xmlstring, 'SimpleXMLElement', LIBXML_NOCDATA); Too bad, so sad with PHP < 5.1. up 0 Maciek Ruckgaber <maciekrb at gmai dot com> 10 years ago after wondering around some time, i just realized something (maybe obvious, not very much for me). Hope helps someone to not waste time as i did :-P when you have something like: <?php $xmlstr = <<<XML <?xml version="1.0" encoding="utf-8"?> <double xmlns="http://foosite.foo/">2328</double> XML; ?> you will have the simpleXML object "transformed" to the text() content: <?php $xml = simplexml_load_string($xmlstr); echo $xml; // this will echo 2328  (string) ?> up 0 igor kraus 11 years ago A simple way to merge two SimpleXML objects. <?php /** * Pumps all child elements of second SimpleXML object into first one. * * @param    object      $xml1   SimpleXML object * @param    object      $xml2   SimpleXML object * @return   void */ function simplexml_merge (SimpleXMLElement &$xml1, SimpleXMLElement $xml2) {     // convert SimpleXML objects into DOM ones     $dom1 = new DomDocument();     $dom2 = new DomDocument();     $dom1->loadXML($xml1->asXML());     $dom2->loadXML($xml2->asXML());     // pull all child elements of second XML     $xpath = new domXPath($dom2);     $xpathQuery = $xpath->query('/*/*');     for ( $i = 0; $i < $xpathQuery->length; $i++)     {         // and pump them into first one         $dom1->documentElement->appendChild(             $dom1->importNode($xpathQuery->item($i), true));     }     $xml1 = simplexml_import_dom($dom1); } $xml1 = simplexml_load_string('<root><child>child 1</child></root>'); $xml2 = simplexml_load_string('<root><child>child 2</child></root>'); simplexml_merge($xml1, $xml2); echo( $xml1->asXml()); ?> Will output: <?xml version="1.0"?> <root>     <child>child 1</child>     <child>child 2</child> </root> up 0 cellog at php dot net 11 years ago simplexml does not simply handle CDATA sections in a foreach loop. <?php $sx = simplexml_load_string(' <test> <one>hi</one> <two><![CDATA[stuff]]></two> <t>   <for>two</for> </t> <multi>one</multi> <multi>two</multi> </test>' ); foreach((array) $sx as $tagname => $val) {     if ( is_string($val)) {        // <one> will go here     } elseif (is_array($val)) {        // <multi> will go here because it happens multiple times     } elseif (is_object($val)) {       // <t> will go here because it contains tags       // <two> will go here because it contains CDATA!     } } ?> To test in the loop, do this <?php if (count((array) $val) == 0) {     // this is not a tag that contains other tags     $val = '' . $val;     // now the CDATA is revealed magically. } ?> up -1 hattori at hanso dot com 8 years ago If you want to serialize and unserialize SimpleXMLElement objects for caching, you need to transform the SimpleXMLElement object into a standard class object before unserializing. This is only if you want to cache converted data, the functionallity of the SimpleXMLElement will not be held. $content = '<SomeXML....' $serialized = str_replace(   array('O:16:"SimpleXMLElement":0:{}', 'O:16:"SimpleXMLElement":'),   array('s:0:"";', 'O:8:"stdClass":'),   serialize(simplexml_load_string($content)) ); $unserialized = unserialize($serialized); up -2 tiznull 6 years ago SimpleXMLElement - Warning: unserialize() [function.unserialize]: Node no longer exists in … .php If you get this error from storing serialized SimpleXMLElement data then this is your fix… <?php function sxml_unserialze($str) { return unserialize(str_replace(array('O:16:"SimpleXMLElement":0:{}', 'O:16:"SimpleXMLElement":'), array('s:0:"";', 'O:8:"stdClass":'), $str)); } ?> up -2 supzero at phparts dot net 6 years ago if we don't know children number. How many loop. How many key. <?php class XML {     protected $pointer;     public    $degerler=array();         function loadString($string){         $this->pointer = simplexml_load_string($string);                 return $this->pointer;     }         function loadFile($file){         $this->pointer = simplexml_load_file($file);         return $this->pointer;     }         function getname(){         return $this->pointer->getName();     }     function child(){         return $this->pointer->children();     }     function att(){         return $this->pointer->attributes();     }     function toArray(){         foreach ( $this->child() as $sq){             $this->degerler[$this->getname()][$sq->getname()][][] = $sq; // How many key         }         return;     }     } ?> up -2 nospam at qool dot com 7 years ago simplexml doesn't appear to like long attributes. I have tried passing it a valid xhtml document but the url in the anchor tag was causing simplexml to generate an error. up -2 youx_free_fr 8 years ago While needing to add an xml subtree to an existing simplexml object, I noticed that simplexml_load_string fails with strings like <emptynode></emptynode> I needed to use dom instead of simplexml to bypass this problem and work with any kind of xml strings. up -2 lists at cyberlot dot net 10 years ago While you can't add new elements to a SimpleXML object you can however add new attributes <?php $string = '<doc channel="chat"><test1>Hello</test1></doc>'; $xml = simplexml_load_string($string); $xml->test1['sub'] = 'No'; echo $xml->asXML(); ?> Will return output <doc channel="chat"><test1 sub="No">Hello</test1></doc> up -1 lb at bostontech dot net 4 years ago please note that: <? $data_array = (array) simplexml_load_string($xml_string); ?> will only convert the root element to an array, where as the child elements remain XML objects. To prove this, try returning a value N objects deep by association.  Then try the same exercise using something like the object2array example below. (Which works great). up -2 thejhereg at gmail dot com 5 years ago "simplexml_load_string() : Entity: line #: parser error : Comment not terminated" On the off chance you see this error and you're pulling your hair out over it, simplexml can't seem to correctly parse XML comment tags if the comment contains "--". Is silly and likely won't happen very often -- but sometimes it does. ;-) up -3 greg dot steffensen at spamless dot richmond dot edu 11 years ago Simplexml's simplicity can be deceptive.  Simplexml elements behave either as objects or strings, depending on the context in which they're used (through overloading of the __toString() method, I assume).  Statements implying conversion to string treat them as strings, while assignment operations treat them as objects.  This can lead to unexpected behavior if, for example, you are trying to compare the values of two Simplexml elements.  The expected syntax will not work.  To force conversion to strings, just "typecast' whatever Simplexml element you're using.  For example: <?php $s = simplexml_load_string('<foo>43</foo> <bar>43</bar>'); // Evaluates to false by comparing object IDs instead of strings ($s->foo == $s->bar); // Evaluates to true ((string)$s->foo == (string)$s->bar); ?> [Ed. Note: Changed from quotes to casts because casts provide a quicker and more explicit conversion than do double quotes.] To Top
__label__pos
0.671493
PHP Article Managing Class Dependencies: An Introduction to Dependency Injection, Service Locators, and Factories, Part 1 By Alejandro Gervasio Managing Class Dependencies: An Introduction to Dependency Injection, Service Locators, and Factories Let’s face it: for good or bad, OOP has been actively drilling deep holes in the soil of PHP in the last few years, hence its ubiquitous presence now is anything but breaking news. Furthermore, while this steady incremental “objectification” in the language’s terrain is generally considered a beneficial shift towards new and more promising horizons, for those still rooted in the procedural paradigm, the process has been far from innocuous. There’s a few solid arguments that sustain this mindset: first and foremost the nature of OOP is awkward and inherently complex, plagued with nuance that can take literally years to tame. Also, defining the APIs that OO components use for interacting with one another can be quite a burden at times, especially when it comes to designing systems whose backbone rests on facilities provided by large and tangled object graphs. From a programmer’s perspective, the process of designing easily consumable APIs while still keeping a decent level of decoupling between the involved classes is always a tricky trade-off, as the more expressive the dependencies are, the harder the work is that needs to be done behind the scenes for wiring up the collaborators in their proper sequence. This fact itself is a dilemma that has plagued the minds of developers from long ago, which is certainly harder to digest as time goes by. With applications becoming increasingly bloated, housing inside their boundaries a growing number of classes, the construction of clean, declarative APIs isn’t just a loose practice anymore that can eventually be pushed into the language’s mainstream from time to time. It’s simply a must. This raises a few interesting questions: how should a class be provided with its dependencies without cluttering its API, or even worse, without coupling it to the dependencies themselves? Just by appealing to the benefits of Dependency Injection? Through the reigns of an injected Service Locator? For obvious reasons, there’s no a one size fits all solution to the problem, even when all of the aforementioned approaches have something in common. Yes, to some extent they all make use of some form of Inversion of Control, which not only allows you to decouple the dependencies from the class but also keeps a neat level of insulation between the dependences’ interfaces and the implementation, making mocking/testing a breeze. Evidently, the topic is a world away from being banal, and as such it deserves a close, in-depth analysis. In this two-part series I’ll be doing a quick roundup of some of the most common methodologies that can be employed for managing class dependencies in modern application development, ranging from using service locators and injectable factories, to sinking your teeth into plain vanilla Dependency Injection, and even implementing a naive Dependency Injection Container. A (Hopefully) Vanishing Plague – “new” Operators in Constructors The mantra is somewhat old, sure, but its claim still rings loud and clear: “placing ‘new’ operators in constructors is just plain evil.” We all know that now, and even take for granted that we’ll never commit such a cardinal sin. But this was literally the default method used for years for a class to look up its dependencies before Dependency Injection reached the PHP world. For the sake of completeness, let’s recreate this clunky, old-fashioned scenario and remind ourselves why we should get away from such a harmful plague. Say that we need to build a simple file storage module which must internally consume a serializer in order to read and write data to a specific file. The implementation of the serializer would look something like to this: <?php namespace LibraryEncoder; class Serializer implements Serializable { public function serialize($data) { if (is_resource($data)) { throw new InvalidArgumentException( "PHP resources are not serializable."); } if (($data = serialize($data)) === false) { throw new RuntimeException( "Unable to serialize the supplied data."); } return $data; } public function unserialize($data) { if (!is_string($data)|| empty($data)) { throw new InvalidArgumentException( "The data to be unserialized must be a non-empty string."); } if (($data = @unserialize($data)) === false) { throw new RuntimeException("Unable to unserialize the supplied data."); } return $data; } } The Serializer class is just a lightweight implementation of the native Serializable interface and exposes the typical serialize/unserialize duet to the outside world. With this contrived strategy class doing its thing as expected, the aforementioned file storage module could be sloppily coded as follows: <?php namespace LibraryFile; use LibraryEncoderSerializer; class FileStorage { const DEFAULT_STORAGE_FILE = "data.dat"; protected $serializer; protected $file; public function __construct($file = self::DEFAULT_STORAGE_FILE) { $this->setFile($file); $this->serializer = new Serializer(); } public function setFile($file) { if (!is_file($file)) { throw new InvalidArgumentException( "The file $file does not exist."); } if (!is_readable($file) || !is_writable($file)) { if (!chmod($file, 0644)) { throw new InvalidArgumentException( "The file $file is not readable or writable."); } } $this->file = $file; return $this; } public function read() { try { return $this->serializer->unserialize( @file_get_contents($this->file)); } catch (Exception $e) { throw new Exception($e->getMessage()); } } public function write($data) { try { return file_put_contents($this->file, $this->serializer->serialize($data)); } catch (Exception $e) { throw new Exception($e->getMessage()); } } } The behavior of FileStorage boils down to just saving and pulling in data from a predefined target file. But the seemingly benign nature of the class is nothing but an illusion, as it blatantly instantiates the serializer in its constructor! This form of “dictatorial” dependency lookup not only introduces a strong coupling between the class and its dependency, but it condemns testability to a quick death. The following code shows how the artifacts ripple through to client code when using this approach: <?php $fileStorage = new FileStorage(); $fileStorage->write("This is a sample string."); echo $fileStorage->read(); Feel free to run the code and it’ll work like a charm, that’s for sure. But we know the coupling is there just beneath the surface, not to mention the fact that there’s not a single clue about if the FileStorage has an internal dependency on another component, or how this one was acquired. Definitively, this is pretty much like an antipattern which goes against the grain when it comes to defining clean, expressive class APIs. There’re a few additional approaches that are worth looking into that can improve the way the two previous classes interoperate with each other. For instance, we could be a bit bolder and inject a factory straight into the internals of FileStorage and let it create a serializer object when necessary, thus making the class’ dependency a little more explicit. Deferring the Creation of Dependencies through an Injected Factory Factories, in any of their forms, are nifty elements that allow us to nicely distill object construction from application logic. While such ability is quite remarkable in itself, it can be taken a bit further when mixed with the goodness of Dependency Injection. If you’re the curious sort like I am, you’ll be wondering how to exploit the benefits provided by a factory for enhancing how the earlier FileStorage class looks up its collaborator, getting rid of the infamous “new” operator in its constructor. At a very basic level, the lookup process could be reformulated through the following factory class: <?php namespace LibraryDependencyInjection; interface SerializerFactoryInterface { public function getSerializer(); } <?php namespace LibraryDependencyInjection; use LibraryEncoderSerializer; class SerializerFactory implements SerializerFactoryInterface { public function getSerializer() [ static $serializer; if ($serializer === null) { $serializer = new Serializer; } return $serializer; } } Having at hand a dynamic factory charged with the task of creating the serializer on demand, now the FileStorage class can be refactored to accept a factory implementer: <?php namespace LibraryFile; use LibraryDependencyInjectionSerializerFactoryInterface; class FileStorage { const DEFAULT_STORAGE_FILE = "data.dat"; protected $factory; protected $file; public function __construct(SerializerFactoryInterface $factory, $file = self::DEFAULT_STORAGE_FILE) { $this->setFile($file); $this->factory = $factory; } public function setFile($file) { if (!is_file($file)) { throw new InvalidArgumentException( "The file $file does not exist."); } if (!is_readable($file) || !is_writable($file)) { if (!chmod($file, 0644)) { throw new InvalidArgumentException( "The file $file is not readable or writable."); } } $this->file = $file; return $this; } public function read() { try { return $this->factory->getSerializer()->unserialize( @file_get_contents($this->file)); } catch (Exception $e) { throw new Exception($e->getMessage()); } } public function write($data) { try { return file_put_contents($this->file, $this->factory->getSerializer()->serialize($data)); } catch (Exception $e) { throw new Exception($e->getMessage()); } } } The functionality of FileStorage remains pretty much the same, but the tight coupling with the serializer has been broken by injecting an implementer of the SerializerFactoryInterface. This simple twist turns the class into a flexible and testable creature, which exposes a more expressive API, as is now easier to see from the outer world what dependencies it needs. The code below shows the result of these enhancements from the perspective of the client code: <?php $fileStorage = new FileStorage(new SerializerFactory()); $fileStorage->write("This is a sample string."); echo $fileStorage->read(); Let’s not fall into blind, pointless optimism, though. It’s fair to say the refactored implementation of the storage module looks more appealing; this approach makes it trivial to switch out different factory implementations at runtime. But in my opinion, at least in this case, it’s a masked violation of the Law of Demeter since the injected factory acts like an unnecessary mediator to the module’s real collaborator. This doesn’t mean that injected factories are a bad thing at all. But in most cases they should be used only for creating dependencies on demand, especially when the dependencies’ life cycles are shorter than that of the client class using them. Closing Remarks Quite often unfairly overlooked in favor of more “seductive” topics, managing class dependencies is unquestionably a central point of object-oriented design and whose underlying logic certainly goes much deeper than dropping a few “new” operators in factories, or worse, in stingy constructors that hide those dependencies from the outside world so they can’t be properly decoupled at will or tested in isolation. There’s no need to feel that all is lost, however, There exists a few additional approaches that can be utilized for handling in an efficient manner the way that classes are provided with their collaborators, including the use of the Service Locator pattern, raw Dependency Injection, and even appealing to the benefits of a Dependency Injection container. All these ones will be covered in detail in the follow up, so stay tuned! Image via SvetlanaR / Shutterstock More: • http://jeunito.me Jose Great article! Keep ’em coming especially the ones on design. Your articles make me think all the time. I liked how you injected a factory into the class and gave it the ability to change its dependency implementation at runtime. Never thought of that one before. However at least for the dependency, I think you are not doing any injecting at all. You injected a factory yes but the way the actual dependency is managed is not anymore more through dependency injection but rather through a factory inside the dependent class. It’s the class now that’s injecting to itself rather than an outside injector injecting dependencies into the class. What do you think? • Alex Gervasio Hi Jose, Glad the post has been overall informative. I like your question on the injectable factory, cause it’s really a good one. In fact, the approach does stick to the formalities of dependency injection, only that the factory is in itself a dependency. Though not precisely prolific, the use of injectable factories is particularly appealing is those cases where the dependencies have shorter lifecycles than the class that houses them, thus deferring their creation until the very last minute. For obvious reasons, the downside of this rest on the fact that you’re using a mediator to get the actual dependency, an issue also exposed by a service locator, be it static or dynamic. So, is this a somewhat furtive form of breakage of the Law of Demeter? In a sense, it is. But, it’s a sort of tradeoff you have to learn to live with, specially if you want to exploit its benefits. Thanks for the feedback. • http://jeunito.me Jose I worked in the Java world before heading over to PHP and back there, dependency injection is old news. It’s slow to gain traction in PHP though and the fact that it just gets attention nowadays is a bit sad if you ask me. • Alex Gervasio Better getting late to the party than never :) • Kise S. Hi thanks for the article, can you please write an article about how to make a plugin/hook system with classes so that it doesn’t need to be changed manually? using standard way right now i use hacks to implement my system where i modify the code to add injection point so that other hooks can register and listen to event and add code, but i think its kinda pointless if i have to modify the code it self to add injection points, im still thinking about my next project so im all ears for new ideas about how to extend codes without having to modifying them, that will make auto-update system easier, where the user just click and wola the whole core system updated without breaking their websites • Alex Gervasio Hey, Thanks for the comments. To be frank, writing such article isn’t something I have in mind right now, but just based on the batch of issues you’re describing above, I guess you need to put in practice the old venerable “Programming to Interfaces” principle, which rests on the foundations of Polymorphism. Regardless of the nature of the system you’re implementing, be nice and make your classes depend upon abstractions (interfaces, abstract classes or both), instead of on concrete implementations. In doing so, you can easily create different implementers of the interfaces in question, without having to amend a single pinch your existing code, thus making it easily pluggable and extendable (AKA open for extension, closed for modification). Just make sure to stick from top to bottom to that approach and things will flow like a charm, trust me. • Dean Thanks for the article. Apparently, I’ve been doing the old school way. I’ll definatly rectify that in my future projects. Did you mean to type hint SerializerFactory and not SerializerFactoryInterface on line 11 of your file storage class, or am I missing something? Thanks, Dean • Alex Gervasio Hi Dean, Thanks for the insights. In fact, the file storage class types hint the factory interface. That way, it’s not coupled to any implementation in particular. • Daniel Lowrey I only made it to the first example before I had to comment. I’m not sure about what comes after it, but … Creating a `Serializer` implementation that only exists to serialize external data is a bastardization of OOP. The point of `Serializable` is just what it sounds like: to allow easy serialization of an existing object. A class that implements `Serializable` needs to be serialized; a `Serializer` does not. • Alex Gervasio Daniel, That’s only your opinion, which though respectable, to my view is wrong. The point of Serializable, just like any other interface that might exist out there, either native or defined in userland is to provide a contract. Period. From that point onward, whatever you want to do with it, or what implementers you wish to build up on top of it is entirely up to you. Even when the practice of using Serializable to create serializable classes is certainly ubiquitous in PHP, it doesn’t mean if I ever use it with other implementers I’m just being a sinner with OOP. Thanks for the feedback. • Daniel Lowrey I don’t have a problem with your logic regarding interfaces, but `Serializable` exists to make objects that need to be serialized work with calls to `serialize()` and `unserialize`. Your Serializer class doesn’t itself need to be serialized or unserialized; it’s not serializable, so it shouldn’t implement the `Serializable` interface. Doing so only uses part of the standard library in a way that’s misleading. If you aren’t serializing/unserializable Serializer instances then the Serializer class shouldn’t implement `Serializable`: “` $obj = new Serializer; $serialized = serialize($obj); $newSerializer = unserialize($serialized); “` • Alex Gervasio Daniel, I get your point. While not showcased in this first installment, I’m just using the contract provided by “Serializable” to assure any implementation injected into FileStorage exposes the “serialize/unserialize” methods. And yep, in perspective this might be potentially misleading, considering the purpose of Serializable. A userland interface should fit better. Thanks for the opinions. • Gordon I agree with Daniel. One important aspect of OOP is deciding what is something, and that has something (is_a versus has_a). A lot of programmers, especially PHP programmers subclass inappropriately (Just look at how many Zend projects have all their models inherit from Zend_Db_* if you don’t believe me!), but you’ve got to remember the semantics of your objects. Every object has relationships with other objects (has a), but equally they also have characteristics that make them what they are (is a). If an object needs to be serialised, then that means that it is a serialisable object, and it should implement the appropriate interfaces. Then you can pass your object into anything that expects to be able to serialise the provided object, making for a very flexible design. I’m also not sure the factory should be enforcing the single instance constraint, it feels a little too close to Singleton for comfort for me. I think the solution to that one is also something that would address the LoD concerns. Have the factory’s getSerializer() method do nothing more than new Serializer, and have a $serializer private property in your consumer class and a getSerializer () method that does the lazy instantiation through the factory. Now you can replace the $factory -> getSerializer() calls with $this -> getSerializer() calls instead. As you’re now accessing a property of the object itself instead of a property of the factory, the LoD is satisfied (except in one place, the getter method that uses the factory to instantiate the serializer). • Alex Gervasio I agree with the semantic-related concepts, sure. In this case, however, we’re far away from debating the “is-a/has-a” dilemma, which by the way is never present in the examples. The point is that if you’re using an implementer of Serializable, client code can rest assured it’ll be consuming an object that conforms to the “serialize/unserialize” contract. It’s really that easy. Of course, if you want to appeal to a user-defined interface that describes more semantically the nature of the contract, rather than a native one, nobody will blame you for that :) Regarding the factory’s implementation, yep, your approach looks slightly better in the sense it doesn’t walk on the dangerous Singleton edge, even though it delegates the control of the instantiation of the serializer straight to FileStorage. Pretty ugly, as now the class has too many responsibilities to my taste, not to mention it violates the LoD as well. Thanks for the opinions. Agreed or not, they’re valuable, trust me. • http://www.andrejfarkas.com Andy Hmm, I don’t get the use of factory here. Why do you make the FileSotrage depend on factory and not on Serializer itself? I mean you can as well pass an instance of Serializer to FileStorage constructor. I think the factory is better used in cases where the object itself returns an instance of some other class. The object would then ask an injected factory to build such a new instance for it and return that one. Just can’t see the benefits of using factory in your particular example. • Alex Gervasio As pointed out in the post, the role of the factory is to defer the instantiation of the dependency. No more, no less. Naturally, at first blush this seems to be rather pointless with the FileStorage class, but in some specific use cases, this does make sense. So, don’t get ahead of yourself, as the follow up also shows a File Storage implementation, where the serializer is directly injected into the class, without no mediators in between. Thanks. • Jesper Hi Alex! I found the article enjoyable to read and am looking forward to see further parts of the series. A question I have is, in the constructor of the new FileStorage class, would it break the OOP pattern or be considered bad practice to do like this: public function __construct(…){ $this->factory = $factory; $this->serializer = $this->factory-> getSerializer(); } Thanks for an interesting article! :) • Alex Gervasio Hey Jesper, Glad to know that. In regards to your question, well, assigning the serializer and the factory to class members is simply pointless. Either you should inject the former or the latter, but never both. Thanks for the comments. • Boabramah Ernest The who has sin and who has not sin is making me confuse. I am now starting to grasp the whole concept about dependency injection and am begining to get it from tutorials like this. I hope you get the time to continue the series. I will like you to also address how we can test the classes. Thanks alot and will be coming back • Alex Gervasio Hey Ernest, Nice to know the article helped you start treading the DI path on the right foot. The second part does cover a few additional concepts, like plain DI, service locators and DICs, but for the sake of brevity, it stays away from showing how to test the sample classes in isolation. Nevertheless, if you’re already get along with PHPUnit, or with any other unit test framework available out there supporting stubs/mocks, this shouldn’t be an issue at all. When hooked it up to Programming to Interfaces (hence Polymorphism) DI allows to decouple classes from their dependencies and those dependencies from the concrete implementations. Thanks for stopping by and dropping your comments. Recommended Sponsors Learn Coding Online Learn Web Development Start learning web development and design for free with SitePoint Premium! Get the latest in PHP, once a week, for free.
__label__pos
0.713377
Version 2.1.2 matplotlib Fork me on GitHub Travis-CI: Related Topics This Page 3D voxel / volumetric plot with rgb colors Demonstrates using ax.voxels to visualize parts of a color space ../../_images/sphx_glr_voxels_rgb_001.png import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D def midpoints(x): sl = () for i in range(x.ndim): x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0 sl += np.index_exp[:] return x # prepare some coordinates, and attach rgb values to each r, g, b = np.indices((17, 17, 17)) / 16.0 rc = midpoints(r) gc = midpoints(g) bc = midpoints(b) # define a sphere about [0.5, 0.5, 0.5] sphere = (rc - 0.5)**2 + (gc - 0.5)**2 + (bc - 0.5)**2 < 0.5**2 # combine the color components colors = np.zeros(sphere.shape + (3,)) colors[..., 0] = rc colors[..., 1] = gc colors[..., 2] = bc # and plot everything fig = plt.figure() ax = fig.gca(projection='3d') ax.voxels(r, g, b, sphere, facecolors=colors, edgecolors=np.clip(2*colors - 0.5, 0, 1), # brighter linewidth=0.5) ax.set(xlabel='r', ylabel='g', zlabel='b') plt.show() Total running time of the script: ( 0 minutes 0.237 seconds) Gallery generated by Sphinx-Gallery
__label__pos
0.990836
Overcoming Data Preparation Challenges with Low-Code Tools PinIt Low-code tools can automate tasks that have historically consumed a significant portion of data teams’ days liberating them to focus more on analysis and less on preparation. Data teams face a critical challenge: the imbalance between the extensive amount of time spent on data preparation and the relatively limited amount of time available for the analysis and model training. Data scientists spend the majority of their work days on data-curation activities like data preparation and cleansing. The problem is that the resource-heavy framework for data preparation impedes organizations’ ability to focus on the model training and data investigation that drives growth and innovation. Think of the problem as an iceberg. Tasks like data standardization, integration and cleaning are a massive undertaking, but they’re all necessary for achieving data insights that provide real value to the organization. Too often, data analysis sits as a tiny suspended ice cap compared to the broad base of beneath-the-surface data engineering support it requires. However, with the adoption of low-code platforms, organizations can reduce the time spent on data preparation tasks, freeing up their data teams to prioritize data analysis and the application of critical insights. See also: Accelerating Digital Transformation: Low Code + Composable Data preparation is a necessary but time-consuming task Recognizing the need for high-quality data is the first step in the journey toward meaningful analytics. In the era of advanced AI, algorithms require quality data to generate meaningful insights. If the data isn’t clean, it can lead to inaccuracies and mistakes. The challenge for data teams doesn’t stem from a lack of data. Instead, the problem lies in the labor-intensive process required to refine and render the vast quantities of available data into a state that is both clean and useful.  Data preparation demands significant time and resources because it includes tasks like standardizing disparate data formats, identifying relevant data across myriad sources, and cleaning “dirty data” to distinguish between errors and outliers. While often tedious and technical, these tasks are necessary for preparing data that’s clean, well-aggregated and informative — and capable of unlocking actionable insights that drive strategic decision-making. This need for clean data is amplified by the data science talent shortage, which underscores the importance of adopting solutions like low-code tools. With low-code platforms, organizations can help fill the talent gap by enabling a greater percentage of their workforce to engage in data preparation. Data teams can then redirect their focus to extracting insights and generating value from the data. 3 ways low-code tools can create efficiencies and drive innovation Low-code tools remove coding barriers, democratize data access, and streamline the data preparation process. By enabling your data team to focus more on analysis and less on preparation, your organization can more effectively apply key takeaways and drive meaningful business progress. This strategic shift accelerates the data-to-insight cycle and enables data professionals to contribute more significantly to your organization’s strategic objectives. With a low-code tool, you can: 1) Eliminate the coding barrier When it comes to data preparation, math, and programming are barriers to participation in data from teams outside of IT/data teams. Low-code tools remove the coding barrier so any user who knows the domain and data can actively engage in the data preparation and analysis process. For skilled programmers, low-code platforms offer the advantage of saving time and, therefore, the chance to concentrate on the analysis and on the steps in the process. While these tools eliminate certain barriers, they don’t eliminate the need for domain expertise and knowledge of data transformation operations. Employees who lack coding skills will still need a basic understanding of math to work with low-code tools. However, these tools make data more accessible and empower a wider range of professionals to leverage their industry-specific expertise. In turn, this accelerates the data preparation phase and drives innovation. 2) Improve automation and reduce errors Low-code tools transform manual, repetitive tasks into automated processes, enhancing operational reliability and consistency. This shift optimizes workflow efficiency, reduces errors, and sets the stage for more advanced data handling techniques. For example, low-code tools streamline the process of connecting to various data sources (e.g., files, databases with unique authentication procedures, cloud repositories, and even handwritten notes) by offering standardized and simplified connectors that mask complex details. They also facilitate fundamental data preparation tasks such as aggregations, filtering, joins, and concatenations through an intuitive drag-and-drop interface, eliminating the need for manual coding of indexes and functions. Traditional methods like Excel spreadsheets need to be manually adjusted for varying data sets — leading to errors when data exceeds predefined parameters, like the number of days in a month. But low-code platforms automatically adapt to changes, processing all input data uniformly and accurately without the need for constant manual oversight. 3) Streamline recruiting processes It’s not easy finding candidates with both advanced coding skills and deep domain knowledge. When organizations set this high bar, they limit the pool of suitable candidates and prolong the recruitment process, delaying critical data-driven projects. Low-code platforms make it easier to identify and onboard employees who can navigate the intricacies of data without the need to be proficient in more complex programming languages like Python. By enabling individuals who are familiar with the data and its key performance indicators (KPIs) to perform preparation and analysis tasks, low-code tools can solve the recruiting problem. As a result, you can deploy resources more effectively and focus on leveraging domain-specific knowledge to drive insights and innovation without being constrained by the technical barrier of coding expertise. Enable any user to intuitively work with data Data preparation is often cumbersome and resource-intensive. But low-code platforms enhance the efficiency of the data preparation process and democratize data handling, so users across all skill levels can intuitively interact with data. Reducing the time and effort it takes to prepare data for analysis optimizes the time for workflow creation and expands your talent pool by lowering the barrier to entry for engaging with data. Automating tasks that have historically consumed a significant portion of data teams’ days liberates them to focus more on analysis and less on preparation. This efficiency fosters innovation and enables teams to use the time they save to develop new ideas and propel their organization forward. Dr. Rosaria Silipo About Dr. Rosaria Silipo Dr. Rosaria Silipo has been working in data analytics since 1992. Currently, she is Head of Data Science Evangelism at KNIME. In the past, she has held senior positions with Siemens, Viseca AG, and Nuance Communications and worked as a consultant on a number of data science projects. She holds a Ph.D. in Bioengineering from the Politecnico di Milano and a Masters in Electrical Engineering from the University of Florence; and is the author of more than 50 scientific publications, many scientific whitepapers, and a number of books for data science practitioners. Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.650318
source: gs3-extensions/solr/trunk/src/perllib/solrbuilder.pm@ 24453 Last change on this file since 24453 was 24453, checked in by davidb, 13 years ago Tidy up of code. Better structuring of classes File size: 16.4 KB Line  1########################################################################### 2# 3# solrbuilder.pm -- perl wrapper for building index with Solr 4# A component of the Greenstone digital library software 5# from the New Zealand Digital Library Project at the 6# University of Waikato, New Zealand. 7# 8# Copyright (C) 1999 New Zealand Digital Library Project 9# 10# This program is free software; you can redistribute it and/or modify 11# it under the terms of the GNU General Public License as published by 12# the Free Software Foundation; either version 2 of the License, or 13# (at your option) any later version. 14# 15# This program is distributed in the hope that it will be useful, 16# but WITHOUT ANY WARRANTY; without even the implied warranty of 17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18# GNU General Public License for more details. 19# 20# You should have received a copy of the GNU General Public License 21# along with this program; if not, write to the Free Software 22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. 23# 24########################################################################### 25 26 27package solrbuilder; 28 29use strict; 30no strict 'refs'; 31 32use lucenebuilder; 33use solrserver; 34use Config; # for getting the perlpath in the recommended way 35 36sub BEGIN { 37 @solrbuilder::ISA = ('lucenebuilder'); 38} 39 40 41sub new { 42 my $class = shift(@_); 43 my $self = new lucenebuilder (@_); 44 $self = bless $self, $class; 45 46 $self->{'buildtype'} = "solr"; 47 48 my $solr_passes_script = "solr_passes.pl"; 49 50 $self->{'solr_passes'} = "$solr_passes_script"; 51 # Tack perl on the beginning to ensure execution 52 $self->{'solr_passes_exe'} = "\"$Config{perlpath}\" -S \"$solr_passes_script\""; 53 return $self; 54} 55 56 57sub default_buildproc { 58 my $self = shift (@_); 59 60 return "solrbuildproc"; 61} 62 63# This writes a nice version of the text docs 64# 65# Essentially the same as the lucenebuilder.pm version, only using solr_passes 66# => refactor and make better use of inheritence 67# 68sub compress_text 69{ 70 my $self = shift (@_); 71 # do nothing if we don't want compressed text 72 return if $self->{'no_text'}; 73 74 my ($textindex) = @_; 75 76 # workaround to avoid hard-coding "solr" check into buildcol.pl 77 $textindex =~ s/^section://; 78 79 my $outhandle = $self->{'outhandle'}; 80 81 # the text directory 82 my $text_dir = &util::filename_cat($self->{'build_dir'}, "text"); 83 my $build_dir = &util::filename_cat($self->{'build_dir'},""); 84 &util::mk_all_dir ($text_dir); 85 86 my $osextra = ""; 87 if ($ENV{'GSDLOS'} =~ /^windows$/i) 88 { 89 $text_dir =~ s@/@\\@g; 90 } 91 else 92 { 93 if ($outhandle ne "STDERR") 94 { 95 # so solr_passes doesn't print to stderr if we redirect output 96 $osextra .= " 2>/dev/null"; 97 } 98 } 99 100 # Find the perl script to call to run solr 101 my $solr_passes = $self->{'solr_passes'}; 102 my $solr_passes_exe = $self->{'solr_passes_exe'}; 103 104 my $solr_passes_sections = "Doc"; 105 106 my ($handle); 107 108 if ($self->{'debug'}) 109 { 110 $handle = *STDOUT; 111 } 112 else 113 { 114 my $collection = $self->{'collection'}; 115 116 print STDERR "Executable: $solr_passes_exe\n"; 117 print STDERR "Sections: $solr_passes_sections\n"; 118 print STDERR "Build Dir: $build_dir\n"; 119 print STDERR "Cmd: $solr_passes_exe $collection text $solr_passes_sections \"$build_dir\" \"dummy\" $osextra\n"; 120 if (!open($handle, "| $solr_passes_exe $collection text $solr_passes_sections \"$build_dir\" \"dummy\" $osextra")) 121 { 122 print STDERR "<FatalError name='NoRunSolrPasses'/>\n</Stage>\n" if $self->{'gli'}; 123 die "solrbuilder::build_index - couldn't run $solr_passes_exe\n$!\n"; 124 } 125 } 126 127 # stored text is always Doc and Sec levels 128 my $levels = { 'document' => 1, 'section' => 1 }; 129 # always do database at section level 130 my $db_level = "section"; 131 132 # set up the document processr 133 $self->{'buildproc'}->set_output_handle ($handle); 134 $self->{'buildproc'}->set_mode ('text'); 135 $self->{'buildproc'}->set_index ($textindex); 136 $self->{'buildproc'}->set_indexing_text (0); 137 #$self->{'buildproc'}->set_indexfieldmap ($self->{'indexfieldmap'}); 138 $self->{'buildproc'}->set_levels ($levels); 139 $self->{'buildproc'}->set_db_level ($db_level); 140 $self->{'buildproc'}->reset(); 141 142 &plugin::begin($self->{'pluginfo'}, $self->{'source_dir'}, 143 $self->{'buildproc'}, $self->{'maxdocs'}); 144 &plugin::read ($self->{'pluginfo'}, $self->{'source_dir'}, 145 "", {}, {}, $self->{'buildproc'}, $self->{'maxdocs'}, 0, $self->{'gli'}); 146 &plugin::end($self->{'pluginfo'}); 147 148 close ($handle) unless $self->{'debug'}; 149 $self->print_stats(); 150 151 print STDERR "</Stage>\n" if $self->{'gli'}; 152} 153 154#---- 155 156 157 158sub filter_in_out_file 159{ 160 my ($in_filename,$out_filename,$replace_rules) = @_; 161 162 if (open(SIN,"<$in_filename")) { 163 164 if (open(SOUT,">$out_filename")) { 165 166 my $line; 167 while (defined ($line=<SIN>)) { 168 chomp $line; 169 170 my $done_insert = 0; 171 foreach my $rule (@$replace_rules) { 172 my $line_re = $rule->{'regexp'}; 173 my $insert = $rule->{'insert'}; 174 175 if ($line =~ m/$line_re/) { 176 print SOUT $insert; 177 $done_insert = 1; 178 last; 179 } 180 } 181 if (!$done_insert) { 182 print SOUT "$line\n";; 183 } 184 } 185 186 close(SOUT); 187 } 188 else { 189 print STDERR "Error: Failed to open $out_filename\n"; 190 print STDERR " $!\n"; 191 } 192 193 close(SIN); 194 } 195 else { 196 print STDERR "Error: Failed to open $in_filename\n"; 197 print STDERR " $!\n"; 198 } 199 200} 201 202# Generate solr schema.xml file based on indexmapfield and other associated 203# config files 204# 205# Unlike make_auxiliary_files(), this needs to be done up-front (rather 206# than at the end) so the data-types in schema.xml are correctly set up 207# prior to document content being pumped through solr_passes.pl 208 209 210sub premake_solr_auxiliary_files 211{ 212 my $self = shift (@_); 213 214 # Replace the following marker: 215 # 216 # <!-- ##GREENSTONE-FIELDS## --> 217 # 218 # with lines of the form: 219 # 220 # <field name="<field>" type="string" ... /> 221 # 222 # for each <field> in 'indexfieldmap' 223 224 my $schema_insert_xml = ""; 225 226 foreach my $ifm (@{$self->{'build_cfg'}->{'indexfieldmap'}}) { 227 228 my ($field) = ($ifm =~ m/^.*->(.*)$/); 229 230 # Need special case for Long/Lat 231 # ... but for now treat everything as of type string 232 233 $schema_insert_xml .= " "; # indent 234 $schema_insert_xml .= "<field name=\"$field\" "; 235 $schema_insert_xml .= "type=\"string\" indexed=\"true\" "; 236 $schema_insert_xml .= "stored=\"false\" multiValued=\"true\" />\n"; 237 } 238 239 # just the one rule to date 240 my $insert_rules 241 = [ { 'regexp' => "^\\s*<!--\\s*##GREENSTONE-FIELDS##\\s*-->\\s*\$", 242 'insert' => $schema_insert_xml } ]; 243 244 my $solr_home = $ENV{'GEXT_SOLR'}; 245 my $in_dirname = &util::filename_cat($solr_home,"etc","conf"); 246 my $schema_in_filename = &util::filename_cat($in_dirname,"schema.xml.in"); 247 248 249 my $collect_home = $ENV{'GSDLCOLLECTDIR'}; 250 my $out_dirname = &util::filename_cat($collect_home,"etc","conf"); 251 my $schema_out_filename = &util::filename_cat($out_dirname,"schema.xml"); 252 253 # make sure output conf directory exists 254 if (!-d $out_dirname) { 255 &util::mk_dir($out_dirname); 256 } 257 258 filter_in_out_file($schema_in_filename,$schema_out_filename,$insert_rules); 259 260 # now do the same for solrconfig.xml, stopwords, ... 261 # these are simpler, as they currently do not need any filtering 262 263 my @in_file_list = ( "solrconfig.xml", "stopwords.txt", "stopwords_en.txt", 264 "synonyms.txt", "protwords.txt" ); 265 266 foreach my $file ( @in_file_list ) { 267 my $in_filename = &util::filename_cat($in_dirname,$file.".in"); 268 my $out_filename = &util::filename_cat($out_dirname,$file); 269 filter_in_out_file($in_filename,$out_filename,[]); 270 } 271} 272 273 274sub solr_core_admin 275{ 276 my $self = shift (@_); 277 my ($url) = @_; 278 279 my $cmd = "wget -q -O - \"$url\""; 280 281 my $status = undef; 282 283 if (open(WIN,"$cmd |")) { 284 285 my $xml_output = ""; 286 my $line; 287 while (defined ($line=<WIN>)) { 288 289 $xml_output .= $line; 290 } 291 close(WIN); 292 293## print $xml_output; 294 295 ($status) = ($xml_output =~ m!<int name="status">(\d+)</int>!s); 296 297 } 298 else { 299 print STDERR "Warning: failed to run $cmd\n"; 300 print STDERR " $!\n"; 301 } 302 303 return $status; 304 305} 306 307sub pre_build_indexes 308{ 309 my $self = shift (@_); 310 my ($indexname) = @_; 311 my $outhandle = $self->{'outhandle'}; 312 313 # If the Solr/Jetty server is not already running, the following starts 314 # it up, and only returns when the server is "reading and listening" 315 316 my $solr_server = new solrserver(); 317 $solr_server->start(); 318 $self->{'solr_server'} = $solr_server; 319 320 my $indexes = []; 321 if (defined $indexname && $indexname =~ /\w/) { 322 push @$indexes, $indexname; 323 } else { 324 $indexes = $self->{'collect_cfg'}->{'indexes'}; 325 } 326 327 # skip para-level check, as this is done in the main 'build_indexes' 328 # routine 329 330 my $all_metadata_specified = 0; # has the user added a 'metadata' index? 331 my $allfields_index = 0; # do we have an allfields index? 332 333 # Using a hashmap here would duplications, but while more space 334 # efficient, it's not entirely clear it would be more computationally 335 # efficient 336 my @all_fields = (); 337 338 foreach my $index (@$indexes) { 339 if ($self->want_built($index)) { 340 341 # get the parameters for the output 342 # split on : just in case there is subcoll and lang stuff 343 my ($fields) = split (/:/, $index); 344 345 foreach my $field (split (/;/, $fields)) { 346 if ($field eq "metadata") { 347 $all_metadata_specified = 1; 348 } 349 else { 350 push(@all_fields,$field); 351 } 352 } 353 } 354 } 355 356 if ($all_metadata_specified) { 357 358 # (Unforunately) we need to process all the documents in the collection 359 # to figure out what the metadata_field_mapping is 360 361 # set up the document processr 362 $self->{'buildproc'}->set_output_handle (undef); 363 $self->{'buildproc'}->set_mode ('index_field_mapping'); 364 $self->{'buildproc'}->reset(); 365 366 &plugin::begin($self->{'pluginfo'}, $self->{'source_dir'}, 367 $self->{'buildproc'}, $self->{'maxdocs'}); 368 &plugin::read ($self->{'pluginfo'}, $self->{'source_dir'}, 369 "", {}, {}, $self->{'buildproc'}, $self->{'maxdocs'}, 0, $self->{'gli'}); 370 &plugin::end($self->{'pluginfo'}); 371 372 } 373 374 else { 375 # Field mapping solely dependent of entries in 'indexes' 376 377 # No need to explicitly handle "allfields" as create_shortname() 378 # will get a fix on it through it's static_indexfield_map 379 380 my $buildproc = $self->{'buildproc'}; 381 382 foreach my $field (@all_fields) { 383 if (!defined $buildproc->{'indexfieldmap'}->{$field}) { 384 my $shortname = $buildproc->create_shortname($field); 385 $buildproc->{'indexfieldmap'}->{$field} = $shortname; 386 $buildproc->{'indexfieldmap'}->{$shortname} = 1; 387 } 388 } 389 } 390 391 # Write out solr 'schema.xml' (and related) file 392 # 393 $self->make_final_field_list(); 394 $self->premake_solr_auxiliary_files(); 395 396 # Now update the solr-core information in solr.xml 397 # => at most two cores <colname>-Doc and <colname>-Sec 398 399 my $jetty_server_port = $ENV{'SOLR_JETTY_PORT'}; 400 my $base_url = "http://localhost:$jetty_server_port/solr/admin/cores"; 401 402 my $collection = $self->{'collection'}; 403 404 foreach my $level (keys %{$self->{'levels'}}) { 405 406 my $llevel = $mgppbuilder::level_map{$level}; 407 408 my $core = $collection."-".lc($llevel); 409 my $check_core_url = "$base_url?action=STATUS&core=$core"; 410 411 my $check_status = $self->solr_core_admin($check_core_url); 412 413 print STDERR "*** check status = $check_status\n"; 414 415 416 # if collect==core not already in solr.xml (check with STATUS) 417 # => use CREATE API to add to solr.xml 418 # 419 # else 420 # => use RELOAD call to refresh fields now expressed in schema.xml 421 } 422 423} 424 425# Essentially the same as the lucenebuilder.pm version, only using solr_passes 426# => refactor and make better use of inheritence 427 428sub build_index { 429 my $self = shift (@_); 430 my ($index,$llevel) = @_; 431 my $outhandle = $self->{'outhandle'}; 432 my $build_dir = $self->{'build_dir'}; 433 434 # get the full index directory path and make sure it exists 435 my $indexdir = $self->{'index_mapping'}->{$index}; 436 &util::mk_all_dir (&util::filename_cat($build_dir, $indexdir)); 437 438 # Find the perl script to call to run solr 439 my $solr_passes = $self->{'solr_passes'}; 440 my $solr_passes_exe = $self->{'solr_passes_exe'}; 441 442 # define the section names for solrpasses 443 # define the section names and possibly the doc name for solrpasses 444 my $solr_passes_sections = $llevel; 445 446 my $opt_create_index = ($self->{'incremental'}) ? "" : "-removeold"; 447 448 my $osextra = ""; 449 if ($ENV{'GSDLOS'} =~ /^windows$/i) { 450 $build_dir =~ s@/@\\@g; 451 } else { 452 if ($outhandle ne "STDERR") { 453 # so solr_passes doesn't print to stderr if we redirect output 454 $osextra .= " 2>/dev/null"; 455 } 456 } 457 458 # get the index expression if this index belongs 459 # to a subcollection 460 my $indexexparr = []; 461 my $langarr = []; 462 463 # there may be subcollection info, and language info. 464 my ($fields, $subcollection, $language) = split (":", $index); 465 my @subcollections = (); 466 @subcollections = split /,/, $subcollection if (defined $subcollection); 467 468 foreach $subcollection (@subcollections) { 469 if (defined ($self->{'collect_cfg'}->{'subcollection'}->{$subcollection})) { 470 push (@$indexexparr, $self->{'collect_cfg'}->{'subcollection'}->{$subcollection}); 471 } 472 } 473 474 # add expressions for languages if this index belongs to 475 # a language subcollection - only put languages expressions for the 476 # ones we want in the index 477 my @languages = (); 478 my $languagemetadata = "Language"; 479 if (defined ($self->{'collect_cfg'}->{'languagemetadata'})) { 480 $languagemetadata = $self->{'collect_cfg'}->{'languagemetadata'}; 481 } 482 @languages = split /,/, $language if (defined $language); 483 foreach my $language (@languages) { 484 my $not=0; 485 if ($language =~ s/^\!//) { 486 $not = 1; 487 } 488 if($not) { 489 push (@$langarr, "!$language"); 490 } else { 491 push (@$langarr, "$language"); 492 } 493 } 494 495 # Build index dictionary. Uses verbatim stem method 496 print $outhandle "\n creating index dictionary (solr_passes -I1)\n" if ($self->{'verbosity'} >= 1); 497 print STDERR "<Phase name='CreatingIndexDic'/>\n" if $self->{'gli'}; 498 my ($handle); 499 500 if ($self->{'debug'}) { 501 $handle = *STDOUT; 502 } else { 503 my $collection = $self->{'collection'}; 504 505 print STDERR "Cmd: $solr_passes_exe $opt_create_index $collection index $solr_passes_sections \"$build_dir\" \"$indexdir\" $osextra\n"; 506 if (!open($handle, "| $solr_passes_exe $opt_create_index $collection index $solr_passes_sections \"$build_dir\" \"$indexdir\" $osextra")) { 507 print STDERR "<FatalError name='NoRunSolrPasses'/>\n</Stage>\n" if $self->{'gli'}; 508 die "solrbuilder::build_index - couldn't run $solr_passes_exe\n!$\n"; 509 } 510 } 511 512 my $store_levels = $self->{'levels'}; 513 my $db_level = "section"; #always 514 my $dom_level = ""; 515 foreach my $key (keys %$store_levels) { 516 if ($mgppbuilder::level_map{$key} eq $llevel) { 517 $dom_level = $key; 518 } 519 } 520 if ($dom_level eq "") { 521 print STDERR "Warning: unrecognized tag level $llevel\n"; 522 $dom_level = "document"; 523 } 524 525 my $local_levels = { $dom_level => 1 }; # work on one level at a time 526 527 # set up the document processr 528 $self->{'buildproc'}->set_output_handle ($handle); 529 $self->{'buildproc'}->set_mode ('text'); 530 $self->{'buildproc'}->set_index ($index, $indexexparr); 531 $self->{'buildproc'}->set_index_languages ($languagemetadata, $langarr) if (defined $language); 532 $self->{'buildproc'}->set_indexing_text (1); 533 #$self->{'buildproc'}->set_indexfieldmap ($self->{'indexfieldmap'}); 534 $self->{'buildproc'}->set_levels ($local_levels); 535 $self->{'buildproc'}->set_db_level($db_level); 536 $self->{'buildproc'}->reset(); 537 538 print $handle "<update>\n"; 539 540 &plugin::read ($self->{'pluginfo'}, $self->{'source_dir'}, 541 "", {}, {}, $self->{'buildproc'}, $self->{'maxdocs'}, 0, $self->{'gli'}); 542 543 544 print $handle "</update>\n"; 545 546 close ($handle) unless $self->{'debug'}; 547 548 $self->print_stats(); 549 550 $self->{'buildproc'}->set_levels ($store_levels); 551 print STDERR "</Stage>\n" if $self->{'gli'}; 552 553} 554 555 556sub post_build_indexes { 557 my $self = shift(@_); 558 559 # deliberately override to prevent the mgpp post_build_index() calling 560 # $self->make_final_field_list() 561 # as this has been done in our pre_build_indexes() phase for solr 562 563 564 # Also need to stop the Solr/jetty server if it was explicitly started 565 # in pre_build_indexes() 566 567 my $solr_server = $self->{'solr_server'}; 568 569 if ($solr_server->explicitly_started()) { 570 $solr_server->stop(); 571 } 572 573 $self->{'solr_server'} = undef; 574 575} 576 577 5781; 579 580 Note: See TracBrowser for help on using the repository browser.
__label__pos
0.984098
Feature Post Breaking News Top 6 ways to parse .CSV? High Performance! Sometime back a question was asked to develop a well performant parser– there was no restriction defined in the question whatsoever as to what technology, logic, flow/etc should be applied. Just the input block, and expected output result format, and maximum time that the parser may take. This may answer questions: • How to query a .CSV and save the result in another CSV? • Custom .CSV Parser? • How to ETL .CSV into a .CSV • High performance .CSV parser I found the performance requirement interesting, and so is the reason of this post; besides, another reason is to discuss only “some” of the solutions of the problem; therefore, it should be stated clearly in a question as to what exactly is required, just to save the the test’ee and tester from any after shocks. Though can have several solutions, but lets get into the details and see what do we have here. Following are important aspects of the problem. Business requirement: Calculate the usage of different country and dial codes for a particular customer, and write result in a separate file. Functional requirement: • Read from CSV data source • Query for the data (select, group by, sum, count, etc) • Write into a separate .CSV file Non functional requirement: (Performance) Data source contains the ~1.2 million records, and the module is required to complete the whole procedure in less than 5 seconds. Given that: We have a CustomerData.CSV file already exists, to which we will query. CustomerData.CSV has the following schema: Columns Description Field 1 This field contains the customer id (sorted in ascending order) Field 2 Country code Field 3 Dial Code Field 4 Start time Field 5 Call duration Result.CSV has the following schema: Columns Description Field 1 Country code Field 2 Dial Code Field 3 Total duration (in minutes and seconds) SOLUTION 1: (Use Jet OLE DB Text Driver) Easiest, quickest, fastest, and very well performant! Step 1: Define the following schema.ini file in some folder that you like:  image If you would like, then look into the Schema.ini File (Text File Driver). Following content goes in schema.ini: 1: [CustomerData.csv] 2: Format=CSVDelimited 3: CharacterSet=ANSI 4: ColNameHeader=False 5: Col1=customerId Text Width 20 6: Col2=countryCode Short Width 3 7: Col3=dialCode Short Width 3 8: Col4=startTime DateTime Width 15 9: Col5=callDuration Text Width 5 10: [result.csv] 11: ColNameHeader=False 12: CharacterSet=1252 13: Format=CSVDelimited 14: Col1=countryCode Short 15: Col2=dialCode Short 16: Col3=Expr1002 Float STEP 2: Stub in the backend code in some .cs file 1: private static void Query(string CustomerID) 2: { 3: //Pseudo/logic: 4: //Use jet ole db text driver to select * insert into new table; 5: //to read-from a .csv, and write-into a .csv 6:  7: string customerId = CustomerID; 8: string writeTo = @"result.csv"; 9: string readFrom = @"CustomerData.csv"; 10:  11: //1: SELECT * INTO NEW_TABLE 12: //2: FROM SOURCE_TABLE 13:  14: //dont just read, write as well. 15: string query = @" SELECT 16: countryCode, dialCode, sum(callDuration) INTO " + writeTo + @" 17: FROM 18: [" + readFrom + @"] 19: WHERE 20: customerId='" + customerId + @"' 21: GROUP BY countryCode, dialCode"; 22:  23: Stopwatch timer = new Stopwatch(); 24:  25: try 26: { 27: Console.WriteLine("Looking for customer: {0}, to export into {1}.", customerId, writeTo); 28: 29: string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\MyDocs\Software Test\;Extended Properties='text;HDR=No;FMT=CSVDelimited'"; 30: using (OleDbConnection conn = new OleDbConnection(connectionString)) 31: { 32: OleDbCommand cmd = new OleDbCommand(query, conn); 33: conn.Open(); 34: timer.Start(); 35: int nRecordsAffected = cmd.ExecuteNonQuery(); 36: timer.Stop(); 37: conn.Close(); 38: } 39: } 40: catch (Exception ex) { Console.Write(ex.ToString()); } 41: Console.WriteLine("Time taken to read/write (ms):[{0}] ({1} secs)", timer.ElapsedMilliseconds, TimeSpan.FromMilliseconds(timer.ElapsedMilliseconds).Seconds); 42: } Output:  image SOLUTION 2: (Write a custom class, create indexes, and apply bisection search) For instance, following code performs following operations to achieve the same: 1. Perform indexing on the selected column  2. Select specific records from the .CSV file  3. Perform aggregate function, call SUM() – Use LINQ Usage: 1: using (CsvParser parser = new CsvParser(@"E:\CustomerData.csv")) 2: { 3: parser.PerformIndexing((int)CsvParser.CsvColumns.Col1_CustomerID);//One time only. 4:  5: timer.Start(); 6: parser.Select("AMANTEL").Sum((int)CsvParser.CsvColumns.CallDuration); 7: timer.Stop(); 8:  9: foreach (var o in parser.Result) 10: { 11: Console.WriteLine(string.Format("CountryCode:{0}, DialCode:{1}, TotalDurationOfCall:{2}", 12: o.CountryCode, o.DialCode, o.TotalDurationOfCall)); 13: } 14:  15: } 16: Console.WriteLine("Time taken to read/write (ms):[{0}] ({1} secs)", timer.ElapsedMilliseconds, TimeSpan.FromMilliseconds(timer.ElapsedMilliseconds).Seconds); Output: image  Backend code: 1: class CsvParser : IDisposable 2: { 3:  4: public dynamic Result { get; set; } 5: private string _fileName; 6: private char _separator = ','; 7: private Dictionary<string, Bounds> _lstIndex = new Dictionary<string, Bounds>(); 8: private List<string> _Rows = new List<string>(); 9: public enum CsvColumns { Col1_CustomerID = 0, Col2_CountryCode = 1, Col3_DialCode = 2, Col4_StartTime = 3, CallDuration = 5 } 10:  11: //Simple bound structure to hold start and end index in the file. 12: class Bounds 13: { 14: public int Start { get; set; } 15: public int End { get; set; } 16:  17: public Bounds(int start, int stop) { Start = start; End = stop; } 18: } 19:  20:  21: //Default constructor 22: public CsvParser(string file, char seperator = ',') 23: { 24: if (string.IsNullOrEmpty(file)) throw new Exception("Invalid file"); 25:  26: this._fileName = file; this._separator = seperator; 27: } 28:  29: /// <summary> 30: /// Should be called once, before using the object; 31: /// </summary> 32: /// <param name="nColumn">Column to be indexed</param> 33: /// <returns>Chained object</returns> 34: public CsvParser PerformIndexing(int nColumn) 35: { 36: using (StreamReader reader = new StreamReader(_fileName)) 37: { 38: string previousVal = string.Empty; string currentVal = string.Empty; 39: int nStart = 0; 40: int nEnd = 0; 41: int nRowCounter = 0; 42:  43: do 44: { 45: currentVal = reader.ReadLine().Split(_separator)[nColumn]; 46:  47: if (previousVal != currentVal) 48: { 49: if (!string.IsNullOrEmpty(previousVal)) 50: { 51: nEnd = nRowCounter; 52: _lstIndex.Add(previousVal, new Bounds(nStart, nEnd)); //Add previous value 53: nStart = nEnd + 1;//next line 54: } 55:  56: previousVal = currentVal; 57: } 58:  59:  60: nRowCounter++;//next line 61: } while (!reader.EndOfStream); 62: } 63:  64: System.Diagnostics.Trace.WriteLine(string.Format("Done. Total indexed {0}.", _lstIndex.Count)); 65: return this; 66: } 67:  68: /// <summary> 69: /// Select rows where given customer id 70: /// </summary> 71: /// <param name="CustomerID">Customer id predicate</param> 72: /// <returns></returns> 73: internal CsvParser Select(string CustomerID) 74: { 75: using (StreamReader reader = new StreamReader(_fileName)) 76: { 77: //1. Get location from index; also get the next index id so that we know where to stop. 78: //2. Jump to that position 79: //3. Start fetching 80:  81: Bounds bounds = _lstIndex[CustomerID]; 82:  83: int nRowCounter = 0; 84: while (!reader.EndOfStream || nRowCounter == bounds.End) 85: { 86: if (nRowCounter >= bounds.Start) 87: _Rows.Add(reader.ReadLine()); 88:  89: nRowCounter++; 90:  91: if (nRowCounter > bounds.End) break; 92: } 93: } 94:  95: return this; 96: } 97:  98: /// <summary> 99: /// Binary search 100: /// </summary> 101: /// <param name="data"></param> 102: /// <param name="key"></param> 103: /// <param name="left"></param> 104: /// <param name="right"></param> 105: /// <returns></returns> 106: [Obsolete("Unused", true)] 107: internal static int Search(string[] data, string key, int left, int right) 108: { 109: if (left <= right) 110: { 111: int middle = (left + right) / 2; 112: if (key == data[middle]) 113: return middle; 114: else if (!key.Equals(data[middle])) 115: return Search(data, key, left, middle - 1); 116: else 117: return Search(data, key, middle + 1, right); 118: } 119: return -1; 120: } 121:  122: /// <summary> 123: /// Provide SUM aggregate function 124: /// </summary> 125: /// <param name="nColumnID">by column</param> 126: /// <returns>Chained object</returns> 127: internal CsvParser Sum(int nColumnID) 128: { 129: var result = from theRow in _Rows 130: let rowItems = theRow.Split(_separator) 131:  132: group theRow by new 133: { 134: countryCode = rowItems[(int)CsvColumns.Col2_CountryCode], 135: dialCode = rowItems[(int)CsvColumns.Col3_DialCode] 136: } into g 137:  138: select new 139: { 140: CountryCode = g.Key.countryCode, 141: DialCode = g.Key.dialCode, 142: TotalDurationOfCall = g.Sum(p => p[(int)CsvColumns.CallDuration]), 143: selectedRows = g 144: }; 145:  146: Result = result.ToList(); 147:  148: return this; 149: } 150:  151: #region IDisposable Members 152: public void Dispose() { } 153: #endregion 154:  155:  156: } Btw, far more interesting code would have been the following implementation: parser .Select(Col1, Col2, Col3) .Where(Col1,"AMANTEL") .Sum(Col3); Let me know if you can help me with that (0: Note that, I have not applied bisection search, yet; but the method is there. SOLUTION 3: (Use TextFieldParser class) Checkout this solution, but its a VB turned into C# solution. Let me know if you enjoy? 1: using (var parser = 2: new TextFieldParser(@"c:\CustomerData.CSV") 3: { 4: TextFieldType = FieldType.Delimited, 5: Delimiters = new[] { "," } 6: }) 7: { 8: while (!parser.EndOfData) 9: { 10: string[] fields; 11: fields = parser.ReadFields(); 12: //Do something with it! 13: } 14: } SOLUTION 4: (Using LINQ to CSV) Here is how. SOLUTION 5: (Use XmlCSVReader, convert CSV to XML and use XPath to query the data) How so? Here is the method. SOLUTION 6: (Load .CSV in a database and use SELECT query to get result) See Importing CSV Data and saving it in database; I hope you get the idea; ping me if you did not. Another, just as interesting A Fast CSV Reader is also there; this is interesting because it has benchmarks. SOLUTION 7 (Bonus): (Use Text Driver with DSN) Just to retrieve data, quick and easy. 1: OdbcConnection conn = new OdbcConnection("DSN=CustomerData.csv"); 2: conn.Open(); 3: OdbcCommand foo = new OdbcCommand(@"SELECT * FROM [CustomerData.csv]", conn); 4: IDataReader dr = foo.ExecuteReader(); 5: while (dr.Read()) 6: { 7: List<string> data = new List<string>(); 8: int cols = dr.GetSchemaTable().Rows.Count; 9: for (int i = 0; i < cols; i++) 10: { 11: Console.WriteLine(string.Format("Col:{0}", dr[i].ToString())); 12: } 13: } Happy parsing! 1 comment:
__label__pos
0.999916
2.2.4. Funciones Definidas por el Usuario Un programa grande suele dividirse en una serie de pequeñas formas o funciones de usuario más fáciles de implementar y depurar. Las mismas se componen a partir de llamadas a las funciones primitivas. Estas llamadas tendrán la forma de listas que podrán anidarse unas dentro de otras de acuerdo a lo que requiera la complejidad de la manipulación que quiera realizarse de los datos aportados como argumentos. Para la definición de funciones de usuario normalmente utilizaremos la forma especial DEFUN. Otra manera de representar funciones de usuario son las expresiones LAMBDA. El estudio de su relación con DEFUN contribuirá a una mejor comprensión del proceso. La carga de las funciones de usuario guardadas en ficheros se realiza mediante la función LOAD. Un fichero en que se guarda un programa LISP contiene las distintas formas o funciones de usuario, una a continuación de la otra, terminando por la función que debe invocarse para iniciar la ejecución del programa. Esto se debe a que la función LOAD imprimirá en pantalla el nombre de la última forma evaluada. El nombre de esta función inicial se suele comenzar con los caracteres "C:" lo que indica al sistema que dicha función de usuario debe tratarse como si fuera un comando nativo de AutoCAD, en el sentido de que pueda invocarse tecleando el nombre (sin el prefijo "C:") sin encerrarlo entre paréntesis. Una función de este tipo no admite argumentos en su lista de parámetros, aunque sí la declaración de variables locales.
__label__pos
0.587554
As atividades são fundamentais e componentes do desenvolvimento dos andróides. Uma atividade encapsula uma tela com a qual o usuário interage. As atividades normalmente conterão componentes com os quais o usuário deverá interagir. Estes podem ser botões, listas, textos de edição, etc. A atividade, entretanto, tem seu próprio ciclo de vida e você pode ouvir os eventos emitidos pela atividade através dos métodos do ciclo de vida. Neste tutorial aprendemos estes métodos de ciclo de vida praticamente escrevendo código que faz algo quando um evento deste tipo é levantado. (a). Criar um aplicativo que lista os métodos do ciclo de vida da atividade em Kotlin Neste exemplo, você aprenderá a interação básica com estes métodos. Mostramos uma simples mensagem de brinde quando um evento deste tipo é levantado. Usamos androide studio e kotlin Etapa 1: Dependências Não são necessárias dependências para este projeto. Passo 2: Código Kotlin Comece criando um arquivo chamado MaiActivity.kt. MainActivity.kt**. Em seguida, adicionar as importações: import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import java.lang.StringBuilder Em seguida, estender a AppCompatActivity: class MainActivity : AppCompatActivity() { // O primeiro método de ciclo de vida que anulamos é o onCreate(). Isto é levantado quando a atividade é criada pela primeira vez. Insuflaremos nosso layout xml aqui. Anexe algum texto ao nosso textbuilder. Em seguida, mostrar o texto em uma visualização de texto. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sb.append("\n onCreate Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onCreate Called") } Em seguida, anulamos nosso onStart(). Isto é levantado quando a atividade é iniciada e se torna visível para uso: override fun onStart() { super.onStart() sb.append("\n onStart Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onStart Called") } E assim por diante. Aqui está o código completo: package info.camposha.activitylifecycle import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.* import java.lang.StringBuilder class MainActivity : AppCompatActivity() { val sb: StringBuilder = StringBuilder() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sb.append("\n onCreate Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onCreate Called") } override fun onStart() { super.onStart() sb.append("\n onStart Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onStart Called") } override fun onResume() { super.onResume() sb.append("\n onResume Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onResume Called") } override fun onPause() { super.onPause() sb.append("\n onPause Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onPause Called") } override fun onStop() { super.onStop() sb.append("\n onStop Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onStop Called") } override fun onDestroy() { super.onDestroy() sb.append("\n onDestroy Called") tv.text = sb.toString() Log.d("ACTIVITY_LIFECYCLE", "onDestroy Called") } } Passo 3: Layouts **activity_main.xml*** O principal sobre nosso layout de atividade principal é que teremos uma visão de texto que mostrará os métodos do ciclo de vida à medida que eles forem sendo levantados: <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="match_parent" android:text="" android:textAppearance="@style/TextAppearance.AppCompat.Medium" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Passo 4: Correr Executar o projeto. Mudança de configuração da tela Nesta peça, analisamos soluções andróides relacionadas a mudanças de configuração no dispositivo andróide. Aqui está uma nota simples sobre como lidar com as mudanças de configuração de acordo com a documentação oficial do androide: Algumas configurações do dispositivo podem mudar durante a execução (como orientação da tela, disponibilidade do teclado e quando o usuário habilita [modo multijanela] (https://developer.android.com/guide/topics/ui/multi-window)). Quando tal mudança ocorre, o Android reinicia a execução Activity ( onDestroy() é chamado, seguido por onCreate()). O comportamento de reinício é projetado para ajudar sua aplicação a se adaptar a novas configurações, recarregando automaticamente sua aplicação com recursos alternativos que combinam com a nova configuração do dispositivo. Para lidar adequadamente com um reinício, é importante que sua atividade restaure seu estado anterior. Você pode utilizar uma combinação de objetos onSaveInstanceState(), ViewModel, e armazenamento persistente para salvar e restaurar o estado da IU de sua atividade durante as mudanças de configuração. Leia mais sobre isso aqui. Como você ouve as mudanças de configuração no andróide? Passo 1 - Especifique a propriedade configChanges no manifesto do andróide Assim: <activity android:name=".MyActivity" android:configChanges="orientation|screenSize|screenLayout|keyboardHidden" android:label="@string/app_name"> O código declara uma atividade que trata tanto de mudanças de orientação da tela quanto de disponibilidade do teclado. • O valor "orientação" impede que se reinicie quando a orientação da tela muda. • O valor "screenSize" também impede que se reinicie quando a orientação muda, mas somente para o Android 3.2 (nível API 13) e acima. • O valor "screenLayout" é necessário para detectar mudanças que podem ser acionadas por dispositivos como telefones dobráveis e Chromebooks conversíveis. • O valor "keyboardHidden" impede que se reinicie quando a disponibilidade do teclado muda. Passo 2: Substituir emConfiguraçãoMétodo modificado Assim: @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); int newOrientation = newConfig.orientation; if (newOrientation == Configuration.ORIENTATION_LANDSCAPE) { // show("Landscape"); } else if (newOrientation == Configuration.ORIENTATION_PORTRAIT){ // show("Portrait"); } } Ou você pode usar uma declaração de interruptor: int orientation=newConfig.orientation; switch(orientation) { case Configuration.ORIENTATION_LANDSCAPE: //to do something break; case Configuration.ORIENTATION_PORTRAIT: //to do something break; } Em Kotlin: override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) // Checks the orientation of the screen if (newConfig.orientation === Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show() } else if (newConfig.orientation === Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show() } } Note que antes de escrever seu código de implementação você precisa adicionar super.onConfigurationChanged(newConfig); ou então uma exceção poderá ser levantada. Observações O onConfigurationCalled() não pode ser chamado se você **1.definir layout para paisagem em XML*** android:screenOrientation="landscape" **2. Conjunto de convitesOrientação solicitada manualmente*** setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 3. Você tem tanto android:screenOrientation como android:configChanges especificados. Exemplo - Como lidar com mudanças na orientação da tela Vamos criar um exemplo simples que irá observar mudanças de configuração em uma atividade andróide e mostrar uma mensagem de brinde com base no fato de a tela ser girada retrato ou paisagem. Passo 1- Criar layout Adicione o seguinte código em seu layout xml: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout> Passo 2: MainActivity.java Em seguida, adicione o seguinte código em sua atividade principal: package com.example.screenorientation; import android.os.Bundle; import android.app.Activity; import android.content.res.Configuration; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); onConfigurationChanged(new Configuration()); } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT) { Toast.makeText(getApplicationContext(), "portrait", Toast.LENGTH_SHORT).show(); System.out.println("portrait"); } else if (getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE) { Toast.makeText(getApplicationContext(), "landscape", Toast.LENGTH_SHORT).show(); System.out.println("landscape"); } else { Toast.makeText(getApplicationContext(), "none", Toast.LENGTH_SHORT).show(); System.out.println("none"); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } É isso aí. Categorized in:
__label__pos
0.937917
C# API differences to GDScript This is a (incomplete) list of API differences between C# and GDScript. General differences As explained in the C# basics, C# generally uses PascalCase instead of the snake_case used in GDScript and C++. Global scope Global functions and some constants had to be moved to classes, since C# does not allow declaring them in namespaces. Most global constants were moved to their own enums. Costanti Global constants were moved to their own enums. For example, ERR_* constants were moved to the Error enum. Special cases: GDScript C# SPKEY GD.SpKey TYPE_* Variant.Type enum OP_* Variant.Operator enum Funzioni Math Math global functions, like abs, acos, asin, atan and atan2, are located under Mathf as Abs, Acos, Asin, Atan and Atan2. The PI constant can be found as Mathf.Pi. Funzioni Random Random global functions, like rand_range and rand_seed, are located under GD. Example: GD.RandRange and GD.RandSeed. Altre Funzioni Many other global functions like print and var2str are located under GD. Example: GD.Print and GD.Var2Str. Exceptions: GDScript C# weakref(obj) Object.WeakRef(obj) is_instance_valid(obj) Object.IsInstanceValid(obj) Tips Sometimes it can be useful to use the using static directive. This directive allows to access the members and nested types of a class without specifying the class name. Esempio: using static Godot.GD; public class Test { static Test() { Print("Hello"); // Instead of GD.Print("Hello"); } } Export keyword Use the [Export] attribute instead of the GDScript export keyword. This attribute can also be provided with optional PropertyHint and hintString parameters. Default values can be set by assigning a value. Esempio: using Godot; public class MyNode : Node { [Export] private NodePath _nodePath; [Export] private string _name = "default"; [Export(PropertyHint.Range, "0,100000,1000,or_greater")] private int _income; [Export(PropertyHint.File, "*.png,*.jpg")] private string _icon; } Signal keyword Use the [Signal] attribute to declare a signal instead of the GDScript signal keyword. This attribute should be used on a delegate, whose name signature will be used to define the signal. [Signal] delegate void MySignal(string willSendsAString); Vedi anche: Segnali in C#. onready keyword GDScript has the ability to defer the initialization of a member variable until the ready function is called with onready (cf. onready keyword). For example: onready var my_label = get_node("MyLabel") However C# does not have this ability. To achieve the same effect you need to do this. private Label _myLabel; public override void _Ready() { _myLabel = GetNode<Label>("MyLabel"); } Singletons Singletons are available as static classes rather than using the singleton pattern. This is to make code less verbose than it would be with an Instance property. Esempio: Input.IsActionPressed("ui_down") However, in some very rare cases this is not enough. For example, you may want to access a member from the base class Godot.Object, like Connect. For such use cases we provide a static property named Singleton that returns the singleton instance. The type of this instance is Godot.Object. Esempio: Input.Singleton.Connect("joy_connection_changed", this, nameof(Input_JoyConnectionChanged)); String Use System.String (string). Most of Godot's String methods are provided by the StringExtensions class as extension methods. Esempio: string upper = "I LIKE SALAD FORKS"; string lower = upper.ToLower(); Tuttavia, ci sono alcune differenze: • erase: Strings are immutable in C#, so we cannot modify the string passed to the extension method. For this reason, Erase was added as an extension method of StringBuilder instead of string. Alternatively, you can use string.Remove. • IsSubsequenceOf/IsSubsequenceOfi: An additional method is provided, which is an overload of IsSubsequenceOf, allowing you to explicitly specify case sensitivity: str.IsSubsequenceOf("ok"); // Case sensitive str.IsSubsequenceOf("ok", true); // Case sensitive str.IsSubsequenceOfi("ok"); // Case insensitive str.IsSubsequenceOf("ok", false); // Case insensitive • Match/Matchn/ExprMatch: An additional method is provided besides Match and Matchn, which allows you to explicitly specify case sensitivity: str.Match("*.txt"); // Case sensitive str.ExprMatch("*.txt", true); // Case sensitive str.Matchn("*.txt"); // Case insensitive str.ExprMatch("*.txt", false); // Case insensitive Base Structs cannot have parameterless constructors in C#. Therefore, new Basis() initializes all primitive members to their default value. Use Basis.Identity for the equivalent of Basis() in GDScript and C++. The following method was converted to a property with a different name: GDScript C# get_scale() Scale Transform2D Structs cannot have parameterless constructors in C#. Therefore, new Transform2D() initializes all primitive members to their default value. Please use Transform2D.Identity for the equivalent of Transform2D() in GDScript and C++. The following methods were converted to properties with their respective names changed: GDScript C# get_rotation() Rotation get_scale() Scale Piano The following method was converted to a property with a slightly different name: GDScript C# center() Center Rect2 The following field was converted to a property with a slightly different name: GDScript C# end End The following method was converted to a property with a different name: GDScript C# get_area() Area Quat Structs cannot have parameterless constructors in C#. Therefore, new Quat() initializes all primitive members to their default value. Please use Quat.Identity for the equivalent of Quat() in GDScript and C++. The following methods were converted to a property with a different name: GDScript C# length() Length length_squared() LengthSquared Array This is temporary. PoolArrays will need their own types to be used the way they are meant to. GDScript C# Array Godot.Collections.Array PoolIntArray int[] PoolByteArray byte[] PoolFloatArray float[] PoolStringArray String[] PoolColorArray Color[] PoolVector2Array Vector2[] PoolVector3Array Vector3[] Godot.Collections.Array<T> is a type-safe wrapper around Godot.Collections.Array. Use the Godot.Collections.Array<T>(Godot.Collections.Array) constructor to create one. Dizionario Use Godot.Collections.Dictionary. Godot.Collections.Dictionary<T> is a type-safe wrapper around Godot.Collections.Dictionary. Use the Godot.Collections.Dictionary<T>(Godot.Collections.Dictionary) constructor to create one. Variant System.Object (object) is used instead of Variant. Communicating with other scripting languages This is explained extensively in Cross-language scripting. Yield Something similar to GDScript's yield with a single parameter can be achieved with C#'s yield keyword. The equivalent of yield on signal can be achieved with async/await and Godot.Object.ToSignal. Esempio: await ToSignal(timer, "timeout"); GD.Print("After timeout"); Other differences preload, as it works in GDScript, is not available in C#. Use GD.Load or ResourceLoader.Load instead. Other differences: GDScript C# Color8 Color.Color8 is_inf float.IsInfinity is_nan float.IsNaN dict2inst TODO inst2dict TODO
__label__pos
0.500617
September 20, 2024 LIQ UI Insert, Update, Delete in Entity Framework ADO.NET Entity Framework is an powerful tools to developed applications. This article explains basic CRUD operations in Entity Framework. This tutorial will help you to insert, update, delete, select, search data into SQL Server by using ADO.NET Entity Framework. For this we will use Students table. We will save Student ID, Name, Address, and Phone number of a Student in Students table. This can be summarized as like: • Table Creations • Web Project Creations • User Interface (UI) Design • Creation of Entity Data Model • Select Operation • Insert Operation • Update Operation • Delete Operation • Search Operation Table Creations Create a Database in the SQL Server named “TestDB”. Create a “Students” table in the database. We can use the following SQL scripts: CREATE TABLE [dbo].[Students]( [StudentID] [int] IDENTITY(1,1) NOT NULL, [StudentName] [nvarchar](150) NULL, [Address] [nvarchar](200) NULL, [Phone] [nvarchar](50) NULL, CONSTRAINT [PK_member] PRIMARY KEY CLUSTERED ( [StudentID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] Web API Project Creations We can create web or desktop application. Let’s start with ASP.Net web application. In order to implement this we need to install Visual Studio 2010/2012. All are available on the internet. Here Visual Studio 2010 is used. All the steps are given bellow: Open Visual Studio and click “New Project” or File -> New Project. In the New Project dialog box: Open the Visual C# templates Select the template ASP.NET Web Application Set the project name to “MyEF” Set the disk location to something like C:\TestProject Click OK A default ASP.NET web application project will be created. User Interface (UI) Creations We need to create a user interface or UI as like the sample image which is given bellow. We can use the following ASP.NET code to design required UI. LIQ UI <table> <tr> <td style="width: 120px"> Student ID</td> <td> <asp:TextBox ID="txtStudentID" runat="server" Enabled="False"></asp:TextBox> </td> </tr> <tr> <td style="width: 120px"> Name</td> <td> <asp:TextBox ID="txtName" runat="server" Width="250px"></asp:TextBox> </td> </tr> <tr> <td> Address</td> <td> <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine" Width="250px"></asp:TextBox> </td> </tr> <tr> <td> Phone</td> <td> <asp:TextBox ID="txtPhone" runat="server"></asp:TextBox> </td> </tr> <tr> <td> &nbsp;</td> <td> &nbsp;</td> </tr> <tr> <td> &nbsp;</td> <td> <asp:Button ID="btnAdd" runat="server" Text="Add" Width="80px" onclick="btnAdd_Click" /> <asp:Button ID="btnEdit" runat="server" onclick="btnEdit_Click" Text="Edit" Width="80px" /> <asp:Button ID="btnDelete" runat="server" onclick="btnDelete_Click" Text="Delete" Width="80px" /> </td> </tr> <tr> <td> &nbsp;</td> <td> &nbsp;</td> </tr> <tr> <td> &nbsp;</td> <td> <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> <asp:Button ID="btnSearch" runat="server" onclick="btnSearch_Click" Text="Search" Width="80px" /> </td> </tr> </table> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="600px" AutoGenerateSelectButton="True" onselectedindexchanged="GridView1_SelectedIndexChanged"> <Columns> <asp:BoundField DataField="StudentID" HeaderText="Student ID" /> <asp:BoundField DataField="StudentName" HeaderText="Name" /> <asp:BoundField DataField="Address" HeaderText="Address" /> <asp:BoundField DataField="Phone" HeaderText="Phone" /> </Columns> </asp:GridView> Here some TextBox & Button and one GridView controls are used. Creation of Entity Data Model Create an ADO.NET Entity Data Model in your project by using Entity Data Model Wizard. Select Operation Create an object of Data Model and Student class in the code behind page. TestDBEntities db = new TestDBEntities(); Student oStudent = new Student(); Write the following code in the code behind page. protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGridView(); } } public void BindGridView() { var result = from S in db.Students select new { S.StudentID, S.StudentName, S.Address, S.Phone }; GridView1.DataSource = result; GridView1.DataBind(); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { txtStudentID.Text = GridView1.SelectedRow.Cells[1].Text; txtName.Text = GridView1.SelectedRow.Cells[2].Text; txtAddress.Text = GridView1.SelectedRow.Cells[3].Text; txtPhone.Text = GridView1.SelectedRow.Cells[4].Text; } Insert Operation Write the following code under the insert button (btnAdd) click event. oStudent.StudentName = txtName.Text; oStudent.Address = txtAddress.Text; oStudent.Phone = txtPhone.Text; db.Students.AddObject(oStudent); db.SaveChanges(); BindGridView(); Update Operation Write the following code under the edit button (btnEdit) click event. oStudent.StudentID=int.Parse((txtStudentID.Text)); var result = (from S in db.Students where S.StudentID ==oStudent.StudentID select S).Single(); result.StudentName = txtName.Text; result.Address = txtAddress.Text; result.Phone = txtPhone.Text; db.Students.ApplyCurrentValues(result); db.SaveChanges(); BindGridView(); Select one student form the GridView, change the data and click edit button. Delete Operation Write the following code under the delete button (btnDelete) click event. oStudent.StudentID = int.Parse((txtStudentID.Text)); var result = (from S in db.Students where S.StudentID == oStudent.StudentID select S).Single(); db.Students.DeleteObject(result); db.SaveChanges(); BindGridView(); Select one student form the GridView and click delete button. Search Operation Write the following code under the search button (btnSearch) click event. oStudent.StudentID = int.Parse((txtSearch.Text)); var result = from S in db.Students where S.StudentID == oStudent.StudentID select new { S.StudentID, S.StudentName, S.Address, S.Phone }; GridView1.DataSource = result; GridView1.DataBind(); Type any student ID in the search TextBox and click search button. Rashedul Alam I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others. View all posts by Rashedul Alam → One thought on “Insert, Update, Delete in Entity Framework Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.989593
A tiger with wings added subdomain optimization 2. 1. domain name like the one that search keywords "notebook", a total of 8 sites on the home page screenshot, only 2 of which is the top-level domain name website, the rest are all sub domain name website. So you can see the importance of straightforward sub domain name right? So I said that the sub domain optimization well, equivalent to the site wings. To optimize the sub domain there are many ways, the following I will briefly 3 main key points. to search engine to quickly search, you need to set the appropriate, people commonly used words. In the 6 sub domain name of the website, we see his website with the words "computer". That is to say, when sub domain optimization, we should not only pay attention to the key words Chinese, also want to pay attention to the English English, after all, is the international language, is the most widely used language in the world, through the optimization, can effectively improve the site click rate and flow. have a lot of time, promotion and site optimization of electronic products are inextricably linked. It can be said that the website optimization is an essential part of every web site. Many people will from time to time to optimize the website, but more often they are Shanghai dragon. Today I want another optimization method of sub domain optimization to introduce to you, the good subdomain can make your website a tiger with wings added optimization. The content of the website like this screenshot, there are obvious content division, type, brand, price, screen size, cards and so on the choice to the user in the top-level domain experience.   Optimization of is basically two level optimization as long as it is outside the station optimization and key station optimization is Links this one. In Links exchange, we must pay attention to the relationship between. Avoid irrelevant answer. 000. sub domain, is the site of the two level domain name. Many webmaster in optimize only thought of website top-level domain optimization, completely ignoring the potential role of sub domain. Below I will use a picture about the role and function of sub domain. 3. Links. webmaster friends all know that the site is the essence of the content of the website. If the content of wonderful attractive, intangibles locked many long-term users, the benefits of this nature is self-evident. The sub domain optimization in different sub domain lies, must also have the corresponding columns, groups, discussion and so on, is to give users a top-level domain like user experience. This was the establishment of the webmaster friends may be a bit difficult, but if you want to be the site of long-term development, this is an essential step in. This requires patience and diligence, need a lot of time and energy input, see the webmaster friends are willing to work hard in this area.
__label__pos
0.503442
OmniSciDB  a667adc9c8  All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages MapDRelJsonWriter.java Go to the documentation of this file. 1 /* 2  * Copyright 2017 MapD Technologies, Inc. 3  * 4  * Licensed under the Apache License, Version 2.0 (the "License"); 5  * you may not use this file except in compliance with the License. 6  * You may obtain a copy of the License at 7  * 8  * http://www.apache.org/licenses/LICENSE-2.0 9  * 10  * Unless required by applicable law or agreed to in writing, software 11  * distributed under the License is distributed on an "AS IS" BASIS, 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13  * See the License for the specific language governing permissions and 14  * limitations under the License. 15  */ 16  17 package org.apache.calcite.rel.externalize; 18  19 import com.google.common.collect.ImmutableList; 20  21 import org.apache.calcite.rel.RelNode; 22 import org.apache.calcite.rel.RelWriter; 23 import org.apache.calcite.rel.core.TableScan; 24 import org.apache.calcite.rel.hint.RelHint; 25 import org.apache.calcite.rel.logical.*; 26 import org.apache.calcite.rel.type.RelDataType; 27 import org.apache.calcite.sql.SqlExplainLevel; 29 import org.apache.calcite.util.Pair; 30  31 import java.util.*; 32 import java.util.stream.Collectors; 33  39 public class MapDRelJsonWriter implements RelWriter { 40  // ~ Instance fields ---------------------------------------------------------- 41  43  private final MapDRelJson relJson; 44  private final Map<RelNode, String> relIdMap = new IdentityHashMap<RelNode, String>(); 45  private final List<Object> relList; 46  private final List<Pair<String, Object>> values = new ArrayList<Pair<String, Object>>(); 47  private String previousId; 48  49  // ~ Constructors ------------------------------------------------------------- 50  51  public MapDRelJsonWriter() { 53  relList = jsonBuilder.list(); 55  } 56  57  // ~ Methods ------------------------------------------------------------------ 58  59  protected void explain_(RelNode rel, List<Pair<String, Object>> values) { 60  final Map<String, Object> map = jsonBuilder.map(); 61  62  map.put("id", null); // ensure that id is the first attribute 63  map.put("relOp", relJson.classToTypeName(rel.getClass())); 64  if (rel instanceof TableScan) { 65  RelDataType row_type = ((TableScan) rel).getTable().getRowType(); 66  List<String> field_names = row_type.getFieldNames(); 67  map.put("fieldNames", field_names); 68  } 69  if (rel instanceof LogicalAggregate) { 70  map.put("fields", rel.getRowType().getFieldNames()); 71  } 72  if (rel instanceof LogicalTableModify) { 73  // FIX-ME: What goes here? 74  } 75  76  // handle hints 77  if (deliverHints(rel)) { 78  map.put("hints", explainHints(rel)); 79  } 80  81  for (Pair<String, Object> value : values) { 82  if (value.right instanceof RelNode) { 83  continue; 84  } 85  put(map, value.left, value.right); 86  } 87  // omit 'inputs: ["3"]' if "3" is the preceding rel 88  final List<Object> list = explainInputs(rel.getInputs()); 89  if (list.size() != 1 || !list.get(0).equals(previousId)) { 90  map.put("inputs", list); 91  } 92  93  final String id = Integer.toString(relIdMap.size()); 94  relIdMap.put(rel, id); 95  map.put("id", id); 96  97  relList.add(map); 98  previousId = id; 99  } 100  101  private void put(Map<String, Object> map, String name, Object value) { 102  map.put(name, relJson.toJson(value)); 103  } 104  105  private List<Object> explainInputs(List<RelNode> inputs) { 106  final List<Object> list = jsonBuilder.list(); 107  for (RelNode input : inputs) { 108  String id = relIdMap.get(input); 109  if (id == null) { 110  input.explain(this); 111  id = previousId; 112  } 113  list.add(id); 114  } 115  return list; 116  } 117  118  private boolean deliverHints(RelNode rel) { 119  if (rel instanceof LogicalTableScan) { 120  LogicalTableScan node = (LogicalTableScan) rel; 121  if (!node.getHints().isEmpty()) { 122  return true; 123  } else { 124  return false; 125  } 126  } else if (rel instanceof LogicalAggregate) { 127  LogicalAggregate node = (LogicalAggregate) rel; 128  if (!node.getHints().isEmpty()) { 129  return true; 130  } else { 131  return false; 132  } 133  } else if (rel instanceof LogicalJoin) { 134  LogicalJoin node = (LogicalJoin) rel; 135  if (!node.getHints().isEmpty()) { 136  return true; 137  } else { 138  return false; 139  } 140  } else if (rel instanceof LogicalProject) { 141  LogicalProject node = (LogicalProject) rel; 142  if (!node.getHints().isEmpty()) { 143  return true; 144  } else { 145  return false; 146  } 147  } else if (rel instanceof LogicalCalc) { 148  LogicalCalc node = (LogicalCalc) rel; 149  if (!node.getHints().isEmpty()) { 150  return true; 151  } else { 152  return false; 153  } 154  } 155  return false; 156  } 157  158  private String explainHints(RelNode rel) { 159  List<String> explained = new ArrayList<>(); 160  if (rel instanceof LogicalTableScan) { 161  LogicalTableScan node = (LogicalTableScan) rel; 162  node.getHints().stream().forEach(s -> explained.add(s.toString().toLowerCase())); 163  } else if (rel instanceof LogicalAggregate) { 164  LogicalAggregate node = (LogicalAggregate) rel; 165  node.getHints().stream().forEach(s -> explained.add(s.toString().toLowerCase())); 166  } else if (rel instanceof LogicalJoin) { 167  LogicalJoin node = (LogicalJoin) rel; 168  node.getHints().stream().forEach(s -> explained.add(s.toString().toLowerCase())); 169  } else if (rel instanceof LogicalProject) { 170  LogicalProject node = (LogicalProject) rel; 171  node.getHints().stream().forEach(s -> explained.add(s.toString().toLowerCase())); 172  } else if (rel instanceof LogicalCalc) { 173  LogicalCalc node = (LogicalCalc) rel; 174  node.getHints().stream().forEach(s -> explained.add(s.toString().toLowerCase())); 175  } 176  return explained.stream().collect(Collectors.joining("|")); 177  } 178  179  public final void explain(RelNode rel, List<Pair<String, Object>> valueList) { 180  explain_(rel, valueList); 181  } 182  183  public SqlExplainLevel getDetailLevel() { 184  return SqlExplainLevel.ALL_ATTRIBUTES; 185  } 186  187  public RelWriter input(String term, RelNode input) { 188  return this; 189  } 190  191  public RelWriter item(String term, Object value) { 192  values.add(Pair.of(term, value)); 193  return this; 194  } 195  196  private List<Object> getList(List<Pair<String, Object>> values, String tag) { 197  for (Pair<String, Object> value : values) { 198  if (value.left.equals(tag)) { 199  // noinspection unchecked 200  return (List<Object>) value.right; 201  } 202  } 203  final List<Object> list = new ArrayList<Object>(); 204  values.add(Pair.of(tag, (Object) list)); 205  return list; 206  } 207  208  public RelWriter itemIf(String term, Object value, boolean condition) { 209  if (condition) { 210  item(term, value); 211  } 212  return this; 213  } 214  215  public RelWriter done(RelNode node) { 216  final List<Pair<String, Object>> valuesCopy = ImmutableList.copyOf(values); 217  values.clear(); 218  explain_(node, valuesCopy); 219  return this; 220  } 221  222  public boolean nest() { 223  return true; 224  } 225  230  public String asString() { 231  return jsonBuilder.toJsonString(asJsonMap()); 232  } 233  234  public Map<String, Object> asJsonMap() { 235  final Map<String, Object> map = jsonBuilder.map(); 236  map.put("rels", relList); 237  return map; 238  } 239 } 240  241 // End RelJsonWriter.java void explain_(RelNode rel, List< Pair< String, Object >> values) string name Definition: setup.in.py:62 List< Object > getList(List< Pair< String, Object >> values, String tag) List< Object > explainInputs(List< RelNode > inputs) final void explain(RelNode rel, List< Pair< String, Object >> valueList) RelWriter itemIf(String term, Object value, boolean condition) void put(Map< String, Object > map, String name, Object value)
__label__pos
0.997559
Networked Physics (2004) Network a physics simulation using the same techniques as first person shooters Posted by Glenn Fiedler on Saturday, September 4, 2004 Introduction Hi, I’m Glenn Fiedler and welcome to the final article in in Game Physics. In the previous article we discussed how to use spring-like forces to model basic collision response, joints and motors. Now we’re going to discuss how to network a physics simulation. Networking a physics simulation is the holy grail of multiplayer gaming and the massive popularity of first person shooters on the PC is a testament to the just how immersive a networked physics simulation can be. In this article I will show you how apply the key networking techniques from first person shooters to network your own physics simulation. First Person Shooters First person shooter physics are usually very simple. The world is static and players are limited to running around and jumping and shooting. Because of cheating, first person shooters typically operate on a client-server model where the server is authoritative over physics. This means that the true physics simulation runs on the server and the clients display an approximation of the server physics to the player. The problem then is how to allow each client to control his own character while displaying a reasonable approximation of the motion of the other players. In order to do this elegantly and simply, we structure the physics simulation as follows: 1. Character physics are completely driven from input data 2. Physics state is known and can be fully encapsulated in a state structure 3. The physics simulation is reasonably deterministic given the same initial state and inputs To do this we need to gather all the user input that drives the physics simulation into a single structure and the state representing each player character into another. Here is an example from a simple run and jump shooter: struct Input { bool left; bool right; bool forward; bool back; bool jump; }; struct State { Vector position; Vector velocity; }; Next we need to make sure that the simulation gives the same result given the same initial state and inputs over time. Or at least, that the results are as close as possible. I’m not talking about determinism to the level of floating point accuracy and rounding modes, just a reasonable, 1-2 second prediction giving basically the same result. Network Fundamentals I will briefly discuss actually networking issues in this section before moving on to the important information of what to send over the pipe. It is after all just a pipe after all, networking is nothing special right? Beware! Ignorance of how the pipe works will really bite you. Here are the two networking fundamentals that you absolutely need to know: Number one. If your network programmer is any good at all he will use UDP, which is an unreliable data protocol, and build some sort of application specific networking layer on top of this. The important thing that you as the physics programmer need to know is that you absolutely must design your physics communication over the network so that you can receive the most recent input and state without waiting for lost packets to be resent. This is important because otherwise your physics simulation will stall out under bad networking conditions. Two. You will be very limited in what can be sent across the network due to bandwidth limitations. Compression is a fact of life when sending data across the network. As physics programmer you need to be very careful what data is compressed and how it is done. For the sake of determinism, some data must not be compressed, while other data is safe. Any data that is compressed in a lossy fashion should have the same quantization applied locally where possible, so that the result is the same on both machines. Bottom line you’ll need to be involved in this compression in order to make it as efficient as possible without breaking your simulation. Physics Runs On The Server The fundamental primitive we will use when sending data between the client and the server is an unreliable data block, or if you prefer, an unreliable non-blocking remote procedure call (rpc). Non-blocking means that the client sends the rpc to the server then continues immediately executing other code, it does not wait for the rpc to execute on the server! Unreliable means that if you call the rpc is continuously on the the server from a client, some of these calls will not reach the server, and others will arrive in a different order than they were called. We design our communications around this primitive because it suits the transport layer (UDP). The communication between the client and the server is then structured as what I call a “stream of input” sent via repeated rpc calls. The key to making this input stream tolerant of packet loss and out of order delivery is the inclusion of a floating point time in seconds value with every input rpc sent. The server keeps track of the current time on the server and ignores any input received with a time value less than the current time. This effectively drops any input that is received out of order. Lost packets are ignored. Thinking in terms of our standard first person shooter, the input we send from client to server is the input structure that we defined earlier: struct Input { bool left; bool right; bool forward; bool back; bool jump; }; class Character { public: void processInput( double time, Input input ); }; Thats the bare minimum data required for sending a simple ground based movement plus jumping across the network. If you are going to allow your clients to shoot you’ll need to add mouse input as part of the input structure as well because weapon firing needs to be done server side. Notice how I define the rpc as a method inside an object? I assume your network programmer has a channel structure built on top of UDP, eg. some way to indicate that a certain rpc call is directed as a specific object instance on the remote machine. So how does the server process these rpc calls? It basically sits in a loop waiting for input from each of the clients. Each character object has its physics advanced ahead in time individually as input rpcs are received from the client that owns it. This means that the physics state of different client characters are slightly out of phase on the server, some clients being a little bit ahead and others a little bit behind in time. Overall however, the different client characters advance ahead roughly in sync with each other. Lets see how this rpc call is implemented in code on the server: void processInput( double time, Input input ) { if ( time < currentTime ) return; float deltaTime = currentTime - time; updatePhysics( currentTime, deltaTime, input ); } The key to the code above is that by advancing the server physics simulation for the client character is performed only as we receive input from that client. This makes sure that the simulation is tolerant of random delays and jitter when sending the input rpc across the network. Clients Approximate Physics Locally Now for the communication from the server back to the clients. This is where the bulk of the server bandwidth kicks in because the information needs to be broadcast to all the clients. What happens now is that after every physics update on the server that occurs in response to an input rpc from a client, the server broadcasts out the physics state at the end of that physics update and the current input just received from the rpc. This is sent to all clients in the form of an unreliable rpc: void clientUpdate( float time, Input input, State state ) { Vector difference = state.position - current.position; float distance = difference.length(); if ( distance > 2.0f ) current.position = state.position; else if ( distance > 0.1 ) current.position += difference * 0.1f; current.velocity = velocity; current.input = input; } What is being done here is this: if the two positions are significantly different (>2m apart) just snap to the corrected position, otherwise if the distance between the server position and the current position on the client is more than 10cms, move 10% of the distance between the current position and the correct position. Otherwise do nothing. Since server update rpcs are being broadcast continually from the server to the the clients, moving only a fraction towards the snap position has the effect of smoothing the correction out with what is called an exponentially smoothed moving average. This trades a bit of extra latency for smoothness because only moving some percent towards the snapped position means that the position will be a bit behind where it should really be. You don’t get anything for free. I recommend that you perform this smoothing for immediate quantities such as position and orientation, while directly snapping derivative quantities such as velocity, angular velocity because the effect of abruptly changing derivative quantities is not as noticeable. Of course, these are just rules of thumb. Make sure you experiment to find out what works best for your simulation. Client-Side Prediction So far we have a developed a solution for driving the physics on the server from client input, then broadcasting the physics to each of the clients so they can maintain a local approximation of the physics on the server. This works perfectly however it has one major disadvantage. Latency! When the user holds down the forward input it is only when that input makes a round trip to the server and back to the client that the client’s character starts moving forward locally. Those who remember the original Quake netcode would be familiar with this effect. The solution to this problem was discovered and first applied in the followup QuakeWorld and is called client side prediction. This technique completely eliminates movement lag for the client and has since become a standard technique used in first person shooter netcode. Client side prediction works by predicting physics ahead locally using the player’s input, simulating ahead without waiting for the server round trip. The server periodically sends corrections to the client which are required to ensure that the client stays in sync with the server physics. At all times the server is authoritative over the physics of the character so even if the client attempts to cheat all they are doing is fooling themselves locally while the server physics remains unaffected. Seeing as all game logic runs on the server according to server physics state, client side movement cheating is basically eliminated. The most complicated part of client side prediction is handling the correction from the server. This is difficult, because the corrections from the server arrive in the past due to client/server communication latency. We need to apply this correction in the past, then calculate the resulting corrected position at present time on the client. The standard technique to do this is to store a circular buffer of saved moves on the client where each move in the buffer corresponds to an input rpc call sent from the client to the server: struct Move { double time; Input input; State state; }; When the client receives a correction it looks through the saved move buffer to compare its physics state at that time with the corrected physics state sent from the server. If the two physics states differ above some threshold then the client rewinds to the corrected physics state and time and replays the stored moves starting from the corrected state in the past, the result of this re-simulation being the corrected physics state at the current time on the client. Sometimes packet loss or out of order delivery occurs and the server input differs from that stored on the client. In this case the server snaps the client to the correct position automatically via rewind and replay. This snapping is quite noticeable to the player, so we reduce it with the same smoothing technique we used above for the other player characters. This smoothing is done after recalculating the corrected position via rewind and replay. Conclusion We can easily apply the client side prediction techniques used in first person shooters to network a physics simulation, but only if there is a clear ownership of objects by clients and these object interact mostly with a static world.
__label__pos
0.840189
Configuring Bare-Metal Restore Server After you have booted your server from Bare Metal Server Live CD or PXE boot, and configured the network, you should start the server and make sure that the server has access to backup data (Disk Safe). Follow the instructions below. Starting CDP Server | Getting Access to the Disk Safe | Attaching the Disk Safe in Server's Web Interface Starting CDP Server 1. Before starting the server, you should set the username and password for the Web Interface. Execute the following command: r1soft-setup --user --pass 2. Now you can start the server by executing the following command: /etc/init.d/cdp-server start Wait 1-2 minutes for the server to initialize. Then you can access it in the browser from some other computer in the same LAN. You can safely ignore debug messages from Linux kernel shown on the console at server startup. Getting Access to the Disk Safe When you are creating a Disk Safe in CDP Standard or Advanced edition, the Web Interface recommends you to save the Disk Safe on a reliable network share, or, if it is not possible, on a secondary hard drive. Tip The second option looks more attractive from the Bare-Metal Restore point of view because in Linux booted from Live CD or via PXE it is much easier to get access to the local hard disk than to the network share. The following three (3) options are described below: Disk Safe Is on the Local Hard Drive Let's assume that the new hard disk which you will restore your server to is visible as /dev/hda and the disk with backup data (Disk Safe) is attached as /dev/hdb. Let's assume that the first disk is empty and does not contain a partition table, and the second disk contains one partition the size of the entire disk (/dev/hdb1). To get access to the Disk Safe, mount the /dev/hdb1 partition to /mnt using the following command: mount /dev/hdb1 /mnt The command should run successfully, because the kernel on Live CD supports a lot of different file systems, including Linux EXT3, EXT4, ReiserFS and Windows NTFS. Now you can proceed to attaching the Disk Safe in the server web interface (see further). Tip If you are not sure which disk is which, you can always display information about disk sizes and partition tables by running the following command: fdisk -l Disk Safe is on NFS Share Accessing Disk Safe on NFS share will not be easy, because while Live CD kernel contains drivers for NFS, the collection of programs available on CD lacks the set of tools for accessing NFS. Fortunately, it is not a problem - missing tools can be installed. 1. Execute the following command: apt-get install nfs-common 2. When prompted, press on the <Y> on the keyboard and then <Enter> to start installation. When the installation is completed, your screen should look like this: 3. Let's assume that your NFS server is called nfsserver and the directory with Disk Safe is called /Share. Execute the following command: mount nfsserver:/Share /mnt Now you can proceed to attaching the Disk Safe in the server web interface (see further). Disk Safe is on Samba Share Accessing Disk Safe on Samba share will also not be easy, because while Live CD kernel contains drivers for CIFS filesystem, the collection of programs available on CD lacks the utility for mounting Samba shares - mount.cifs. Fortunately, it is not a problem - mount.cifs can be installed. 1. Execute the following command: apt-get install smbfs 2. When prompted, press on the <Y> on the keyboard and then <Enter> to start installation. 3. Error messages are safe to ignore. 4. When the installation is completed, your screen should look like this: 5. Let's assume that your Samba server is called filedump and the share with Disk Safe is called Share. Execute the following command: mount.cifs //filedump/Share /mnt -o user= 6. Enter the password for accessing the Samba share when prompted. Now you can proceed to attaching the Disk Safe in the server web interface (see further). Attaching the Disk Safe in Server's Web Interface 1. Launch the web browser on some computer that can access the server you are restoring via the network. Then open the server's web interface, enter the Username and Password you configured, and click on the "Login" button. (See Accessing Standard Edition Web Interface, Accessing Enterprise Edition Web Interface, Accessing Advanced Edition Web Interface.) 2. If you are prompted for license activation, click "OK." 3. Click on the "Disk Safes" item in the Main Menu to open the "Disk Safes" screen. 4. In the "Disk Safes" menu, click on "Attach Existing Disk Safe." 5. Assuming that the Disk Safe was in Safe directory on the mounted local disk or network share, enter the "/mnt/Safe" as a path to the safe and click on the "Attach" button. 6. In a few seconds you should see the message "Successfully opened disk safe." Click "OK." You can proceed to restore the server from the data contained in the Disk Safe. See Launching Bare\-Metal Restore.
__label__pos
0.891718
Cómo construir un teclado de piano usando Vanilla JavaScript Hacer un teclado de piano que se pueda tocar puede ser una excelente manera de aprender un lenguaje de programación (además de ser muy divertido). Este tutorial le muestra cómo codificar uno usando JavaScript vanilla sin la necesidad de bibliotecas o marcos externos. Aquí está el teclado de piano JavaScript que hice si primero desea ver el producto final. Este tutorial asume que tiene un conocimiento básico de JavaScript, como funciones y manejo de eventos, así como familiaridad con HTML y CSS. De lo contrario, es totalmente amigable para principiantes y está dirigido a aquellos que desean mejorar sus habilidades de JavaScript a través del aprendizaje basado en proyectos (¡o simplemente quieren hacer un proyecto genial!). El teclado de piano que estamos haciendo para este proyecto se basa en el teclado sintético generado dinámicamente hecho por Keith William Horwood. Ampliaremos el número de teclas disponibles a 4 octavas y estableceremos nuevas combinaciones de teclas. Aunque su teclado puede tocar sonidos de otros instrumentos, mantendremos las cosas simples y nos quedaremos con el piano. Estos son los pasos que seguiremos para abordar este proyecto: 1. Obtenga archivos de trabajo 2. Configurar combinaciones de teclas 3. Generar teclado 4. Manejar pulsaciones de teclas ¡Empecemos! 1. Obtenga archivos de trabajo Este tutorial utilizará los siguientes archivos: · Audiosynth.js · PlayKeyboard.js Como se mencionó, basaremos nuestro teclado de piano en el hecho por Keith. Naturalmente, también tomaremos prestado parte de su código que amablemente nos ha dado permiso con audiosynth.js. Incorporamos audiosynth.js en playKeyboard.js (mi versión modificada de parte del código de Keith) que maneja todo nuestro JavaScript. Este tutorial brinda una explicación detallada en las siguientes secciones sobre los puntos principales de cómo el código en este archivo crea un teclado de piano completamente funcional. Dejamos intacto el archivo audiosynth.js ya que es el único responsable de la generación de sonido. El código de este archivo distingue este teclado de piano de otros que se encuentran en línea mediante el uso de Javascript para generar dinámicamente el sonido apropiado cuando el usuario presiona una tecla. Por lo tanto, el código no tiene que cargar ningún archivo de audio externo. Keith ya proporciona una explicación de cómo funciona la generación de sonido en su sitio web, por lo que no entraremos en detalles aquí. En pocas palabras, implica usar la Math.sin()función en JS para crear formas de onda sinusoidales y transformarlas para que suenen más como instrumentos reales a través de algunas matemáticas sofisticadas. Cree un archivo HTML de índice y vinculemos a los archivos JS en el encabezado: En el cuerpo, podemos crear un elemento vacío para que sirva como nuestro "contenedor" de teclado: Le damos un nombre de identificación para que podamos hacer referencia a él más tarde cuando creemos el teclado usando JS. Podemos ejecutar nuestro código JS llamándolo en el cuerpo también: playKeyboard() Usamos playKeyboard.js como una gran función. Se ejecutará tan pronto como el navegador llegue a esa línea de código y generará un teclado completamente funcional en el elemento con id = “keyboard”. Las primeras líneas de playKeyboard.js se configuran para la funcionalidad del dispositivo móvil (opcional) y crean un nuevo AudioSynth()objeto. Usamos este objeto para llamar a los métodos de audiosynth.js a los que vinculamos anteriormente. Usamos uno de estos métodos al principio para establecer un volumen para el sonido. En la línea 11, establecemos la posición del Do central en la cuarta octava. 2. Configurar combinaciones de teclas Antes de generar el teclado, debemos configurar nuestras combinaciones de teclas, ya que determinan cuántas teclas deben generarse. Originalmente quería intentar tocar las notas iniciales de 'Für Elise', así que elegí un rango de 4 octavas para un total de 48 teclas en blanco y negro. Esto requirió casi todas las teclas de mi teclado (PC) y puede incluir menos. Una nota de advertencia: no tengo las mejores combinaciones de teclas, por lo que pueden parecer poco intuitivas cuando intentas jugar. Quizás este sea el precio de intentar crear un teclado de 4 octavas. Para configurar las combinaciones de teclas, primero cree un objeto que utilizará el código clave como sus claves y la nota que se reproducirá como sus valores clave (línea inicial 15): var keyboard = { /* ~ */ 192: 'C,-2', /* 1 */ 49: 'C#,-2', /* 2 */ 50: 'D,-2', /* 3 */ 51: 'D#,-2', //...and the rest of the keys } Los comentarios denotan las teclas que un usuario puede presionar en un teclado de computadora. Si un usuario presiona la tecla de tilde, entonces el código clave correspondiente es 192. Puede obtener el código clave usando una herramienta como keycode.info. El valor de la clave es la nota que se tocará y se escribirá en el formato de 'nota, modificador de octava' donde el modificador de octava representa la posición relativa de la octava desde la octava que contiene el Do central. Por ejemplo, 'C, -2' es la nota C 2 octavas por debajo del Do central. Tenga en cuenta que no hay teclas "planas". Cada nota está representada por un 'sostenido'. Para que nuestro teclado de piano sea funcional, tenemos que preparar una tabla de búsqueda inversa donde intercambiamos los key: valuepares de modo que la nota a tocar se convierta en la tecla y el código de tecla se convierta en el valor. Necesitamos una tabla de este tipo porque queremos iterar sobre las notas musicales para generar fácilmente nuestro teclado. Aquí es donde las cosas pueden complicarse: en realidad necesitamos 2 tablas de búsqueda inversa. Usamos una tabla para buscar la etiqueta que queremos mostrar para la tecla de la computadora que presionamos para tocar una nota (declarada como reverseLookupTexten la línea 164) y una segunda para buscar la tecla real que se presionó (declarada como reverseLookupen la línea 165). El astuto puede darse cuenta de que ambas tablas de búsqueda tienen códigos clave como valores, entonces, ¿cuál es la diferencia entre ellos? It turns out that (for reasons unknown to me) when you get a keycode that corresponds to a key and you try to use String.fromCharCode() method on that keycode, you don’t always get back the same string representing the pressed key. For example, pressing left open bracket yields keycode 219 but when you actually try to convert the keycode back to a string using String.fromCharCode(219) it returns "Û". To get "[", you have to use key code 91. We replace the incorrect codes starting on line 168. Getting the right keycode initially involved a bit of trial and error, but later I realized you can just use another function (getDispStr() on line 318) to force the correct string to be displayed. The majority of the keys do behave properly but you can choose to start with a smaller keyboard so you don’t have to deal with incorrect keycodes. 3. Generate Keyboard We start the keyboard generation process by selecting our element keyboard container with document.getElementById(‘keyboard’) on line 209. On the next line, we declare the selectSound object and set the value property to zero to have audioSynth.js load the sound profile for piano. You may wish to enter a different value (can be 0-3) if you want to try out other instruments. See line 233 of audioSynth.js with Synth.loadSoundProfile for more details. On line 216 with var notes, we retrieve the available notes for one octave (C, C#, D…B) from audioSynth.js. We generate our keyboard by looping through each octave and then each note in that octave. For each note, we create a element to represent the appropriate key using document.createElement(‘div’). To distinguish whether we need to create a black or white key, we look at the length of the note name. Adding a sharp sign makes the length of the string greater than one (ex. ‘C#’) which indicates a black key and vice versa for white. For each key we can set a width, height, and an offset from the left based on key position. We can also set appropriate classes for use with CSS later. Next, we label the key with the computer key we need to press to play its note and store it in another element. This is where reverseLookupText comes in handy. Inside the same , we also display the note name. We accomplish all of this by setting the label’s innerHTML property and appending the label to the key (lines 240-242). label.innerHTML = '' + s + '' + ' ' + n.substr(0,1) + '' + (__octave + parseInt(i)) + '' + (n.substr(1,1)?n.substr(1,1):''); Similarly, we add an event listener to the key to handle mouse clicks (line 244): thisKey.addEventListener(evtListener[0], (function(_temp) { return function() { fnPlayKeyboard({keyCode:_temp}); } })(reverseLookup[n + ',' + i])); The first parameter evtListener[0] is a mousedown event declared much earlier on line 7. The second parameter is a function that returns a function. We need reverseLookup to get us the correct keycode and we pass that value as a parameter _temp to the inner function. We will not need reverseLookup to handle actual keydown events. This code is pre-ES2015 (aka ES6) and the updated, hopefully clearer equivalent is: const keyCode = reverseLookup[n + ',' + i]; thisKey.addEventListener('mousedown', () => { fnPlayKeyboard({ keyCode }); }); After creating and appending all necessary keys to our keyboard, we will need to handle the actual playing of a note. 4. Handle Key Presses We handle key presses the same way whether the user clicks the key or presses the corresponding computer key through use of the function fnPlayKeyboard on line 260. The only difference is the type of event we use in addEventListener to detect the key press. We set up an array called keysPressed in line 206 to detect what keys are being pressed/clicked. For simplicity, we will assume that a key being pressed can include it being clicked as well. We can divide the process of handling key presses into 3 steps: adding the keycode of the pressed key to keysPressed, playing the appropriate note, and removing the keycode from keysPressed. The first step of adding a keycode is easy: keysPressed.push(e.keyCode); where e is the event detected by addEventListener. If the added keycode is one of the key bindings we assigned, then we call fnPlayNote() on line 304 to play the note associated with that key. In fnPlayNote(), we first create a new Audio() element container for our note using the generate() method from audiosynth.js. When the audio loads, we can then play the note. Lines 308-313 are legacy code and seem they can just be replaced by container.play(), though I have not done any extensive testing to see what the difference is. Removing a key press is also quite straightforward, as you can just remove the key from the keysPressed array with the splice method on line 298. For more details, see the function called fnRemoveKeyBinding(). The only thing we have to watch out for is when the user holds down a key or multiple keys. We have to make sure that the note only plays once while a key is held down (lines 262-267): var i = keysPressed.length; while(i--) { if(keysPressed[i]==e.keyCode) { return false; } } Returning false prevents the rest of fnPlayKeyboard() from executing. Summary We have created a fully functioning piano keyboard using vanilla JavaScript! To recap, here are the steps we took: 1. We set up our index HTML file to load the appropriate JS files and execute playKeyboard() in to generate and make the keyboard functional. We have a element with id= "keyboard" where the keyboard will be displayed on the page. 2. In our JavaScript file playKeyboard.js, we set up our key bindings with keycodes as keys and musical notes as values. We also create two reverse lookup tables in which one is responsible for looking up the appropriate key label based on the note and the other for looking up the correct keycode. 3. We dynamically generate the keyboard by looping through every note in each octave range. Each key is created as its own element. We use the reverse lookup tables to generate the key label and correct keycode. Then an event listener on mousedown uses it to call fnPlayKeyboard() to play the note. The keydown event calls the same function but does not need a reverse lookup table to get the keycode. 4. We handle key presses resulting from either mouse clicks or computer key presses in 3 steps: add keycode of the pressed key to an array, play the appropriate note, and remove keycode from that array. We must be careful not to repeatedly play a note (from the beginning) while the user continuously holds down a key. The keyboard is now fully functional but it may look a bit dull. I will leave the CSS part to you ? Again, here is the JavaScript piano keyboard I made for reference. If you want to learn more about web development and check out some other neat projects, visit my blog at 1000 Mile World. Thanks for reading and happy coding!
__label__pos
0.560217
Special Charators Hi Folks, Is there a way to use them in strings? Can I search for them and replace them with an ascii value or silimar somehow? Thanks in advace I don’t understand. :frowning: If it’s from an input field it’s already a string! Do you mean the text comes from a database and you’re creating JavaScript containing that text using server-side programming? In that case you need to escape special characters in the server-side script that generates the code. It’s not a JavaScript problem. Why should that cause an error (unless homepage[0] is undefined)? When asking for help online it’s always a good idea to be as explicit as possible about what you’re trying to do, and why. Providing code examples of existing code also helps. I don’t quite understand what you are trying to do, or how. Thanks for your reply. Its from a user input field so I’m not sure where the special chars will be and what they are. I query the database and create my html, could I use a regular expression or similar when doing this to convert all the special chars to javascript friendly text? For example this code causes an error: homepage[0] += “example - example” Many thanks What special characters? If you want to include a character that you cannot input directly from your keyboard, or cannot be represented using the character encoding you use, you can use escape notation. Octal escape notation: var copyright = "\\251 2010"; Unicode escape notation: var copyright = "\\u00a9 2010"; Literal notation: var copyright = "&#169; 2010"; For characters that are special to JavaScript, escape them with a preceding backslash: var s1 = "My \\"new\\" car"; var s2 = 'Jane\\'s car'; Thanks for your reply. The javascript thats causing an error is below. Can you help? Thankyou homepage[0] = "<h2 class='draggable'>Bring n buy</h2><div class='container'>" homepage[0] += '<ul>' homepage[0] += "<li><a href='index.cfm?area=marketplace/index&page=view-forum&forumid=267'>Kingsize bed frame</a></li>" Error: unterminated string literal Source File: http://intranet/portal.cfm Line: 24, Column: 16 Source Code: homepage[0] += "<li><a href='index.cfm?area=marketplace/index&page=view-forum&forumid=267'> Do you have this JavaScript code between <script> and </script> rather than in an external script file (<script src="..."></script>? If so, the problem is most likely the closing tags you have in your strings. In HTML (which includes pretend-XHTML) the script element type has a content model of CDATA, which behaves a bit oddly. One oddity is that the first occurrance of the character sequence ‘</’ followed by a name-start character will be interpreted as </script> and thereby close the script tag. To prevent this you need to escape that character sequence, which you can do by inserting a backslash character between the ‘<’ and the ‘/’. That ‘escapes’ the ‘/’ character. homepage[0] += "<li><a href='index.cfm?area=marketplace/index&page=view-forum&forumid=267'>Kingsize bed frame<\\/a><\\/li>" Without the backslash characters in the end tags, the script tag is closed after ‘bed frame’ which means the string constant isn’t properly terminated.
__label__pos
0.879009
6 I have two symmetric (item co-occurrence) matrices A and B and want to find out if they describe the same co-occurrence, only with the row/column labels permuted. (The same permutation has to be applied to rows and columns to keep the symmetry/co-occurrence property) For example these two matrices should be equal in my test: a = np.array([ #1 #2 #3 #4 #5 #6 #7 [0, 1, 1, 0, 0, 0, 1], #1 [1, 0, 1, 2, 1, 1, 2], #2 [1, 1, 0, 0, 0, 0, 1], #3 [0, 2, 0, 0, 4, 0, 4], #4 [0, 1, 0, 4, 0, 1, 2], #5 [0, 1, 0, 0, 1, 0, 0], #6 [1, 2, 1, 4, 2, 0, 0] #7 ]) b = np.array([ #5 #7 #1,3#3,1#2 #4 #6 [0, 2, 0, 0, 1, 4, 1], #5 [2, 0, 1, 1, 2, 4, 0], #7 [0, 1, 0, 1, 1, 0, 0], #1,3 could be either [0, 1, 1, 0, 1, 0, 0], #1,3 could be either [1, 2, 1, 1, 0, 2, 1], #2 [4, 4, 0, 0, 2, 0, 0], #4 [1, 0, 0, 0, 1, 0, 0] #6 ]) I currently test if the eigenvalues are the same using numpy.linalg.eigvals (I am not even sure this is a sufficient condition), but I would like to find a test which doesn't involve numerical accuracy, since I am dealing with integers here. 5 • 2 This problem is equivalent to graph isomorphism: exact solutions are likely to be slow. See e.g. this question – Maxim Oct 29, 2018 at 11:23 • I was wondering how did you create b without knowing the indices [5, 7, 1, 3, 2, 4, 6] in the first place. – Andreas K. Oct 29, 2018 at 12:44 • I calculate the co-occurrence of objects based on a list of lists of objects. These objects get random indices assigned (out of my control) before the co-occurrence matrix is created. This way a different co-oc matrix is created every time. For my example I used two of these matrices and assigned the indices for the second matrix by hand. – C. Yduqoli Oct 30, 2018 at 2:41 • I'd recommend reading up on the graph isomorphism problem and checking to see if your particular flavor of graph is a solved problem. If not, you're probably in for a lot of brute force. – Daniel F Oct 30, 2018 at 12:09 • If in many cases your matrices won't be equivalent, it might be worth first doing a test that wil tell you if they are not, but won't tell you if they are. For example you could, for each matrix, compute the multiset of each row (eg the first row of a would be {(4,0), (3,1)}) and then forming the multiset of the row multisets. If these two multisets (one for a, one for b) are not equal then the matrices are not equivalent. – dmuir Oct 30, 2018 at 19:28 3 Answers 3 2 Here's a vectorized solution based on sorting and leveraging searchsorted - import pandas as pd # Sort rows for a and b aS = np.sort(a,axis=1) bS = np.sort(b,axis=1) # Scale down each row to a scalar each scale = np.r_[(np.maximum(aS.max(0),bS.max(0))+1)[::-1].cumprod()[::-1][1:],1] aS1D = aS.dot(scale) bS1D = bS.dot(scale) # Use searchsorted to get the correspondence on indexing sidx = aS1D.argsort() searchsorted_idx = np.searchsorted(aS1D,bS1D,sorter=sidx) searchsorted_idx[searchsorted_idx==len(aS1D)] = len(aS1D)-1 df = pd.DataFrame({'A':searchsorted_idx}) new_order = sidx[df.groupby('A').cumcount().values+searchsorted_idx] # new_order is the permuted order, i.e. [5, 7, 1, 3, 2, 4, 6] # Finally index into a with the new_order and compare against b out = np.array_equal(a[new_order[:,None], new_order],b) 6 • Nice one, but a lot slower than the solution with eigenvalues. – Andreas K. Oct 29, 2018 at 12:02 • @AndyK What size are you testing it on? – Divakar Oct 29, 2018 at 12:03 • That doesn't seem to be correct. I tried a = scipy.linalg.toeplitz(np.arange(8)) and b some shuffled version of that, and am getting False all the time. Oct 29, 2018 at 12:14 • @AndyK I'm pretty sure eigenvalues are not sufficient. for example [[4 0] [0 0]] and [[2 2] [2 2]] have the same eigenvalues but obviously cannot be shuffled into each other. Oct 29, 2018 at 12:18 • What about np.array([[12, 8, 11],[8, 0, 12],[11, 12, 8]]) np.array([[0, 12, 8],[12, 8, 11],[8, 11, 12]]). This should return True, but your method return False in my testing. – C. Yduqoli Oct 30, 2018 at 3:14 1 I will assume that you have the list of permutation of the rows/columns of a which gives the b, e.g. something like this p = np.array([5, 7, 1, 3, 2, 4, 6]) - 1 Then you can simply do the following on a a_p = a[p] a_p = a_p[:, p] and check if b and the permuted a_p are equal: (a_p == b).all() Edit: since you don't have a list like the above p, you could (at least for small arrays a and b) generate the permutations of the indices and check for each one: from itertools import permutations def a_p(a, b, p): p = np.array(p) a_p = a[p] a_p = a_p[:, p] return a_p for p in permutations(range(a.shape[0])): if (a_p(a, b, p) == b).all(): print('True') break else: print('False') Note that this brute-force method works for non-symmetric matrices as well. But since the number of permutations is huge for large arrays a and b, this method can be very slow. So your solution with computing eigenvalues is much better. Here's a benchmark: def Yduqoli(a, b): ''' I suppose your solution is similar''' if (np.array(np.unique(a, return_counts=True)) == np.array(np.unique(b, return_counts=True))).all(): a_eigs = np.sort(np.linalg.eigvals(a)) b_eigs = np.sort(np.linalg.eigvals(b)) return np.allclose(a_eigs, b_eigs) else: return False def AndyK(a, b): for p in permutations(range(a.shape[0])): if (a_p(a, b, p) == b).all(): return True return False %timeit AndyK(a,b) 103 ms ± 4.54 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) %timeit Yduqoli(a,b) 408 µs ± 65.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) where I used the symmetric matrices a and b provided by the OP. Update: As mentioned by Paul Panzer, simply checking the eigenvalues can give incorrect result in some cases, e.g. a = np.array([[4, 0], [0, 0]]), b = np.array([[2, 2], [2, 2]]) have the same eigenvalues, but cannot be shuffled one into the other. So we first need to check if the arrays a and b have the same elements (regardless their positions). 2 • Sorry, I don't have that list. – C. Yduqoli Oct 29, 2018 at 10:43 • Do you mean a = np.array([[4, 0], [0, 0]])? It is symmetric because a = a.T. But it was an arbitrary example. – Andreas K. Oct 30, 2018 at 8:27 1 You could always sort the matrix by row-norm and see if they are different. If two rows have the same norm, you'd have to check permutations of the rows that have the same norm though. But this reduces the problem to only rows with the same norm. In many cases you can first sort by 2-norm, then 1-norm and finally brute force the remaining permutations. import numpy as np def get_row_norm(a): """ Sort by 2-norm """ row_norms = np.sum(a**2, axis=1) return row_norms def sort(a): """ Return the matrix a sorted by 2-norm """ n = a.shape[0] # Get the norms row_norms = get_row_norm(a) # Get the order order = np.argsort(row_norms)[::-1] sorted_a = a.copy() for m in range(n): i = order[m] for k in range(m+1): j = order[k] sorted_a[m, k] = a[i, j] sorted_a[k, m] = a[i, j] return sorted_a a = np.array([ #1 #2 #3 #4 #5 #6 #7 [0, 1, 1, 0, 0, 0, 1], #1 [1, 0, 1, 2, 1, 1, 2], #2 [1, 1, 0, 0, 0, 0, 1], #3 [0, 2, 0, 0, 4, 0, 4], #4 [0, 1, 0, 4, 0, 1, 2], #5 [0, 1, 0, 0, 1, 0, 0], #6 [1, 2, 1, 4, 2, 0, 0] #7 ]) b = np.array([ #5 #7 #1,3#3,1#2 #4 #6 [0, 2, 0, 0, 1, 4, 1], #5 [2, 0, 1, 1, 2, 4, 0], #7 [0, 1, 0, 1, 1, 0, 0], #1,3 could be either [0, 1, 1, 0, 1, 0, 0], #1,3 could be either [1, 2, 1, 1, 0, 2, 1], #2 [4, 4, 0, 0, 2, 0, 0], #4 [1, 0, 0, 0, 1, 0, 0] #6 ]) # Sort a and b A = sort(a) B = sort(b) # Print the norms print(get_row_norm(a)) # [ 3. 12. 3. 36. 22. 2. 26.] print(get_row_norm(A)) # [36. 26. 22. 12. 3. 3. 2.] print(get_row_norm(B)) # [36. 26. 22. 12. 3. 3. 2.] # Assert that they are equal print( (A == B).all()) Note that if they are not equal, you still have to check permutation of the fifth and sixth row, since their norms are equal. 7 • Here's a counter-example: a = np.array([[2, 2], [0, 1]]), b = np.array([[1, 0], [2, 2]]), where b is a with swapped rows and columns. – Andreas K. Oct 29, 2018 at 11:27 • @AndyK But that is a different matrix altogether? Oct 29, 2018 at 11:38 • I meant b is a with swapped rows 0 <-> 1 and columns 0 <-> 1. – Andreas K. Oct 29, 2018 at 11:44 • But those matrices are not symmetric and that is what the op asked for. Oct 29, 2018 at 12:54 • Indeed you are right. I forgot that they should be symmetric. – Andreas K. Oct 29, 2018 at 13:04 Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.88727
Net-informations.com SiteMap  | About     How to Transaction in ADO.NET Performing a Transaction Using ADO.NET A transaction consists of a single command or a group of commands that execute together. When we do some database operations in such a way that either all the database operations are successful or all of them fail. This would result in the amount of information being same once the transaction is complete or it fails. Transactions allow you to combine multiple operations into a single unit of work. If a failure occurs at one point in the transaction, all of the updates can be rolled back to their pre-transaction state. In ADO.NET, you can control transactions using the Connection and Transaction objects. You can initiate a local transaction using BeginTransaction statement. Connection.BeginTransaction. Once you have begun a transaction, you can enlist a command in that transaction using the Transaction property of the Command object. new SqlCommand("Your SQL Statemnt Here", Connection, transaction).ExecuteNonQuery(); You can then use the Transaction object to commit or rollback modifications made at the data source based on the success or failure of the components of the transaction. transaction.Commit(); The following example shows how to perform a transaction in an ADO.Net programming. C# Source Code using System; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string connetionString = null; SqlConnection cnn; SqlCommand cmd; SqlTransaction transaction; connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"; cnn = new SqlConnection(connetionString); try { cnn.Open(); transaction = cnn.BeginTransaction(); cmd = new SqlCommand("Your SQL Statemnt Here", cnn, transaction); cmd.ExecuteNonQuery(); cmd = new SqlCommand("Your SQL Statemnt Here", cnn, transaction); cmd.ExecuteNonQuery(); transaction.Commit(); } catch (Exception ex) { MessageBox.Show("Can not open connection ! "); } cnn.Close(); } } } VB.Net Source Code Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim cnn As SqlConnection Dim cmd As SqlCommand Dim transaction As SqlTransaction connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" cnn = New SqlConnection(connetionString) Try cnn.Open() transaction = cnn.BeginTransaction() cmd = New SqlCommand("Your SQL Statemnt Here", cnn, transaction) cmd.ExecuteNonQuery() cmd = New SqlCommand("Your SQL Statemnt Here", cnn, transaction) cmd.ExecuteNonQuery() transaction.Commit() Catch ex As Exception MessageBox.Show("Can not open connection ! ") End Try cnn.Close() End Sub End Class net-informations.com (C) 2016    Founded by raps mk All Rights Reserved. All other trademarks are property of their respective owners.
__label__pos
0.962003
시간 제한 메모리 제한 제출 정답 맞은 사람 정답 비율 2 초 128 MB 1 0 0 0.000% 문제 Shanghai Hypercomputers, the world's largest computer chip manufacturer, has invented a new class of nanoparticles called Amphiphilic Carbon Molecules (ACMs). ACMs are semiconductors. It means that they can be either conductors or insulators of electrons, and thus possess a property that is very important for the computer chip industry. They are also amphiphilic molecules, which means parts of them are hydrophilic while other parts of them are hydrophobic. Hydrophilic ACMs are soluble in polar solvents (for example, water) but are insoluble in nonpolar solvents (for example, acetone). Hydrophobic ACMs, on the contrary, are soluble in acetone but insoluble in water. Semiconductor ACMs dissolved in either water or acetone can be used in the computer chip manufacturing process.  As a materials engineer at Shanghai Hypercomputers, your job is to prepare ACM solutions from ACM particles. You go to your factory everyday at 8 am and find a batch of ACM particles on your workbench. You prepare the ACM solutions by dripping some water, as well as some acetone, into those particles and watch the ACMs dissolve in the solvents. You always want to prepare unmixed solutions, so you first separate the ACM particles by placing an Insulating Carbon Partition Card (ICPC) perpendicular to your workbench. The ICPC is long enough to completely separate the particles. You then drip water on one side of the ICPC and acetone on the other side. The ICPC helps you obtain hydrophilic ACMs dissolved in water on one side and hydrophobic ACMs dissolved in acetone on the other side. If you happen to put the ICPC on top of some ACM particles, those ACMs will be right at the border between the water solution and the acetone solution, and they will be dissolved. Fig.1 shows your working situation.  Fig. 1 Your daily job is very easy and boring, so your supervisor makes it a little bit more challenging by asking you to dissolve as much ACMs into solution as possible. You know you have to be very careful about where to put the ICPC since hydrophilic ACMs on the acetone side, or hydrophobic ACMs on the water side, will not dissolve. As an experienced engineer, you also know that sometimes it can be very difficult to find the best position for the ICPC, so you decide to write a program to help you. You have asked your supervisor to buy a special digital camera and have it installed above your workbench, so that your program can obtain the exact positions and species (hydrophilic or hydrophobic) of each ACM particle in a 2D pictures taken by the camera. The ICPC you put on your workbench will appear as a line in the 2D pictures.  Fig. 2 입력 The input contains no more than 30 test cases. The first line of each test case contains 2 integers n, m (1<=n, m<=30), which is the size of the board. After this line, there will be n more lines. Each of these lines contains m strings, separated by single spaces. Each of these strings represents one block in the initial configuration. Each string always consists of two capital letters. The first letter is the symbol of the block. The second letter is always one of the letters `U',`D',`L',`R' and `S', which shows the block's moving attribute: up, down, left, right, and stand still respectively. There are no blank lines between test cases. The input ends with a line of two 0's: `0 0'. 출력 For each test case, first output the test case number. After this line, you must output the final configuration of the board with n lines, each containing m characters. If there is a block on the position, output the symbol of the block. If there is no block on the position, output a period instead. Do not output blank lines between test cases. 예제 입력 3 3 AD AU CL HS GU HL CS FD GS 1 2 BS BL 0 0 예제 출력 Case 1 ... ... .F. Case 2 .. 힌트
__label__pos
0.627966
Source orange / source / orange / numeric_interface.cpp Full commit #include "numeric_interface.hpp" #include "errors.hpp" bool importarray_called = false; PyObject *moduleNumeric = NULL, *moduleNumarray = NULL, *moduleNumpy = NULL; PyObject *numericMaskedArray = NULL, *numarrayMaskedArray = NULL, *numpyMaskedArray = NULL; PyTypeObject *PyNumericArrayType = NULL, *PyNumarrayArrayType = NULL, *PyNumpyArrayType = NULL; void initializeNumTypes() { PyObject *ma; moduleNumeric = PyImport_ImportModule("Numeric"); if (moduleNumeric) { PyNumericArrayType = (PyTypeObject *)PyDict_GetItemString(PyModule_GetDict(moduleNumeric), "ArrayType"); ma = PyImport_ImportModule("MA"); if (ma) numericMaskedArray = PyDict_GetItemString(PyModule_GetDict(ma), "MaskedArray"); } else PyErr_Clear(); moduleNumarray = PyImport_ImportModule("numarray"); if (moduleNumarray) { PyNumarrayArrayType = (PyTypeObject *)PyDict_GetItemString(PyModule_GetDict(moduleNumarray), "ArrayType"); ma = PyImport_ImportModule("numarray.ma"); if (ma) numarrayMaskedArray = PyDict_GetItemString(PyModule_GetDict(ma), "MaskedArray"); } else PyErr_Clear(); moduleNumpy = PyImport_ImportModule("numpy"); if (moduleNumpy) { PyObject *mdict = PyModule_GetDict(moduleNumpy); PyNumpyArrayType = (PyTypeObject *)PyDict_GetItemString(mdict, "ndarray"); ma = PyDict_GetItemString(mdict, "ma"); if (ma) numpyMaskedArray = PyDict_GetItemString(PyModule_GetDict(ma), "MaskedArray"); } else PyErr_Clear(); importarray_called = true; // import_array(); } // avoids unnecessarily importing the numeric modules bool isSomeNumeric_wPrecheck(PyObject *args) { static char *numericNames[] = {"array", "numpy.ndarray", "ndarray", "numarray.numarraycore.NumArray", "NumArray", 0}; for(char **nni = numericNames; *nni; nni++) if (!strcmp(args->ob_type->tp_name, *nni)) return isSomeNumeric(args); return false; } bool isSomeNumeric(PyObject *obj) { if (!importarray_called) initializeNumTypes(); return PyNumericArrayType && PyType_IsSubtype(obj->ob_type, PyNumericArrayType) || PyNumarrayArrayType && PyType_IsSubtype(obj->ob_type, PyNumarrayArrayType) || PyNumpyArrayType && PyType_IsSubtype(obj->ob_type, PyNumpyArrayType); } bool isSomeMaskedNumeric_wPrecheck(PyObject *args) { static char *numericNames[] = {"MaskedArray", "numpy.ma.core.MaskedArray", "numarray.ma.MA.MaskedArray", 0}; for(char **nni = numericNames; *nni; nni++) if (!strcmp(args->ob_type->tp_name, *nni)) return isSomeMaskedNumeric(args); return false; } bool isSomeMaskedNumeric(PyObject *obj) { if (!importarray_called) initializeNumTypes(); return numarrayMaskedArray && PyType_IsSubtype(obj->ob_type, (PyTypeObject *)numarrayMaskedArray) || numpyMaskedArray && PyType_IsSubtype(obj->ob_type, (PyTypeObject *)numpyMaskedArray); } char getArrayType(PyObject *args) { PyObject *res = PyObject_CallMethod(args, "typecode", NULL); if (!res) { PyErr_Clear(); PyObject *ress = PyObject_GetAttrString(args, "dtype"); if (ress) { res = PyObject_GetAttrString(ress, "char"); Py_DECREF(ress); } } if (!res) { PyErr_Clear(); return -1; } char cres = PyString_AsString(res)[0]; Py_DECREF(res); return cres; } void numericToDouble(PyObject *args, double *&matrix, int &columns, int &rows) { prepareNumeric(); if (!isSomeNumeric(args)) raiseErrorWho("numericToDouble", "invalid type (got '%s', expected 'ArrayType')", args->ob_type->tp_name); PyArrayObject *array = (PyArrayObject *)(args); if (array->nd != 2) raiseErrorWho("numericToDouble", "two-dimensional array expected"); const char arrayType = getArrayType(array); if (!strchr(supportedNumericTypes, arrayType)) raiseErrorWho("numericToDouble", "ExampleTable cannot use arrays of complex numbers or Python objects", NULL); columns = array->dimensions[1]; rows = array->dimensions[0]; matrix = new double[columns * rows]; const int &strideRow = array->strides[0]; const int &strideCol = array->strides[1]; double *matrixi = matrix; char *coli, *cole; for(char *rowi = array->data, *rowe = array->data + rows*strideRow; rowi != rowe; rowi += strideRow) { #define READLINE(TYPE) \ for(coli = rowi, cole = rowi + columns*strideCol; coli != cole; *matrixi++ = double(*(TYPE *)coli), coli += strideCol); \ break; switch (arrayType) { case 'c': case 'b': READLINE(char) case 'B': READLINE(unsigned char) case 'h': READLINE(short) case 'H': READLINE(unsigned short) case 'i': READLINE(int) case 'I': READLINE(unsigned int) case 'l': READLINE(long) case 'L': READLINE(unsigned long) case 'f': READLINE(float) case 'd': READLINE(double) } #undef READLINE } } void numericToDouble(PyObject *args, double *&matrix, int &rows) { prepareNumeric(); if (!isSomeNumeric(args)) raiseErrorWho("numericToDouble", "invalid type (got '%s', expected 'ArrayType')", args->ob_type->tp_name); PyArrayObject *array = (PyArrayObject *)(args); if (array->nd != 1) raiseErrorWho("numericToDouble", "one-dimensional array expected"); const char arrayType = getArrayType(array); if (!strchr(supportedNumericTypes, arrayType)) raiseError("numericToDouble", "ExampleTable cannot use arrays of complex numbers or Python objects", NULL); rows = array->dimensions[0]; matrix = new double[rows]; const int &strideRow = array->strides[0]; double *matrixi = matrix; char *rowi, *rowe; #define READLINE(TYPE) \ for(rowi = array->data, rowe = array->data + rows*strideRow; rowi != rowe; *matrixi++ = double(*(TYPE *)rowi), rowi += strideRow); \ break; switch (arrayType) { case 'c': case 'b': READLINE(char) case 'B': READLINE(unsigned char) case 'h': READLINE(short) case 'H': READLINE(unsigned short) case 'i': READLINE(int) case 'I': READLINE(unsigned int) case 'l': READLINE(long) case 'L': READLINE(unsigned long) case 'f': READLINE(float) case 'd': READLINE(double) } #undef READLINE }
__label__pos
0.998767
summaryrefslogtreecommitdiffstats path: root/src/set.c blob: ff34bf5ee8f568e49a3346e11f35127a3e91fa44 (plain) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 /* * (C) 2012-2013 by Pablo Neira Ayuso <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This code has been sponsored by Sophos Astaro <http://www.sophos.com> */ #include "internal.h" #include <time.h> #include <endian.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <netinet/in.h> #include <limits.h> #include <errno.h> #include <libmnl/libmnl.h> #include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nf_tables.h> #include <libnftables/set.h> #include "linux_list.h" #include "expr/data_reg.h" struct nft_set *nft_set_alloc(void) { struct nft_set *s; s = calloc(1, sizeof(struct nft_set)); if (s == NULL) return NULL; INIT_LIST_HEAD(&s->element_list); return s; } EXPORT_SYMBOL(nft_set_alloc); void nft_set_free(struct nft_set *s) { struct nft_set_elem *elem, *tmp; if (s->table != NULL) xfree(s->table); if (s->name != NULL) xfree(s->name); list_for_each_entry_safe(elem, tmp, &s->element_list, head) { list_del(&elem->head); nft_set_elem_free(elem); } xfree(s); } EXPORT_SYMBOL(nft_set_free); bool nft_set_attr_is_set(const struct nft_set *s, uint16_t attr) { return s->flags & (1 << attr); } EXPORT_SYMBOL(nft_set_attr_is_set); void nft_set_attr_unset(struct nft_set *s, uint16_t attr) { switch (attr) { case NFT_SET_ATTR_TABLE: if (s->flags & (1 << NFT_SET_ATTR_TABLE)) if (s->table) { xfree(s->table); s->table = NULL; } break; case NFT_SET_ATTR_NAME: if (s->flags & (1 << NFT_SET_ATTR_NAME)) if (s->name) { xfree(s->name); s->name = NULL; } break; case NFT_SET_ATTR_FLAGS: case NFT_SET_ATTR_KEY_TYPE: case NFT_SET_ATTR_KEY_LEN: case NFT_SET_ATTR_DATA_TYPE: case NFT_SET_ATTR_DATA_LEN: case NFT_SET_ATTR_FAMILY: break; default: return; } s->flags &= ~(1 << attr); } EXPORT_SYMBOL(nft_set_attr_unset); void nft_set_attr_set(struct nft_set *s, uint16_t attr, const void *data) { switch(attr) { case NFT_SET_ATTR_TABLE: if (s->table) xfree(s->table); s->table = strdup(data); break; case NFT_SET_ATTR_NAME: if (s->name) xfree(s->name); s->name = strdup(data); break; case NFT_SET_ATTR_FLAGS: s->set_flags = *((uint32_t *)data); break; case NFT_SET_ATTR_KEY_TYPE: s->key_type = *((uint32_t *)data); break; case NFT_SET_ATTR_KEY_LEN: s->key_len = *((uint32_t *)data); break; case NFT_SET_ATTR_DATA_TYPE: s->data_type = *((uint32_t *)data); break; case NFT_SET_ATTR_DATA_LEN: s->data_len = *((uint32_t *)data); break; case NFT_SET_ATTR_FAMILY: s->family = *((uint32_t *)data); break; default: return; } s->flags |= (1 << attr); } EXPORT_SYMBOL(nft_set_attr_set); void nft_set_attr_set_u32(struct nft_set *s, uint16_t attr, uint32_t val) { nft_set_attr_set(s, attr, &val); } EXPORT_SYMBOL(nft_set_attr_set_u32); void nft_set_attr_set_str(struct nft_set *s, uint16_t attr, const char *str) { nft_set_attr_set(s, attr, str); } EXPORT_SYMBOL(nft_set_attr_set_str); const void *nft_set_attr_get(struct nft_set *s, uint16_t attr) { if (!(s->flags & (1 << attr))) return NULL; switch(attr) { case NFT_SET_ATTR_TABLE: return s->table; case NFT_SET_ATTR_NAME: return s->name; case NFT_SET_ATTR_FLAGS: return &s->set_flags; case NFT_SET_ATTR_KEY_TYPE: return &s->key_type; case NFT_SET_ATTR_KEY_LEN: return &s->key_len; case NFT_SET_ATTR_DATA_TYPE: return &s->data_type; case NFT_SET_ATTR_DATA_LEN: return &s->data_len; case NFT_SET_ATTR_FAMILY: return &s->family; } return NULL; } EXPORT_SYMBOL(nft_set_attr_get); const char *nft_set_attr_get_str(struct nft_set *s, uint16_t attr) { return nft_set_attr_get(s, attr); } EXPORT_SYMBOL(nft_set_attr_get_str); uint32_t nft_set_attr_get_u32(struct nft_set *s, uint16_t attr) { uint32_t val = *((uint32_t *)nft_set_attr_get(s, attr)); return val; } EXPORT_SYMBOL(nft_set_attr_get_u32); struct nlmsghdr * nft_set_nlmsg_build_hdr(char *buf, uint16_t cmd, uint16_t family, uint16_t type, uint32_t seq) { struct nlmsghdr *nlh; struct nfgenmsg *nfh; nlh = mnl_nlmsg_put_header(buf); nlh->nlmsg_type = (NFNL_SUBSYS_NFTABLES << 8) | cmd; nlh->nlmsg_flags = NLM_F_REQUEST | type; nlh->nlmsg_seq = seq; nfh = mnl_nlmsg_put_extra_header(nlh, sizeof(struct nfgenmsg)); nfh->nfgen_family = family; nfh->version = NFNETLINK_V0; nfh->res_id = 0; return nlh; } EXPORT_SYMBOL(nft_set_nlmsg_build_hdr); void nft_set_nlmsg_build_payload(struct nlmsghdr *nlh, struct nft_set *s) { if (s->flags & (1 << NFT_SET_ATTR_TABLE)) mnl_attr_put_strz(nlh, NFTA_SET_TABLE, s->table); if (s->flags & (1 << NFT_SET_ATTR_NAME)) mnl_attr_put_strz(nlh, NFTA_SET_NAME, s->name); if (s->flags & (1 << NFT_SET_ATTR_FLAGS)) mnl_attr_put_u32(nlh, NFTA_SET_FLAGS, htonl(s->set_flags)); if (s->flags & (1 << NFT_SET_ATTR_KEY_TYPE)) mnl_attr_put_u32(nlh, NFTA_SET_KEY_TYPE, htonl(s->key_type)); if (s->flags & (1 << NFT_SET_ATTR_KEY_LEN)) mnl_attr_put_u32(nlh, NFTA_SET_KEY_LEN, htonl(s->key_len)); /* These are only used to map matching -> action (1:1) */ if (s->flags & (1 << NFT_SET_ATTR_DATA_TYPE)) mnl_attr_put_u32(nlh, NFTA_SET_DATA_TYPE, htonl(s->data_type)); if (s->flags & (1 << NFT_SET_ATTR_DATA_LEN)) mnl_attr_put_u32(nlh, NFTA_SET_DATA_LEN, htonl(s->data_len)); } EXPORT_SYMBOL(nft_set_nlmsg_build_payload); static int nft_set_parse_attr_cb(const struct nlattr *attr, void *data) { const struct nlattr **tb = data; int type = mnl_attr_get_type(attr); if (mnl_attr_type_valid(attr, NFTA_SET_MAX) < 0) return MNL_CB_OK; switch(type) { case NFTA_SET_TABLE: case NFTA_SET_NAME: if (mnl_attr_validate(attr, MNL_TYPE_STRING) < 0) { perror("mnl_attr_validate"); return MNL_CB_ERROR; } break; case NFTA_SET_FLAGS: case NFTA_SET_KEY_TYPE: case NFTA_SET_KEY_LEN: case NFTA_SET_DATA_TYPE: case NFTA_SET_DATA_LEN: if (mnl_attr_validate(attr, MNL_TYPE_U32) < 0) { perror("mnl_attr_validate"); return MNL_CB_ERROR; } break; } tb[type] = attr; return MNL_CB_OK; } int nft_set_nlmsg_parse(const struct nlmsghdr *nlh, struct nft_set *s) { struct nlattr *tb[NFTA_SET_MAX+1] = {}; struct nfgenmsg *nfg = mnl_nlmsg_get_payload(nlh); int ret = 0; mnl_attr_parse(nlh, sizeof(*nfg), nft_set_parse_attr_cb, tb); if (tb[NFTA_SET_TABLE]) { s->table = strdup(mnl_attr_get_str(tb[NFTA_SET_TABLE])); s->flags |= (1 << NFT_SET_ATTR_TABLE); } if (tb[NFTA_SET_NAME]) { s->name = strdup(mnl_attr_get_str(tb[NFTA_SET_NAME])); s->flags |= (1 << NFT_SET_ATTR_NAME); } if (tb[NFTA_SET_FLAGS]) { s->set_flags = ntohl(mnl_attr_get_u32(tb[NFTA_SET_FLAGS])); s->flags |= (1 << NFT_SET_ATTR_FLAGS); } if (tb[NFTA_SET_KEY_TYPE]) { s->key_type = ntohl(mnl_attr_get_u32(tb[NFTA_SET_KEY_TYPE])); s->flags |= (1 << NFT_SET_ATTR_KEY_TYPE); } if (tb[NFTA_SET_KEY_LEN]) { s->key_len = ntohl(mnl_attr_get_u32(tb[NFTA_SET_KEY_LEN])); s->flags |= (1 << NFT_SET_ATTR_KEY_LEN); } if (tb[NFTA_SET_DATA_TYPE]) { s->data_type = ntohl(mnl_attr_get_u32(tb[NFTA_SET_DATA_TYPE])); s->flags |= (1 << NFT_SET_ATTR_DATA_TYPE); } if (tb[NFTA_SET_DATA_LEN]) { s->data_len = ntohl(mnl_attr_get_u32(tb[NFTA_SET_DATA_LEN])); s->flags |= (1 << NFT_SET_ATTR_DATA_LEN); } s->family = nfg->nfgen_family; s->flags |= (1 << NFT_SET_ATTR_FAMILY); return ret; } EXPORT_SYMBOL(nft_set_nlmsg_parse); static int nft_set_xml_parse(struct nft_set *s, char *xml) { #ifdef XML_PARSING mxml_node_t *tree; mxml_node_t *node = NULL; struct nft_set_elem *elem; const char *name, *table; int family; tree = mxmlLoadString(NULL, xml, MXML_OPAQUE_CALLBACK); if (tree == NULL) { errno = EINVAL; return -1; } if (strcmp(tree->value.opaque, "set") != 0) goto err; name = nft_mxml_str_parse(tree, "name", MXML_DESCEND_FIRST); if (name == NULL) goto err; if (s->name) xfree(s->name); s->name = strdup(name); s->flags |= (1 << NFT_SET_ATTR_NAME); table = nft_mxml_str_parse(tree, "table", MXML_DESCEND_FIRST); if (table == NULL) goto err; if (s->table) xfree(s->table); s->table = strdup(table); s->flags |= (1 << NFT_SET_ATTR_TABLE); family = nft_mxml_family_parse(tree, "family", MXML_DESCEND_FIRST); if (family < 0) goto err; s->family = family; s->flags |= (1 << NFT_SET_ATTR_FAMILY); if (nft_mxml_num_parse(tree, "flags", MXML_DESCEND_FIRST, BASE_DEC, &s->set_flags, NFT_TYPE_U32) != 0) goto err; s->flags |= (1 << NFT_SET_ATTR_FLAGS); if (nft_mxml_num_parse(tree, "key_type", MXML_DESCEND_FIRST, BASE_DEC, &s->key_type, NFT_TYPE_U32) != 0) goto err; s->flags |= (1 << NFT_SET_ATTR_KEY_TYPE); if (nft_mxml_num_parse(tree, "key_len", MXML_DESCEND_FIRST, BASE_DEC, &s->key_type, NFT_TYPE_U32) != 0) goto err; s->flags |= (1 << NFT_SET_ATTR_KEY_LEN); if (nft_mxml_num_parse(tree, "data_type", MXML_DESCEND_FIRST, BASE_DEC, &s->data_type, NFT_TYPE_U32) != 0) goto err; s->flags |= (1 << NFT_SET_ATTR_DATA_TYPE); if (nft_mxml_num_parse(tree, "data_len", MXML_DESCEND_FIRST, BASE_DEC, &s->data_len, NFT_TYPE_U32) != 0) goto err; s->flags |= (1 << NFT_SET_ATTR_DATA_LEN); for (node = mxmlFindElement(tree, tree, "set_elem", NULL, NULL, MXML_DESCEND); node != NULL; node = mxmlFindElement(node, tree, "set_elem", NULL, NULL, MXML_DESCEND)) { elem = nft_set_elem_alloc(); if (elem == NULL) goto err; if (nft_mxml_set_elem_parse(node, elem) < 0) goto err; list_add_tail(&elem->head, &s->element_list); } mxmlDelete(tree); return 0; err: mxmlDelete(tree); return -1; #else errno = EOPNOTSUPP; return -1; #endif } int nft_set_parse(struct nft_set *s, enum nft_set_parse_type type, char *data) { int ret; switch (type) { case NFT_SET_PARSE_XML: ret = nft_set_xml_parse(s, data); break; default: ret = -1; errno = EOPNOTSUPP; break; } return ret; } EXPORT_SYMBOL(nft_set_parse); static int nft_set_snprintf_json(char *buf, size_t size, struct nft_set *s, uint32_t type, uint32_t flags) { int len = size, offset = 0, ret; struct nft_set_elem *elem; ret = snprintf(buf, size, "{ \"set\": { \"name\": \"%s\"," "\"table\": \"%s\"," "\"flags\": %u,\"family\": \"%s\"," "\"key_type\": %u,\"key_len\": %u", s->name, s->table, s->set_flags, nft_family2str(s->family), s->key_type, s->key_len); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); if(s->flags & (1 << NFT_SET_ATTR_DATA_TYPE) && s->flags & (1 << NFT_SET_ATTR_DATA_LEN)){ ret = snprintf(buf+offset, size, ",\"data_type\": %u,\"data_len\": %u", s->data_type, s->data_len); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); } /* Empty set? Skip printinf of elements */ if (list_empty(&s->element_list)){ ret = snprintf(buf+offset, size, "}}"); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); return offset; } ret = snprintf(buf+offset, size, ",\"set_elem\": ["); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); list_for_each_entry(elem, &s->element_list, head) { ret = snprintf(buf+offset, size, "{"); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); ret = nft_set_elem_snprintf(buf+offset, size, elem, type, flags); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); ret = snprintf(buf+offset, size, "}, "); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); } ret = snprintf(buf+offset-2, size, "]}}"); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); return offset; } static int nft_set_snprintf_default(char *buf, size_t size, struct nft_set *s, uint32_t type, uint32_t flags) { int ret; int len = size, offset = 0; struct nft_set_elem *elem; ret = snprintf(buf, size, "%s %s %x", s->name, s->table, s->set_flags); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); /* Empty set? Skip printinf of elements */ if (list_empty(&s->element_list)) return offset; ret = snprintf(buf+offset, size, "\n"); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); list_for_each_entry(elem, &s->element_list, head) { ret = snprintf(buf+offset, size, "\t"); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); ret = nft_set_elem_snprintf(buf+offset, size, elem, type, flags); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); } return offset; } static int nft_set_snprintf_xml(char *buf, size_t size, struct nft_set *s, uint32_t flags) { int ret; int len = size, offset = 0; struct nft_set_elem *elem; ret = snprintf(buf, size, "<set><family>%s</family>" "<table>%s</table>" "<name>%s</name>" "<flags>%u</flags>" "<key_type>%u</key_type>" "<key_len>%u</key_len>" "<data_type>%u</data_type>" "<data_len>%u</data_len>", nft_family2str(s->family), s->table, s->name, s->set_flags, s->key_type, s->key_len, s->data_type, s->data_len); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); if (!list_empty(&s->element_list)) { list_for_each_entry(elem, &s->element_list, head) { ret = nft_set_elem_snprintf(buf+offset, size, elem, NFT_SET_O_XML, flags); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); } } ret = snprintf(buf+offset, size, "</set>"); SNPRINTF_BUFFER_SIZE(ret, size, len, offset); return offset; } int nft_set_snprintf(char *buf, size_t size, struct nft_set *s, uint32_t type, uint32_t flags) { switch(type) { case NFT_SET_O_DEFAULT: return nft_set_snprintf_default(buf, size, s, type, flags); case NFT_SET_O_XML: return nft_set_snprintf_xml(buf, size, s, flags); case NFT_SET_O_JSON: return nft_set_snprintf_json(buf, size, s, type, flags); default: break; } return -1; } EXPORT_SYMBOL(nft_set_snprintf); void nft_set_elem_add(struct nft_set *s, struct nft_set_elem *elem) { list_add_tail(&elem->head, &s->element_list); } EXPORT_SYMBOL(nft_set_elem_add); struct nft_set_list { struct list_head list; }; struct nft_set_list *nft_set_list_alloc(void) { struct nft_set_list *list; list = calloc(1, sizeof(struct nft_set_list)); if (list == NULL) return NULL; INIT_LIST_HEAD(&list->list); return list; } EXPORT_SYMBOL(nft_set_list_alloc); void nft_set_list_free(struct nft_set_list *list) { struct nft_set *s, *tmp; list_for_each_entry_safe(s, tmp, &list->list, head) { list_del(&s->head); nft_set_free(s); } xfree(list); } EXPORT_SYMBOL(nft_set_list_free); int nft_set_list_is_empty(struct nft_set_list *list) { return list_empty(&list->list); } EXPORT_SYMBOL(nft_set_list_is_empty); void nft_set_list_add(struct nft_set *s, struct nft_set_list *list) { list_add(&s->head, &list->list); } EXPORT_SYMBOL(nft_set_list_add); void nft_set_list_add_tail(struct nft_set *s, struct nft_set_list *list) { list_add_tail(&s->head, &list->list); } EXPORT_SYMBOL(nft_set_list_add_tail); int nft_set_list_foreach(struct nft_set_list *set_list, int (*cb)(struct nft_set *t, void *data), void *data) { struct nft_set *cur, *tmp; int ret; list_for_each_entry_safe(cur, tmp, &set_list->list, head) { ret = cb(cur, data); if (ret < 0) return ret; } return 0; } EXPORT_SYMBOL(nft_set_list_foreach); struct nft_set_list_iter { struct nft_set_list *list; struct nft_set *cur; }; struct nft_set_list_iter *nft_set_list_iter_create(struct nft_set_list *l) { struct nft_set_list_iter *iter; iter = calloc(1, sizeof(struct nft_set_list_iter)); if (iter == NULL) return NULL; iter->list = l; iter->cur = list_entry(l->list.next, struct nft_set, head); return iter; } EXPORT_SYMBOL(nft_set_list_iter_create); struct nft_set *nft_set_list_iter_cur(struct nft_set_list_iter *iter) { return iter->cur; } EXPORT_SYMBOL(nft_set_list_iter_cur); struct nft_set *nft_set_list_iter_next(struct nft_set_list_iter *iter) { struct nft_set *s = iter->cur; /* get next rule, if any */ iter->cur = list_entry(iter->cur->head.next, struct nft_set, head); if (&iter->cur->head == iter->list->list.next) return NULL; return s; } EXPORT_SYMBOL(nft_set_list_iter_next); void nft_set_list_iter_destroy(struct nft_set_list_iter *iter) { xfree(iter); } EXPORT_SYMBOL(nft_set_list_iter_destroy);
__label__pos
0.967259
[pmwiki-devel] More database standards Crisses crisses at kinhost.org Wed Dec 13 17:23:12 CST 2006 On Dec 13, 2006, at 2:11 PM, marc wrote: > I know that most folk aren't using a database, and probably very > few are > using more than one, but I'd like to pin down how we communicate the > active connection name to recipes even for a single db. > > A connection is usually defined in (farm)config.php by: > > $Databases['connection_name'] = array(... > > where connection_name is arbitrary. This means that when a recipe > needs > it - to perform some db action - the connection name must be somehow > passed to the recipe. One could pass it around in parameters, but that > is horribly messy. Worse, when dealing with objects, it's not really > viable at all. What's not viable? You can't pass object pointers to objects? I've called objects inside objects, and I'm not understanding why creating an object in an object is ok but you can't pass objects or object pointers.... I'm not sure I've tried, though. > To complicate matters, where there is more than one database, you > could > be passing around multiple connection names. In addition, how is a > recipe writer to cater for the situation where one table comes from > one > db and a second from another? And perhaps a third. Or a fourth. > > Is there a proposed solution for this? I don't know. I know how I've handled it for AuthUserDBase so far. I've used SDVA and given a sample sql script for how to set up the database, but only for the standalone version. The very nature of AuthUserDBase was to share the login settings of another database already managed by another program (say vBulletin, Joomla!, Drupal, Moodle.....or now, with ADOdb, maybe even LDAP?). I had to set default values, but allow people to change them. I've added a hook for an admin-created function to do the encryption for the database, since I can't predict the encryption methods used by every program out there, and the vBulletin one was double MD5 with a salt. So, I suggest you wrap your definitions in SDVA for arrays, SDV for variables, and let the admin sort it out, get something into a testing phase, document what you can, and get feedback from people. The better documented, and the more hooks, the more likely people can actually use it and you'll get good feedback. Crisses More information about the pmwiki-devel mailing list
__label__pos
0.562838
PHP min() - Math Functions What is min Function? Explanation The "min()" function returns the lowest value among the two numbers given. Syntax: min(x,y) In the above syntax "x","y" are the numbers to be compared to find the lowest value. Example : <?php echo(max(4,8) . "<br />"); echo(max(-4,7) . "<br />"); echo(max(-2,-6) . "<br />"); echo(max(8.30,8.40)) ?> Result : 4 -4 -6 8.3 In the above example the lowest values among the numbers are displayed. PHP Topics Ask Questions Ask Question
__label__pos
0.969633
/* Check whether cpowl can be linked. This is for the benefit of Straberry Perl versions 5.12.x, where a gcc bug renders cpow() unusable, but cpowl() works fine */ #include <stdio.h> #include <math.h> #include <complex.h> #include <math.h> int main(void) { double _Complex rop, op; __real__ op = 0.6; __imag__ op = 0.5; rop = (double _Complex)cpowl(op, op); return 0; }
__label__pos
0.851891
聊天室 环信聊天室模型支持最大成员数为5000,和群组不同,聊天室内成员离线后,服务器当监听到此成员不在线后不在会给此成员再发推送。 • 支持最大成员5000; • 环信的聊天室内仅有 owner 和游客; • 不支持客户端建立聊天室; • 不支持客户端邀请; • 不支持 REST 邀请。 服务器端 创建聊天室 curl -X POST “http://a1.easemob.com/easemob-demo/chatdemoui/chatrooms” -H “Authorization: Bearer ${token}” -d ‘{“owner”:”u1”,”members”:[“u1”,”u2”],”maxusers”:5000,”groupname”:”chatroom title”,”desc”:”chatroom description”}” 查询所有 APP 聊天室 curl -X GET “http://a1.easemob.com/easemob-demo/chatdemoui/chatrooms” -H “Authorization: Bearer ${token}” 查询聊天室详情 curl -X GET “http://a1.easemob.com/easemob-demo/chatdemoui/chatrooms/1430798028680235” -H “Authorization: Bearer ${token}” 聊天室踢人 curl -X DELETE ‘https://a1.easemob.com/easemob-demo/chatdemoui/chatrooms/1430798028680235/users/u2’ -H “Authorization: Bearer ${token}” 删除聊天室 curl -X DELETE ‘https://a1.easemob.com/easemob-demo/chatdemoui/chatrooms/143228117786605’ -H “Authorization: Bearer ${token}” 更多REST操作请参考 聊天室管理 客户端 • 支持查询所有 APP 聊天室; • 支持查询聊天室详情; • 加入聊天室; • 退出聊天室; • 客户端的 API 都是通过 EMChatManager 获取。 加入聊天室 public void joinChatRoom(final String roomId, final EMValueCallBack<EMChatRoom> callback) 参数: • roomId: 聊天室 ID,一般都会从自己 APP 的后台获取。 • callback: EMValueCallBack<EMChatRoom> 加入成功返回聊天室简要信息,加入失败返回 error。 示例: public void onChatroomViewCreation{ findViewById(R.id.container_to_group).setVisibility(View.GONE); final ProgressDialog pd = ProgressDialog.show(this, "", "Joining......"); EMChatManager.getInstance().joinChatRoom(toChatUsername, new EMValueCallBack<EMChatRoom>() { @Override public void onSuccess(EMChatRoom value) { runOnUiThread(new Runnable(){ @Override public void run(){ pd.dismiss(); room = EMChatManager.getInstance().getChatRoom(toChatUsername); if(room !=null){ ((TextView) findViewById(R.id.name)).setText(room.getName()); }else{ ((TextView) findViewById(R.id.name)).setText(toChatUsername); } EMLog.d(TAG, "join room success : " + room.getName()); onConversationInit(); onListViewCreation(); } }); } @Override public void onError(final int error, String errorMsg) { EMLog.d(TAG, "join room failure : " + error); runOnUiThread(new Runnable(){ @Override public void run(){ pd.dismiss(); } }); finish(); } }); } protected void onConversationInit(){ if(chatType == CHATTYPE_SINGLE){ conversation = EMChatManager.getInstance().getConversationByType(toChatUsername,EMConversationType.Chat); }else if(chatType == CHATTYPE_GROUP){ conversation = EMChatManager.getInstance().getConversationByType(toChatUsername,EMConversationType.GroupChat); }else if(chatType == CHATTYPE_CHATROOM){ conversation = EMChatManager.getInstance().getConversationByType(toChatUsername,EMConversationType.ChatRoom); } // 把此会话的未读数置为0 conversation.markAllMessagesAsRead(); // 初始化db时,每个conversation加载数目是getChatOptions().getNumberOfMessagesLoaded // 这个数目如果比用户期望进入会话界面时显示的个数不一样,就多加载一些 final List<EMMessage> msgs = conversation.getAllMessages(); int msgCount = msgs != null ? msgs.size() : 0; if (msgCount < conversation.getAllMsgCount() && msgCount < pagesize) { String msgId = null; if (msgs != null && msgs.size() > 0) { msgId = msgs.get(0).getMsgId(); } if (chatType == CHATTYPE_SINGLE) { conversation.loadMoreMsgFromDB(msgId, pagesize); } else { conversation.loadMoreGroupMsgFromDB(msgId, pagesize); } } // 监听聊天室变化回调 EMChatManager.getInstance().addChatRoomChangeListener(new EMChatRoomChangeListener(){ @Override public void onInvitationReceived(String roomId, String roomName, String inviter, String reason) { } @Override public void onChatRoomDestroyed(String roomId, String roomName) { if(roomId.equals(toChatUsername)){ finish(); } } @Override public void onMemberJoined(String roomId, String participant) { } @Override public void onMemberExited(String roomId, String roomName, String participant) { } @Override public void onMemberKicked(String roomId, String roomName, String participant) { if(roomId.equals(toChatUsername)){ String curUser = EMChatManager.getInstance().getCurrentUser(); if(curUser.equals(participant)){ EMChatManager.getInstance().leaveChatRoom(toChatUsername); finish(); } } } }); } 请注意对于聊天室模型,请一定要等到 Join 回调成功后再去初始化 conversation。 离开聊天室 public void leaveChatRoom(String roomId) 参数: roomId: 要退出的聊天室的ID。 此方法是异步方法,不会阻塞当前线程。此方法没有回调,原因是在任何场景下退出聊天室,SDK 保证退出成功,无论有网出错,还是无网退出。对于聊天室模型,一般退出会话页面,就会调用此 leave 方法。 public EMCursorResult<EMChatRoom> fetchPublicChatRoomsFromServer(int pageSize, String cursor) throws EaseMobException 参数: • pageSize: 此次获取的条目。 • cursor: 后台需要的 cursor id,根据此 Id 再次获取 pageSize 的条目,首次传 null 即可。 返回值: EMCursorResult<EMChatRoom> 内部包含返回的 cursor,和 List<EMChatRoom>。 获取所有聊天室信息 获取所有环信的聊天室信息,包括聊天室 ID 和名称。 public EMChatRoom fetchChatRoomFromServer(String roomId) throws EaseMobException 获取聊天室详情 聊天室回调监听 public interface EMChatRoomChangeListener { /** * 聊天室被解散。 * * @param roomId * 聊天室id * @param roomName * 聊天室名称 */ void onChatRoomDestroyed(String roomId, String roomName); /** * 聊天室加入新成员事件 * * @param roomId * 聊天室id * @param participant * 新成员username */ void onMemberJoined(String roomId, String participant); /** * 聊天室成员主动退出事件 * * @param roomId * 聊天室id * @param roomName * 聊天室名字 * @param participant * 退出的成员的username */ void onMemberExited(String roomId, String roomName, String participant); /** * 聊天室人员被移除 * * @param roomId * 聊天室id *@param roomName * 聊天室名字 * @param participant * 被移除人员的username */ void onMemberKicked(String roomId, String roomName, String participant); } 应用可以通过注册聊天室监听,进行对UI的刷新。 public void addChatRoomChangeListener(EMChatRoomChangeListener listener) 注册聊天室监听 在会话页面注册监听,来监听成员被踢和聊天室被删除。 EMChatManager.getInstance().addChatRoomChangeListener(new EMChatRoomChangeListener(){ @Override public void onChatRoomDestroyed(String roomId, String roomName) { if(roomId.equals(toChatUsername)){ finish(); } } @Override public void onMemberJoined(String roomId, String participant) { } @Override public void onMemberExited(String roomId, String roomName, String participant) { } @Override public void onMemberKicked(String roomId, String roomName, String participant) { if(roomId.equals(toChatUsername)){ finish(); } } }); 移除聊天室监听 public void removeChatRoomChangeListener(EMChatRoomChangeListener listener) 上一页:群组管理 下一页:实时通话
__label__pos
0.602656
Login django-mptt enabled FilteredSelectMultiple m2m widget Author: anentropic Posted: November 5, 2009 Language: Python Version: 1.1 Tags: widget mptt Score: 0 (after 0 ratings) If you are using django-mptt to manage content (eg heirarchical categories) then it needs a bit of help to make a nice admin interface. For many-to-many fields, Django provides the quite nice FilteredSelectMultiple widget (a two-pane selection list with search box) but it only renders 'flat' lists... if you have a big category tree it's going to be confusing to know what belongs to what. Also, list items are sorted alphabetically in the js, which won't be what you want. This snippet extends FilteredSelectMultiple to show the tree structure in the list. You'll also need the js from this snippet: #1780 For usage details see my blog at: http://anentropic.wordpress.com 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 from itertools import chain from django import forms from django.conf import settings from django.contrib.admin import widgets from django.utils.encoding import smart_unicode, force_unicode from django.utils.safestring import mark_safe from django.utils.html import escape, conditional_escape class MPTTModelChoiceIterator(forms.models.ModelChoiceIterator): def choice(self, obj): tree_id = getattr(obj, getattr(self.queryset.model._meta, 'tree_id_atrr', 'tree_id'), 0) left = getattr(obj, getattr(self.queryset.model._meta, 'left_atrr', 'lft'), 0) return super(MPTTModelChoiceIterator, self).choice(obj) + ((tree_id, left),) class MPTTModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): level = getattr(obj, getattr(self.queryset.model._meta, 'level_attr', 'level'), 0) return u'%s %s' % ('-'*level, smart_unicode(obj)) def _get_choices(self): if hasattr(self, '_choices'): return self._choices return MPTTModelChoiceIterator(self) choices = property(_get_choices, forms.ChoiceField._set_choices) class MPTTFilteredSelectMultiple(widgets.FilteredSelectMultiple): def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): super(MPTTFilteredSelectMultiple, self).__init__(verbose_name, is_stacked, attrs, choices) def render_options(self, choices, selected_choices): """ this is copy'n'pasted from django.forms.widgets Select(Widget) change to the for loop and render_option so they will unpack and use our extra tuple of mptt sort fields (if you pass in some default choices for this field, make sure they have the extra tuple too!) """ def render_option(option_value, option_label, sort_fields): option_value = force_unicode(option_value) selected_html = (option_value in selected_choices) and u' selected="selected"' or '' return u'<option value="%s" data-tree-id="%s" data-left-value="%s"%s>%s</option>' % ( escape(option_value), sort_fields[0], sort_fields[1], selected_html, conditional_escape(force_unicode(option_label)), ) # Normalize to strings. selected_choices = set([force_unicode(v) for v in selected_choices]) output = [] for option_value, option_label, sort_fields in chain(self.choices, choices): if isinstance(option_label, (list, tuple)): output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value))) for option in option_label: output.append(render_option(*option)) output.append(u'</optgroup>') else: output.append(render_option(option_value, option_label, sort_fields)) return u'\n'.join(output) class Media: extend = False js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js", settings.MEDIA_URL + "js/mptt_m2m_selectbox.js", settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js", ) More like this 1. django-mptt enabled replacement for SelectBox.js by anentropic 5 years, 4 months ago 2. MPTTModelAdmin by anentropic 5 years, 5 months ago 3. Ajax auto-filtered Foreign Key Field by anentropic 5 years, 4 months ago 4. Convert multiple select for m2m to multiple checkboxes in django admin form by abidibo 1 year, 11 months ago 5. Many 2 Many Admin Ordering with Mysql by visik7 1 year, 7 months ago Comments Please login first before commenting.
__label__pos
0.565527
skip to navigation skip to content django-polymorphic-tree 0.8.7 A polymorphic mptt structure to display content in a tree. Latest Version: 1.2.5 django-polymorphic-tree This is a stand alone module, which provides: ” A polymorphic structure to display content in a tree. “ In other words, this module provides a node tree, where each node can be a different model type. This allows you to freely structure tree data. For example: • Build a tree of a root node, category nodes, leaf nodes, each with custom fields. • Build a todo list of projects, categories and items. • Build a book of chapters, sections, and pages. Origin This module was extracted out of django-fluent-pages because it turned out to serve a generic purpose. This was done during contract work at Leukeleu (also known for their involvement in django-fiber). Installation First install the module, preferably in a virtual environment: pip install django-polymorphic-tree Or install the current repository: pip install -e git+https://github.com/edoburu/django-polymorphic-tree.git#egg=django-polymorphic-tree The main dependencies are django-mptt and django-polymorphic, which will be automatically installed. Configuration Next, create a project which uses the application: cd .. django-admin.py startproject demo Add the following to settings.py: INSTALLED_APPS += ( 'polymorphic_tree', 'polymorphic', 'mptt', ) Usage The main feature of this module is creating a tree of custom node types. It boils down to creating a application with 2 files: The models.py file should define the custom node type, and any fields it has: from django.db import models from django.utils.translation import ugettext_lazy as _ from polymorphic_tree.models import PolymorphicMPTTModel, PolymorphicTreeForeignKey # A base model for the tree: class BaseTreeNode(PolymorphicMPTTModel): parent = PolymorphicTreeForeignKey('self', blank=True, null=True, related_name='children', verbose_name=_('parent')) title = models.CharField(_("Title"), max_length=200) class Meta: verbose_name = _("Tree node") verbose_name_plural = _("Tree nodes") # Create 3 derived models for the tree nodes: class CategoryNode(BaseTreeNode): opening_title = models.CharField(_("Opening title"), max_length=200) opening_image = models.ImageField(_("Opening image"), upload_to='images') class Meta: verbose_name = _("Category node") verbose_name_plural = _("Category nodes") class TextNode(BaseTreeNode): extra_text = models.TextField() # Extra settings: can_have_children = False class Meta: verbose_name = _("Text node") verbose_name_plural = _("Text nodes") class ImageNode(BaseTreeNode): image = models.ImageField(_("Image"), upload_to='images') class Meta: verbose_name = _("Image node") verbose_name_plural = _("Image nodes") The admin.py file should define the admin, both for the child nodes and parent: from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from polymorphic_tree.admin import PolymorphicMPTTParentModelAdmin, PolymorphicMPTTChildModelAdmin from . import models # The common admin functionality for all derived models: class BaseChildAdmin(PolymorphicMPTTChildModelAdmin): GENERAL_FIELDSET = (None, { 'fields': ('parent', 'title'), }) base_model = models.BaseTreeNode base_fieldsets = ( GENERAL_FIELDSET, ) # Optionally some custom admin code class TextNodeAdmin(BaseChildAdmin): pass # Create the parent admin that combines it all: class TreeNodeParentAdmin(PolymorphicMPTTParentModelAdmin): base_model = models.BaseTreeNode child_models = ( (models.CategoryNode, BaseChildAdmin), (models.TextNode, TextNodeAdmin), # custom admin allows custom edit/delete view. (models.ImageNode, BaseChildAdmin), ) list_display = ('title', 'actions_column',) class Media: css = { 'all': ('admin/treenode/admin.css',) } admin.site.register(models.BaseTreeNode, TreeNodeParentAdmin) The child_models attribute defines which admin interface is loaded for hte edit and delete page. The list view is still rendered by the parent admin. Todo • Sphinx Documentation • Unit tests • Example app • A final review of class names (hence the alpha version tag, but we will provide aliases for the old names) • Getting the polymorphic-admin code merged upstream back into django-polymorphic (see pull request #10). Contributing This module is designed to be generic. In case there is anything you didn’t like about it, or think it’s not flexible enough, please let us know. We’d love to improve it! If you have any other valuable contribution, suggestion or idea, please let us know as well because we will look into it. Pull requests are welcome too. :-)   File Type Py Version Uploaded on Size django-polymorphic-tree-0.8.7.tar.gz (md5) Source 2013-05-28 49KB
__label__pos
0.924558
1 $\begingroup$ Say we have a pandas series with the following values [np.nan, np.nan, 1, np.nan, 2, np.nan] What is the most efficient way fill the nan value with 0 in the middle. so we have [np.nan, np.nan, 1, 0, 2, np.nan] In other word, how to we do interpolation with a fixed value, or a .fillna operation but ignore the nan at the beginning and end of the array. $\endgroup$ 3 $\begingroup$ Current solution, I am using def interpolate_with_fixed(s, value=0): i = s.first_valid_index() j = s.last_valid_index() s.loc[i:j].fillna(value, inplace=True) return s |improve this answer||||| $\endgroup$ • $\begingroup$ This my hackish solution. Would like to know if there is a more elegent solution. $\endgroup$ – Louis T Nov 16 '17 at 5:06 1 $\begingroup$ I think your solution is quite idiomatic. Here is an alternative solution: In [355]: s.loc[s.notnull().idxmax() : s[::-1].notnull().idxmax()].fillna(0, inplace=True) In [356]: s Out[356]: 0 NaN 1 NaN 2 1.0 3 0.0 4 2.0 5 NaN dtype: float64 |improve this answer||||| $\endgroup$ Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.543295
#1 1. No Profile Picture Registered User Devshed Newbie (0 - 499 posts) Join Date Oct 2009 Posts 17 Rep Power 0 Simple XPath Query Raises Exception Why does the following line of code raise a "SyntaxError: invalid predicate" exception? Code: root.find("def/hij[text()=klm]") My simple code is: Code: import xml.etree.ElementTree as ET tree = ET.parse("testXML.xml") root = tree.getroot() # root = "abc/" element (ie, main element) test = root.find("def/hij") # Does not raise exception test = root.find("def/hij[text()=klm]") # raises exception My XML file: Code: <abc> <def> <hij>blah</hij> <hij>klm</hij> </def> </abc> 2. #2 3. Contributing User Join Date Aug 2011 Posts 5,043 Rep Power 482 I'd say you get that syntax error because etree doesn't support that syntax. http://docs.python.org/3/library/xml...d-xpath-syntax Maybe it works with expat [code]Code tags[/code] are essential for python code and Makefiles! IMN logo majestic logo threadwatch logo seochat tools logo
__label__pos
0.973483
0 $\begingroup$ Why does the following limit not exist? $$ \lim_{x \to 3} \left(x^2-5x+4\right)^{x-3} $$ The base tends to $-2$ while the exponent tends to $0$. According to me the limit should be $1$, but the solution given for the problem says that the limit does not exist. Which is the correct answer? $\endgroup$ • 3 $\begingroup$ The limit does not exist because the function is not defined on a neighborhood of 3. $\endgroup$ – Did Dec 21 '18 at 16:39 • 4 $\begingroup$ Because the base is negative in a neighborhood of 3 hence raising it to a noninteger power cannot be done. $\endgroup$ – Did Dec 21 '18 at 16:42 • 7 $\begingroup$ @Dr.SonnhardGraubner: For any choice of the branch of log to be used, the limit would be $1$, but we don't know if we can use complex analysis or not. Certainly no mention of complex analysis was made. $\endgroup$ – robjohn Dec 21 '18 at 16:49 • 2 $\begingroup$ @Did Technically, $3$ is a limit point of and belongs to the domain. The $\varepsilon-\delta$ definition of limit doesn't require $x\mapsto (x^2-5x+4)^{x-3}$ to be defined in the entire deleted $\delta$ neighbourhood of $3$ $\endgroup$ – Shubham Johri Dec 21 '18 at 18:11 • 4 $\begingroup$ If you interpret the function as having domain $(-\infty, 1) \cup [(1, 4) \cap \mathbb{Z}_{(2)}] \cup [4, \infty)$ then the limit as $x\to 3$ does not exist (nor does either one-sided limit): 3 is a cluster point of the numbers $p/q$ with $p$ even and $q$ odd for which the limit approaches 1, and also a cluster point of the numbers $p/q$ with $p$ odd and $q$ odd for which the limit approaches $-1$. $\endgroup$ – Daniel Schepler Dec 21 '18 at 19:26 8 $\begingroup$ The quadratic $x^2-5x+4$ factorises as $(x-4)(x-1)$. If $x$ is in a small neighbourhood of $3$ then $x-4<0$ and $x-1>0$, so $x^2-5x+4 < 0$. This means that we run into issues with even defining the quantity $(x^2-5x+4)^{x-3}$ when, say, $x = 3 \pm \dfrac{1}{2n}$ for some positive integer $n$. This is bad news for the limit as $x \to 3$. | cite | improve this answer | | $\endgroup$ • $\begingroup$ Wait so is the problem due to the base being negative, or the power tending to 0? $\endgroup$ – Pranav Aggarwal Dec 21 '18 at 16:45 • $\begingroup$ If I change the questions to lim x tends to 3 (x^2-5x+4)^(x-2), the answer would be -2 right? $\endgroup$ – Pranav Aggarwal Dec 21 '18 at 16:45 • 1 $\begingroup$ @Pranav: The issue is that the base is negative, since in the limit you are required to take fractional powers in a neighbourhood of the limit. You run into the same issue if you replace the $x-3$ by $x-2$ (or $x-a$ for any $a$), so it is not the case that $\lim_{x \to 3} (x^3-5x+4)^{x-2} = -2$. You can evaluate $(x^3-5x+4)^{x-2}$ when $x=3$, and you get $-2$, but that is not the limit as $x \to 3$, since the quantity isn't even defined everywhere in an open interval about $2$ (or indeed any real number). $\endgroup$ – Clive Newstead Dec 21 '18 at 16:50 • 1 $\begingroup$ ...this is ignoring complex numbers, of course. Taking the limit over $\mathbb{C}$ you need to consider different branch cuts of the complex plane to figure out how to define the quantity with non-integral exponents. $\endgroup$ – Clive Newstead Dec 21 '18 at 16:53 • 1 $\begingroup$ @CliveNewstead am I right in thinking magnitude limits to $1$ although the sign is ambiguous? So the absolute value of the expression has a limit. $\endgroup$ – samerivertwice Dec 23 '18 at 4:25 Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.897278
Perl - Quick Guide Advertisements Perl - Introduction Perl is a general-purpose programming language originally developed for text manipulation and now used for a wide range of tasks including system administration, web development, network programming, GUI development, and more. What is Perl? • Perl is a stable, cross platform programming language. • Though Perl is not officially an acronym but few people used it as Practical Extraction and Report Language. • It is used for mission critical projects in the public and private sectors. • Perl is an Open Source software, licensed under its Artistic License, or the GNU General Public License (GPL). • Perl was created by Larry Wall. • Perl 1.0 was released to usenet's alt.comp.sources in 1987. • At the time of writing this tutorial, the latest version of perl was 5.16.2. • Perl is listed in the Oxford English Dictionary. PC Magazine announced Perl as the finalist for its 1998 Technical Excellence Award in the Development Tool category. Perl Features • Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC, among others. • Perls database integration interface DBI supports third-party databases including Oracle, Sybase, Postgres, MySQL and others. • Perl works with HTML, XML, and other mark-up languages. • Perl supports Unicode. • Perl is Y2K compliant. • Perl supports both procedural and object-oriented programming. • Perl interfaces with external C/C++ libraries through XS or SWIG. • Perl is extensible. There are over 20,000 third party modules available from the Comprehensive Perl Archive Network (CPAN). • The Perl interpreter can be embedded into other systems. Perl and the Web • Perl used to be the most popular web programming language due to its text manipulation capabilities and rapid development cycle. • Perl is widely known as "the duct-tape of the Internet". • Perl can handle encrypted Web data, including e-commerce transactions. • Perl can be embedded into web servers to speed up processing by as much as 2000%. • Perl's mod_perl allows the Apache web server to embed a Perl interpreter. • Perl's DBI package makes web-database integration easy. Perl is Interpreted Perl is an interpreted language, which means that your code can be run as is, without a compilation stage that creates a non portable executable program. Traditional compilers convert programs into machine language. When you run a Perl program, it's first compiled into a byte code, which is then converted ( as the program runs) into machine instructions. So it is not quite the same as shells, or Tcl, which are strictly interpreted without an intermediate representation. It is also not like most versions of C or C++, which are compiled directly into a machine dependent format. It is somewhere in between, along with Python and awk and Emacs .elc files. Perl - Environment Before we start writing our Perl programs, let's understand how to setup our Perl environment. Perl is available on a wide variety of platforms − • Unix (Solaris, Linux, FreeBSD, AIX, HP/UX, SunOS, IRIX etc.) • Win 9x/NT/2000/ • WinCE • Macintosh (PPC, 68K) • Solaris (x86, SPARC) • OpenVMS • Alpha (7.2 and later) • Symbian • Debian GNU/kFreeBSD • MirOS BSD • And many more... This is more likely that your system will have perl installed on it. Just try giving the following command at the $ prompt − $perl -v If you have perl installed on your machine, then you will get a message something as follows − This is perl 5, version 16, subversion 2 (v5.16.2) built for i686-linux Copyright 1987-2012, Larry Wall Perl may be copied only under the terms of either the Artistic License or the GNU General Public License, which may be found in the Perl 5 source kit. Complete documentation for Perl, including FAQ lists, should be found on this system using "man perl" or "perldoc perl". If you have access to the Internet, point your browser at http://www.perl.org/, the Perl Home Page. If you do not have perl already installed, then proceed to the next section. Getting Perl Installation The most up-to-date and current source code, binaries, documentation, news, etc. are available at the official website of Perl. Perl Official Websitehttps://www.perl.org/ You can download Perl documentation from the following site. Perl Documentation Websitehttps://perldoc.perl.org Install Perl Perl distribution is available for a wide variety of platforms. You need to download only the binary code applicable for your platform and install Perl. If the binary code for your platform is not available, you need a C compiler to compile the source code manually. Compiling the source code offers more flexibility in terms of choice of features that you require in your installation. Here is a quick overview of installing Perl on various platforms. Unix and Linux Installation Here are the simple steps to install Perl on Unix/Linux machine. • Open a Web browser and go to https://www.perl.org/get.html. • Follow the link to download zipped source code available for Unix/Linux. • Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt. $tar -xzf perl-5.x.y.tar.gz $cd perl-5.x.y $./Configure -de $make $make test $make install NOTE − Here $ is a Unix prompt where you type your command, so make sure you are not typing $ while typing the above mentioned commands. This will install Perl in a standard location /usr/local/bin and its libraries are installed in /usr/local/lib/perlXX, where XX is the version of Perl that you are using. It will take a while to compile the source code after issuing the make command. Once installation is done, you can issue perl -v command at $ prompt to check perl installation. If everything is fine, then it will display message like we have shown above. Windows Installation Here are the steps to install Perl on Windows machine. • Follow the link for the Strawberry Perl installation on Windows http://strawberryperl.com • Download either 32bit or 64bit version of installation. • Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Perl install wizard, which is really easy to use. Just accept the default settings, wait until the installation is finished, and you're ready to roll! Macintosh Installation In order to build your own version of Perl, you will need 'make', which is part of the Apples developer tools usually supplied with Mac OS install DVDs. You do not need the latest version of Xcode (which is now charged for) in order to install make. Here are the simple steps to install Perl on Mac OS X machine. • Open a Web browser and go to https://www.perl.org/get.html. • Follow the link to download zipped source code available for Mac OS X. • Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt. $tar -xzf perl-5.x.y.tar.gz $cd perl-5.x.y $./Configure -de $make $make test $make install This will install Perl in a standard location /usr/local/bin and its libraries are installed in /usr/local/lib/perlXX, where XX is the version of Perl that you are using. Running Perl The following are the different ways to start Perl. Interactive Interpreter You can enter perl and start coding right away in the interactive interpreter by starting it from the command line. You can do this from Unix, DOS, or any other system, which provides you a command-line interpreter or shell window. $perl -e <perl code> # Unix/Linux or C:>perl -e <perl code> # Windows/DOS Here is the list of all the available command line options − Sr.No. Option & Description 1 -d[:debugger] Runs program under debugger 2 -Idirectory Specifies @INC/#include directory 3 -T Enables tainting checks 4 -t Enables tainting warnings 5 -U Allows unsafe operations 6 -w Enables many useful warnings 7 -W Enables all warnings 8 -X Disables all warnings 9 -e program Runs Perl script sent in as program 10 file Runs Perl script from a given file Script from the Command-line A Perl script is a text file, which keeps perl code in it and it can be executed at the command line by invoking the interpreter on your application, as in the following − $perl script.pl # Unix/Linux or C:>perl script.pl # Windows/DOS Integrated Development Environment You can run Perl from a graphical user interface (GUI) environment as well. All you need is a GUI application on your system that supports Perl. You can download Padre, the Perl IDE. You can also use Eclipse Plugin EPIC - Perl Editor and IDE for Eclipse if you are familiar with Eclipse. Before proceeding to the next chapter, make sure your environment is properly setup and working perfectly fine. If you are not able to setup the environment properly then you can take help from your system admininstrator. All the examples given in subsequent chapters have been executed with v5.16.2 version available on the CentOS flavor of Linux. Perl - Syntax Overview Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. However, there are some definite differences between the languages. This chapter is designd to quickly get you up to speed on the syntax that is expected in Perl. A Perl program consists of a sequence of declarations and statements, which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code. Every simple statement must end with a semicolon (;). Perl is a free-form language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial. First Perl Program Interactive Mode Programming You can use Perl interpreter with -e option at command line, which lets you execute Perl statements from the command line. Let's try something at $ prompt as follows − $perl -e 'print "Hello World\n"' This execution will produce the following result − Hello, world Script Mode Programming Assuming you are already on $ prompt, let's open a text file hello.pl using vi or vim editor and put the following lines inside your file. #!/usr/bin/perl # This will print "Hello, World" print "Hello, world\n"; Here /usr/bin/perl is actual the perl interpreter binary. Before you execute your script, be sure to change the mode of the script file and give execution priviledge, generally a setting of 0755 works perfectly and finally you execute the above script as follows − $chmod 0755 hello.pl $./hello.pl This execution will produce the following result − Hello, world You can use parentheses for functions arguments or omit them according to your personal taste. They are only required occasionally to clarify the issues of precedence. Following two statements produce the same result. print("Hello, world\n"); print "Hello, world\n"; Perl File Extension A Perl script can be created inside of any normal simple-text editor program. There are several programs available for every type of platform. There are many programs designd for programmers available for download on the web. As a Perl convention, a Perl file must be saved with a .pl or .PL file extension in order to be recognized as a functioning Perl script. File names can contain numbers, symbols, and letters but must not contain a space. Use an underscore (_) in places of spaces. Comments in Perl Comments in any programming language are friends of developers. Comments can be used to make program user friendly and they are simply skipped by the interpreter without impacting the code functionality. For example, in the above program, a line starting with hash # is a comment. Simply saying comments in Perl start with a hash symbol and run to the end of the line − # This is a comment in perl Lines starting with = are interpreted as the start of a section of embedded documentation (pod), and all subsequent lines until the next =cut are ignored by the compiler. Following is the example − #!/usr/bin/perl # This is a single line comment print "Hello, world\n"; =begin comment This is all part of multiline comment. You can use as many lines as you like These comments will be ignored by the compiler until the next =cut is encountered. =cut This will produce the following result − Hello, world Whitespaces in Perl A Perl program does not care about whitespaces. Following program works perfectly fine − #!/usr/bin/perl print "Hello, world\n"; But if spaces are inside the quoted strings, then they would be printed as is. For example − #!/usr/bin/perl # This would print with a line break in the middle print "Hello world\n"; This will produce the following result − Hello world All types of whitespace like spaces, tabs, newlines, etc. are equivalent for the interpreter when they are used outside of the quotes. A line containing only whitespace, possibly with a comment, is known as a blank line, and Perl totally ignores it. Single and Double Quotes in Perl You can use double quotes or single quotes around literal strings as follows − #!/usr/bin/perl print "Hello, world\n"; print 'Hello, world\n'; This will produce the following result − Hello, world Hello, world\n$ There is an important difference in single and double quotes. Only double quotes interpolate variables and special characters such as newlines \n, whereas single quote does not interpolate any variable or special character. Check below example where we are using $a as a variable to store a value and later printing that value − #!/usr/bin/perl $a = 10; print "Value of a = $a\n"; print 'Value of a = $a\n'; This will produce the following result − Value of a = 10 Value of a = $a\n$ "Here" Documents You can store or print multiline text with a great comfort. Even you can make use of variables inside the "here" document. Below is a simple syntax, check carefully there must be no space between the << and the identifier. An identifier may be either a bare word or some quoted text like we used EOF below. If identifier is quoted, the type of quote you use determines the treatment of the text inside the here docoment, just as in regular quoting. An unquoted identifier works like double quotes. #!/usr/bin/perl $a = 10; $var = <<"EOF"; This is the syntax for here document and it will continue until it encounters a EOF in the first line. This is case of double quote so variable value will be interpolated. For example value of a = $a EOF print "$var\n"; $var = <<'EOF'; This is case of single quote so variable value will be interpolated. For example value of a = $a EOF print "$var\n"; This will produce the following result − This is the syntax for here document and it will continue until it encounters a EOF in the first line. This is case of double quote so variable value will be interpolated. For example value of a = 10 This is case of single quote so variable value will be interpolated. For example value of a = $a Escaping Characters Perl uses the backslash (\) character to escape any type of character that might interfere with our code. Let's take one example where we want to print double quote and $ sign − #!/usr/bin/perl $result = "This is \"number\""; print "$result\n"; print "\$result\n"; This will produce the following result − This is "number" $result Perl Identifiers A Perl identifier is a name used to identify a variable, function, class, module, or other object. A Perl variable name starts with either $, @ or % followed by zero or more letters, underscores, and digits (0 to 9). Perl does not allow punctuation characters such as @, $, and % within identifiers. Perl is a case sensitive programming language. Thus $Manpower and $manpower are two different identifiers in Perl. Perl - Data Types Perl is a loosely typed language and there is no need to specify a type for your data while using in your program. The Perl interpreter will choose the type based on the context of the data itself. Perl has three basic data types: scalars, arrays of scalars, and hashes of scalars, also known as associative arrays. Here is a little detail about these data types. Sr.No. Types & Description 1 Scalar Scalars are simple variables. They are preceded by a dollar sign ($). A scalar is either a number, a string, or a reference. A reference is actually an address of a variable, which we will see in the upcoming chapters. 2 Arrays Arrays are ordered lists of scalars that you access with a numeric index, which starts with 0. They are preceded by an "at" sign (@). 3 Hashes Hashes are unordered sets of key/value pairs that you access using the keys as subscripts. They are preceded by a percent sign (%). Numeric Literals Perl stores all the numbers internally as either signed integers or double-precision floating-point values. Numeric literals are specified in any of the following floating-point or integer formats − Type Value Integer 1234 Negative integer -100 Floating point 2000 Scientific notation 16.12E14 Hexadecimal 0xffff Octal 0577 String Literals Strings are sequences of characters. They are usually alphanumeric values delimited by either single (') or double (") quotes. They work much like UNIX shell quotes where you can use single quoted strings and double quoted strings. Double-quoted string literals allow variable interpolation, and single-quoted strings are not. There are certain characters when they are proceeded by a back slash, have special meaning and they are used to represent like newline (\n) or tab (\t). You can embed newlines or any of the following Escape sequences directly in your double quoted strings − Escape sequence Meaning \\ Backslash \' Single quote \" Double quote \a Alert or bell \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \0nn Creates Octal formatted numbers \xnn Creates Hexideciamal formatted numbers \cX Controls characters, x may be any character \u Forces next character to uppercase \l Forces next character to lowercase \U Forces all following characters to uppercase \L Forces all following characters to lowercase \Q Backslash all following non-alphanumeric characters \E End \U, \L, or \Q Example Let's see again how strings behave with single quotation and double quotation. Here we will use string escapes mentioned in the above table and will make use of the scalar variable to assign string values. #!/usr/bin/perl # This is case of interpolation. $str = "Welcome to \ntutorialspoint.com!"; print "$str\n"; # This is case of non-interpolation. $str = 'Welcome to \ntutorialspoint.com!'; print "$str\n"; # Only W will become upper case. $str = "\uwelcome to tutorialspoint.com!"; print "$str\n"; # Whole line will become capital. $str = "\UWelcome to tutorialspoint.com!"; print "$str\n"; # A portion of line will become capital. $str = "Welcome to \Ututorialspoint\E.com!"; print "$str\n"; # Backsalash non alpha-numeric including spaces. $str = "\QWelcome to tutorialspoint's family"; print "$str\n"; This will produce the following result − Welcome to tutorialspoint.com! Welcome to \ntutorialspoint.com! Welcome to tutorialspoint.com! WELCOME TO TUTORIALSPOINT.COM! Welcome to TUTORIALSPOINT.com! Welcome\ to\ tutorialspoint\'s\ family Perl - Variables Variables are the reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals, or strings in these variables. We have learnt that Perl has the following three basic data types − • Scalars • Arrays • Hashes Accordingly, we are going to use three types of variables in Perl. A scalar variable will precede by a dollar sign ($) and it can store either a number, a string, or a reference. An array variable will precede by sign @ and it will store ordered lists of scalars. Finaly, the Hash variable will precede by sign % and will be used to store sets of key/value pairs. Perl maintains every variable type in a separate namespace. So you can, without fear of conflict, use the same name for a scalar variable, an array, or a hash. This means that $foo and @foo are two different variables. Creating Variables Perl variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. Keep a note that this is mandatory to declare a variable before we use it if we use use strict statement in our program. The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is the value stored in the variable. For example − $age = 25; # An integer assignment $name = "John Paul"; # A string $salary = 1445.50; # A floating point Here 25, "John Paul" and 1445.50 are the values assigned to $age, $name and $salary variables, respectively. Shortly we will see how we can assign values to arrays and hashes. Scalar Variables A scalar is a single unit of data. That data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page. Simply saying it could be anything, but only a single thing. Here is a simple example of using scalar variables − #!/usr/bin/perl $age = 25; # An integer assignment $name = "John Paul"; # A string $salary = 1445.50; # A floating point print "Age = $age\n"; print "Name = $name\n"; print "Salary = $salary\n"; This will produce the following result − Age = 25 Name = John Paul Salary = 1445.5 Array Variables An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets. Here is a simple example of using array variables − #!/usr/bin/perl @ages = (25, 30, 40); @names = ("John Paul", "Lisa", "Kumar"); print "\$ages[0] = $ages[0]\n"; print "\$ages[1] = $ages[1]\n"; print "\$ages[2] = $ages[2]\n"; print "\$names[0] = $names[0]\n"; print "\$names[1] = $names[1]\n"; print "\$names[2] = $names[2]\n"; Here we used escape sign (\) before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result − $ages[0] = 25 $ages[1] = 30 $ages[2] = 40 $names[0] = John Paul $names[1] = Lisa $names[2] = Kumar Hash Variables A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name followed by the "key" associated with the value in curly brackets. Here is a simple example of using hash variables − #!/usr/bin/perl %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40); print "\$data{'John Paul'} = $data{'John Paul'}\n"; print "\$data{'Lisa'} = $data{'Lisa'}\n"; print "\$data{'Kumar'} = $data{'Kumar'}\n"; This will produce the following result − $data{'John Paul'} = 45 $data{'Lisa'} = 30 $data{'Kumar'} = 40 Variable Context Perl treats same variable differently based on Context, i.e., situation where a variable is being used. Let's check the following example − #!/usr/bin/perl @names = ('John Paul', 'Lisa', 'Kumar'); @copy = @names; $size = @names; print "Given names are : @copy\n"; print "Number of names are : $size\n"; This will produce the following result − Given names are : John Paul Lisa Kumar Number of names are : 3 Here @names is an array, which has been used in two different contexts. First we copied it into anyother array, i.e., list, so it returned all the elements assuming that context is list context. Next we used the same array and tried to store this array in a scalar, so in this case it returned just the number of elements in this array assuming that context is scalar context. Following table lists down the various contexts − Sr.No. Context & Description 1 Scalar Assignment to a scalar variable evaluates the right-hand side in a scalar context. 2 List Assignment to an array or a hash evaluates the right-hand side in a list context. 3 Boolean Boolean context is simply any place where an expression is being evaluated to see whether it's true or false. 4 Void This context not only doesn't care what the return value is, it doesn't even want a return value. 5 Interpolative This context only happens inside quotes, or things that work like quotes. Perl - Scalars A scalar is a single unit of data. That data might be an integer number, floating point, a character, a string, a paragraph, or an entire web page. Here is a simple example of using scalar variables − #!/usr/bin/perl $age = 25; # An integer assignment $name = "John Paul"; # A string $salary = 1445.50; # A floating point print "Age = $age\n"; print "Name = $name\n"; print "Salary = $salary\n"; This will produce the following result − Age = 25 Name = John Paul Salary = 1445.5 Numeric Scalars A scalar is most often either a number or a string. Following example demonstrates the usage of various types of numeric scalars − #!/usr/bin/perl $integer = 200; $negative = -300; $floating = 200.340; $bigfloat = -1.2E-23; # 377 octal, same as 255 decimal $octal = 0377; # FF hex, also 255 decimal $hexa = 0xff; print "integer = $integer\n"; print "negative = $negative\n"; print "floating = $floating\n"; print "bigfloat = $bigfloat\n"; print "octal = $octal\n"; print "hexa = $hexa\n"; This will produce the following result − integer = 200 negative = -300 floating = 200.34 bigfloat = -1.2e-23 octal = 255 hexa = 255 String Scalars Following example demonstrates the usage of various types of string scalars. Notice the difference between single quoted strings and double quoted strings − #!/usr/bin/perl $var = "This is string scalar!"; $quote = 'I m inside single quote - $var'; $double = "This is inside single quote - $var"; $escape = "This example of escape -\tHello, World!"; print "var = $var\n"; print "quote = $quote\n"; print "double = $double\n"; print "escape = $escape\n"; This will produce the following result − var = This is string scalar! quote = I m inside single quote - $var double = This is inside single quote - This is string scalar! escape = This example of escape - Hello, World Scalar Operations You will see a detail of various operators available in Perl in a separate chapter, but here we are going to list down few numeric and string operations. #!/usr/bin/perl $str = "hello" . "world"; # Concatenates strings. $num = 5 + 10; # adds two numbers. $mul = 4 * 5; # multiplies two numbers. $mix = $str . $num; # concatenates string and number. print "str = $str\n"; print "num = $num\n"; print "mix = $mix\n"; This will produce the following result − str = helloworld num = 15 mul = 20 mix = helloworld15 Multiline Strings If you want to introduce multiline strings into your programs, you can use the standard single quotes as below − #!/usr/bin/perl $string = 'This is a multiline string'; print "$string\n"; This will produce the following result − This is a multiline string You can use "here" document syntax as well to store or print multilines as below − #!/usr/bin/perl print <<EOF; This is a multiline string EOF This will also produce the same result − This is a multiline string V-Strings A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the specified ordinals. This form is known as v-strings. A v-string provides an alternative and more readable way to construct strings, rather than use the somewhat less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}". They are any literal that begins with a v and is followed by one or more dot-separated elements. For example − #!/usr/bin/perl $smile = v9786; $foo = v102.111.111; $martin = v77.97.114.116.105.110; print "smile = $smile\n"; print "foo = $foo\n"; print "martin = $martin\n"; This will also produce the same result − smile = ☺ foo = foo martin = Martin Wide character in print at main.pl line 7. Special Literals So far you must have a feeling about string scalars and its concatenation and interpolation opration. So let me tell you about three special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. They may be used only as separate tokens and will not be interpolated into strings. Check the below example − #!/usr/bin/perl print "File name ". __FILE__ . "\n"; print "Line Number " . __LINE__ ."\n"; print "Package " . __PACKAGE__ ."\n"; # they can not be interpolated print "__FILE__ __LINE__ __PACKAGE__\n"; This will produce the following result − File name hello.pl Line Number 4 Package main __FILE__ __LINE__ __PACKAGE__ Perl - Arrays An array is a variable that stores an ordered list of scalar values. Array variables are preceded by an "at" (@) sign. To refer to a single element of an array, you will use the dollar sign ($) with the variable name followed by the index of the element in square brackets. Here is a simple example of using the array variables − #!/usr/bin/perl @ages = (25, 30, 40); @names = ("John Paul", "Lisa", "Kumar"); print "\$ages[0] = $ages[0]\n"; print "\$ages[1] = $ages[1]\n"; print "\$ages[2] = $ages[2]\n"; print "\$names[0] = $names[0]\n"; print "\$names[1] = $names[1]\n"; print "\$names[2] = $names[2]\n"; Here we have used the escape sign (\) before the $ sign just to print it. Other Perl will understand it as a variable and will print its value. When executed, this will produce the following result − $ages[0] = 25 $ages[1] = 30 $ages[2] = 40 $names[0] = John Paul $names[1] = Lisa $names[2] = Kumar In Perl, List and Array terms are often used as if they're interchangeable. But the list is the data, and the array is the variable. Array Creation Array variables are prefixed with the @ sign and are populated using either parentheses or the qw operator. For example − @array = (1, 2, 'Hello'); @array = qw/This is an array/; The second line uses the qw// operator, which returns a list of strings, separating the delimited string by white space. In this example, this leads to a four-element array; the first element is 'this' and last (fourth) is 'array'. This means that you can use different lines as follows − @days = qw/Monday Tuesday ... Sunday/; You can also populate an array by assigning each value individually as follows − $array[0] = 'Monday'; ... $array[6] = 'Sunday'; Accessing Array Elements When accessing individual elements from an array, you must prefix the variable with a dollar sign ($) and then append the element index within the square brackets after the name of the variable. For example − #!/usr/bin/perl @days = qw/Mon Tue Wed Thu Fri Sat Sun/; print "$days[0]\n"; print "$days[1]\n"; print "$days[2]\n"; print "$days[6]\n"; print "$days[-1]\n"; print "$days[-7]\n"; This will produce the following result − Mon Tue Wed Sun Sun Mon Array indices start from zero, so to access the first element you need to give 0 as indices. You can also give a negative index, in which case you select the element from the end, rather than the beginning, of the array. This means the following − print $days[-1]; # outputs Sun print $days[-7]; # outputs Mon Sequential Number Arrays Perl offers a shortcut for sequential numbers and letters. Rather than typing out each element when counting to 100 for example, we can do something like as follows − #!/usr/bin/perl @var_10 = (1..10); @var_20 = (10..20); @var_abc = (a..z); print "@var_10\n"; # Prints number from 1 to 10 print "@var_20\n"; # Prints number from 10 to 20 print "@var_abc\n"; # Prints number from a to z Here double dot (..) is called range operator. This will produce the following result − 1 2 3 4 5 6 7 8 9 10 10 11 12 13 14 15 16 17 18 19 20 a b c d e f g h i j k l m n o p q r s t u v w x y z Array Size The size of an array can be determined using the scalar context on the array - the returned value will be the number of elements in the array − @array = (1,2,3); print "Size: ",scalar @array,"\n"; The value returned will always be the physical size of the array, not the number of valid elements. You can demonstrate this, and the difference between scalar @array and $#array, using this fragment is as follows − #!/usr/bin/perl @array = (1,2,3); $array[50] = 4; $size = @array; $max_index = $#array; print "Size: $size\n"; print "Max Index: $max_index\n"; This will produce the following result − Size: 51 Max Index: 50 There are only four elements in the array that contains information, but the array is 51 elements long, with a highest index of 50. Adding and Removing Elements in Array Perl provides a number of useful functions to add and remove elements in an array. You may have a question what is a function? So far you have used print function to print various values. Similarly there are various other functions or sometime called sub-routines, which can be used for various other functionalities. Sr.No. Types & Description 1 push @ARRAY, LIST Pushes the values of the list onto the end of the array. 2 pop @ARRAY Pops off and returns the last value of the array. 3 shift @ARRAY Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. 4 unshift @ARRAY, LIST Prepends list to the front of the array, and returns the number of elements in the new array. #!/usr/bin/perl # create a simple array @coins = ("Quarter","Dime","Nickel"); print "1. \@coins = @coins\n"; # add one element at the end of the array push(@coins, "Penny"); print "2. \@coins = @coins\n"; # add one element at the beginning of the array unshift(@coins, "Dollar"); print "3. \@coins = @coins\n"; # remove one element from the last of the array. pop(@coins); print "4. \@coins = @coins\n"; # remove one element from the beginning of the array. shift(@coins); print "5. \@coins = @coins\n"; This will produce the following result − 1. @coins = Quarter Dime Nickel 2. @coins = Quarter Dime Nickel Penny 3. @coins = Dollar Quarter Dime Nickel Penny 4. @coins = Dollar Quarter Dime Nickel 5. @coins = Quarter Dime Nickel Slicing Array Elements You can also extract a "slice" from an array - that is, you can select more than one item from an array in order to produce another array. #!/usr/bin/perl @days = qw/Mon Tue Wed Thu Fri Sat Sun/; @weekdays = @days[3,4,5]; print "@weekdays\n"; This will produce the following result − Thu Fri Sat The specification for a slice must have a list of valid indices, either positive or negative, each separated by a comma. For speed, you can also use the .. range operator − #!/usr/bin/perl @days = qw/Mon Tue Wed Thu Fri Sat Sun/; @weekdays = @days[3..5]; print "@weekdays\n"; This will produce the following result − Thu Fri Sat Replacing Array Elements Now we are going to introduce one more function called splice(), which has the following syntax − splice @ARRAY, OFFSET [ , LENGTH [ , LIST ] ] This function will remove the elements of @ARRAY designated by OFFSET and LENGTH, and replaces them with LIST, if specified. Finally, it returns the elements removed from the array. Following is the example − #!/usr/bin/perl @nums = (1..20); print "Before - @nums\n"; splice(@nums, 5, 5, 21..25); print "After - @nums\n"; This will produce the following result − Before - 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 After - 1 2 3 4 5 21 22 23 24 25 11 12 13 14 15 16 17 18 19 20 Here, the actual replacement begins with the 6th number after that five elements are then replaced from 6 to 10 with the numbers 21, 22, 23, 24 and 25. Transform Strings to Arrays Let's look into one more function called split(), which has the following syntax − split [ PATTERN [ , EXPR [ , LIMIT ] ] ] This function splits a string into an array of strings, and returns it. If LIMIT is specified, splits into at most that number of fields. If PATTERN is omitted, splits on whitespace. Following is the example − #!/usr/bin/perl # define Strings $var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens"; $var_names = "Larry,David,Roger,Ken,Michael,Tom"; # transform above strings into arrays. @string = split('-', $var_string); @names = split(',', $var_names); print "$string[3]\n"; # This will print Roses print "$names[4]\n"; # This will print Michael This will produce the following result − Roses Michael Transform Arrays to Strings We can use the join() function to rejoin the array elements and form one long scalar string. This function has the following syntax − join EXPR, LIST This function joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns the string. Following is the example − #!/usr/bin/perl # define Strings $var_string = "Rain-Drops-On-Roses-And-Whiskers-On-Kittens"; $var_names = "Larry,David,Roger,Ken,Michael,Tom"; # transform above strings into arrays. @string = split('-', $var_string); @names = split(',', $var_names); $string1 = join( '-', @string ); $string2 = join( ',', @names ); print "$string1\n"; print "$string2\n"; This will produce the following result − Rain-Drops-On-Roses-And-Whiskers-On-Kittens Larry,David,Roger,Ken,Michael,Tom Sorting Arrays The sort() function sorts each element of an array according to the ASCII Numeric standards. This function has the following syntax − sort [ SUBROUTINE ] LIST This function sorts the LIST and returns the sorted array value. If SUBROUTINE is specified then specified logic inside the SUBTROUTINE is applied while sorting the elements. #!/usr/bin/perl # define an array @foods = qw(pizza steak chicken burgers); print "Before: @foods\n"; # sort this array @foods = sort(@foods); print "After: @foods\n"; This will produce the following result − Before: pizza steak chicken burgers After: burgers chicken pizza steak Please note that sorting is performed based on ASCII Numeric value of the words. So the best option is to first transform every element of the array into lowercase letters and then perform the sort function. The $[ Special Variable So far you have seen simple variable we defined in our programs and used them to store and print scalar and array values. Perl provides numerous special variables, which have their predefined meaning. We have a special variable, which is written as $[. This special variable is a scalar containing the first index of all arrays. Because Perl arrays have zero-based indexing, $[ will almost always be 0. But if you set $[ to 1 then all your arrays will use on-based indexing. It is recommended not to use any other indexing other than zero. However, let's take one example to show the usage of $[ variable − #!/usr/bin/perl # define an array @foods = qw(pizza steak chicken burgers); print "Foods: @foods\n"; # Let's reset first index of all the arrays. $[ = 1; print "Food at \@foods[1]: $foods[1]\n"; print "Food at \@foods[2]: $foods[2]\n"; This will produce the following result − Foods: pizza steak chicken burgers Food at @foods[1]: pizza Food at @foods[2]: steak Merging Arrays Because an array is just a comma-separated sequence of values, you can combine them together as shown below − #!/usr/bin/perl @numbers = (1,3,(4,5,6)); print "numbers = @numbers\n"; This will produce the following result − numbers = 1 3 4 5 6 The embedded arrays just become a part of the main array as shown below − #!/usr/bin/perl @odd = (1,3,5); @even = (2, 4, 6); @numbers = (@odd, @even); print "numbers = @numbers\n"; This will produce the following result − numbers = 1 3 5 2 4 6 Selecting Elements from Lists The list notation is identical to that for arrays. You can extract an element from an array by appending square brackets to the list and giving one or more indices − #!/usr/bin/perl $var = (5,4,3,2,1)[4]; print "value of var = $var\n" This will produce the following result − value of var = 1 Similarly, we can extract slices, although without the requirement for a leading @ character − #!/usr/bin/perl @list = (5,4,3,2,1)[1..3]; print "Value of list = @list\n"; This will produce the following result − Value of list = 4 3 2 Perl - Hashes A hash is a set of key/value pairs. Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets.. Here is a simple example of using the hash variables − #!/usr/bin/perl %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40); print "\$data{'John Paul'} = $data{'John Paul'}\n"; print "\$data{'Lisa'} = $data{'Lisa'}\n"; print "\$data{'Kumar'} = $data{'Kumar'}\n"; This will produce the following result − $data{'John Paul'} = 45 $data{'Lisa'} = 30 $data{'Kumar'} = 40 Creating Hashes Hashes are created in one of the two following ways. In the first method, you assign a value to a named key on a one-by-one basis − $data{'John Paul'} = 45; $data{'Lisa'} = 30; $data{'Kumar'} = 40; In the second case, you use a list, which is converted by taking individual pairs from the list: the first element of the pair is used as the key, and the second, as the value. For example − %data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40); For clarity, you can use => as an alias for , to indicate the key/value pairs as follows − %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); Here is one more variant of the above form, have a look at it, here all the keys have been preceded by hyphen (-) and no quotation is required around them − %data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); But it is important to note that there is a single word, i.e., without spaces keys have been used in this form of hash formation and if you build-up your hash this way then keys will be accessed using hyphen only as shown below. $val = %data{-JohnPaul} $val = %data{-Lisa} Accessing Hash Elements When accessing individual elements from a hash, you must prefix the variable with a dollar sign ($) and then append the element key within curly brackets after the name of the variable. For example − #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); print "$data{'John Paul'}\n"; print "$data{'Lisa'}\n"; print "$data{'Kumar'}\n"; This will produce the following result − 45 30 40 Extracting Slices You can extract slices of a hash just as you can extract slices from an array. You will need to use @ prefix for the variable to store the returned value because they will be a list of values − #!/uer/bin/perl %data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); @array = @data{-JohnPaul, -Lisa}; print "Array : @array\n"; This will produce the following result − Array : 45 30 Extracting Keys and Values You can get a list of all of the keys from a hash by using keys function, which has the following syntax − keys %HASH This function returns an array of all the keys of the named hash. Following is the example − #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @names = keys %data; print "$names[0]\n"; print "$names[1]\n"; print "$names[2]\n"; This will produce the following result − Lisa John Paul Kumar Similarly, you can use values function to get a list of all the values. This function has the following syntax − values %HASH This function returns a normal array consisting of all the values of the named hash. Following is the example − #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @ages = values %data; print "$ages[0]\n"; print "$ages[1]\n"; print "$ages[2]\n"; This will produce the following result − 30 45 40 Checking for Existence If you try to access a key/value pair from a hash that doesn't exist, you'll normally get the undefined value, and if you have warnings switched on, then you'll get a warning generated at run time. You can get around this by using the exists function, which returns true if the named key exists, irrespective of what its value might be − #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); if( exists($data{'Lisa'} ) ) { print "Lisa is $data{'Lisa'} years old\n"; } else { print "I don't know age of Lisa\n"; } Here we have introduced the IF...ELSE statement, which we will study in a separate chapter. For now you just assume that if( condition ) part will be executed only when the given condition is true otherwise else part will be executed. So when we execute the above program, it produces the following result because here the given condition exists($data{'Lisa'} returns true − Lisa is 30 years old Getting Hash Size You can get the size - that is, the number of elements from a hash by using the scalar context on either keys or values. Simply saying first you have to get an array of either the keys or values and then you can get the size of array as follows − #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @keys = keys %data; $size = @keys; print "1 - Hash size: is $size\n"; @values = values %data; $size = @values; print "2 - Hash size: is $size\n"; This will produce the following result − 1 - Hash size: is 3 2 - Hash size: is 3 Add and Remove Elements in Hashes Adding a new key/value pair can be done with one line of code using simple assignment operator. But to remove an element from the hash you need to use delete function as shown below in the example − #!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @keys = keys %data; $size = @keys; print "1 - Hash size: is $size\n"; # adding an element to the hash; $data{'Ali'} = 55; @keys = keys %data; $size = @keys; print "2 - Hash size: is $size\n"; # delete the same element from the hash; delete $data{'Ali'}; @keys = keys %data; $size = @keys; print "3 - Hash size: is $size\n"; This will produce the following result − 1 - Hash size: is 3 2 - Hash size: is 4 3 - Hash size: is 3 Perl Conditional Statements - IF...ELSE Perl conditional statements helps in the decision making, which require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general from of a typical decision making structure found in most of the programming languages − Decision making statements in Perl The number 0, the strings '0' and "" , the empty list () , and undef are all false in a boolean context and all other values are true. Negation of a true value by ! or not returns a special false value. Perl programming language provides the following types of conditional statements. Sr.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if...else statement An if statement can be followed by an optional else statement. 3 if...elsif...else statement An if statement can be followed by an optional elsif statement and then by an optional else statement. 4 unless statement An unless statement consists of a boolean expression followed by one or more statements. 5 unless...else statement An unless statement can be followed by an optional else statement. 6 unless...elsif..else statement An unless statement can be followed by an optional elsif statement and then by an optional else statement. 7 switch statement With the latest versions of Perl, you can make use of the switch statement. which allows a simple way of comparing a variable value against various conditions. The ? : Operator Let's check the conditional operator ? :which can be used to replace if...else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. The value of a ? expression is determined like this: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression. Below is a simple example making use of this operator − #!/usr/local/bin/perl $name = "Ali"; $age = 10; $status = ($age > 60 )? "A senior citizen" : "Not a senior citizen"; print "$name is - $status\n"; This will produce the following result − Ali is - Not a senior citizen Perl - Loops There may be a situation when you need to execute a block of code several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times and following is the general form of a loop statement in most of the programming languages − Loop Architecture in Perl Perl programming language provides the following types of loop to handle the looping requirements. Sr.No. Loop Type & Description 1 while loop Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. 2 until loop Repeats a statement or group of statements until a given condition becomes true. It tests the condition before executing the loop body. 3 for loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. 4 foreach loop The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. 5 do...while loop Like a while statement, except that it tests the condition at the end of the loop body 6 nested loops You can use one or more loop inside any another while, for or do..while loop. Loop Control Statements Loop control statements change the execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Perl supports the following control statements. Click the following links to check their detail. Sr.No. Control Statement & Description 1 next statement Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. 2 last statement Terminates the loop statement and transfers execution to the statement immediately following the loop. 3 continue statement A continue BLOCK, it is always executed just before the conditional is about to be evaluated again. 4 redo statement The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. 5 goto statement Perl supports a goto command with three forms: goto label, goto expr, and goto &name. The Infinite Loop A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. #!/usr/local/bin/perl for( ; ; ) { printf "This loop will run forever.\n"; } You can terminate the above infinite loop by pressing the Ctrl + C keys. When the conditional expression is absent, it is assumed to be true. You may have an initialization and increment expression, but as a programmer more commonly use the for (;;) construct to signify an infinite loop. Perl - Operators What is an Operator? Simple answer can be given using the expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and + is called operator. Perl language supports many operator types, but following is a list of important and most frequently used operators − • Arithmetic Operators • Equality Operators • Logical Operators • Assignment Operators • Bitwise Operators • Logical Operators • Quote-like Operators • Miscellaneous Operators Lets have a look at all the operators one by one. Perl Arithmetic Operators Assume variable $a holds 10 and variable $b holds 20, then following are the Perl arithmatic operators − Show Example Sr.No. Operator & Description 1 + ( Addition ) Adds values on either side of the operator Example − $a + $b will give 30 2 - (Subtraction) Subtracts right hand operand from left hand operand Example − $a - $b will give -10 3 * (Multiplication) Multiplies values on either side of the operator Example − $a * $b will give 200 4 / (Division) Divides left hand operand by right hand operand Example − $b / $a will give 2 5 % (Modulus) Divides left hand operand by right hand operand and returns remainder Example − $b % $a will give 0 6 ** (Exponent) Performs exponential (power) calculation on operators Example − $a**$b will give 10 to the power 20 Perl Equality Operators These are also called relational operators. Assume variable $a holds 10 and variable $b holds 20 then, lets check the following numeric equality operators − Show Example Sr.No. Operator & Description 1 == (equal to) Checks if the value of two operands are equal or not, if yes then condition becomes true. Example − ($a == $b) is not true. 2 != (not equal to) Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. Example − ($a != $b) is true. 3 <=> Checks if the value of two operands are equal or not, and returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. Example − ($a <=> $b) returns -1. 4 > (greater than) Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. Example − ($a > $b) is not true. 5 < (less than) Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. Example − ($a < $b) is true. 6 >= (greater than or equal to) Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. Example − ($a >= $b) is not true. 7 <= (less than or equal to) Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. Example − ($a <= $b) is true. Below is a list of equity operators. Assume variable $a holds "abc" and variable $b holds "xyz" then, lets check the following string equality operators − Show Example Sr.No. Operator & Description 1 lt Returns true if the left argument is stringwise less than the right argument. Example − ($a lt $b) is true. 2 gt Returns true if the left argument is stringwise greater than the right argument. Example − ($a gt $b) is false. 3 le Returns true if the left argument is stringwise less than or equal to the right argument. Example − ($a le $b) is true. 4 ge Returns true if the left argument is stringwise greater than or equal to the right argument. Example − ($a ge $b) is false. 5 eq Returns true if the left argument is stringwise equal to the right argument. Example − ($a eq $b) is false. 6 ne Returns true if the left argument is stringwise not equal to the right argument. Example − ($a ne $b) is true. 7 cmp Returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument. Example − ($a cmp $b) is -1. Perl Assignment Operators Assume variable $a holds 10 and variable $b holds 20, then below are the assignment operators available in Perl and their usage − Show Example Sr.No. Operator & Description 1 = Simple assignment operator, Assigns values from right side operands to left side operand Example − $c = $a + $b will assigned value of $a + $b into $c 2 += Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand Example − $c += $a is equivalent to $c = $c + $a 3 -= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand Example − $c -= $a is equivalent to $c = $c - $a 4 *= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand Example − $c *= $a is equivalent to $c = $c * $a 5 /= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand Example − $c /= $a is equivalent to $c = $c / $a 6 %= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand Example − $c %= $a is equivalent to $c = $c % a 7 **= Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand Example − $c **= $a is equivalent to $c = $c ** $a Perl Bitwise Operators Bitwise operator works on bits and perform bit by bit operation. Assume if $a = 60; and $b = 13; Now in binary format they will be as follows − $a = 0011 1100 $b = 0000 1101 ----------------- $a&$b = 0000 1100 $a|$b = 0011 1101 $a^$b = 0011 0001 ~$a  = 1100 0011 There are following Bitwise operators supported by Perl language, assume if $a = 60; and $b = 13 Show Example Sr.No. Operator & Description 1 & Binary AND Operator copies a bit to the result if it exists in both operands. Example − ($a & $b) will give 12 which is 0000 1100 2 | Binary OR Operator copies a bit if it exists in eather operand. Example − ($a | $b) will give 61 which is 0011 1101 3 ^ Binary XOR Operator copies the bit if it is set in one operand but not both. Example − ($a ^ $b) will give 49 which is 0011 0001 4 ~ Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. Example − (~$a ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. 5 << Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. Example − $a << 2 will give 240 which is 1111 0000 6 >> Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. Example − $a >> 2 will give 15 which is 0000 1111 Perl Logical Operators There are following logical operators supported by Perl language. Assume variable $a holds true and variable $b holds false then − Show Example Sr.No. Operator & Description 1 and Called Logical AND operator. If both the operands are true then then condition becomes true. Example − ($a and $b) is false. 2 && C-style Logical AND operator copies a bit to the result if it exists in both operands. Example − ($a && $b) is false. 3 or Called Logical OR Operator. If any of the two operands are non zero then then condition becomes true. Example − ($a or $b) is true. 4 || C-style Logical OR operator copies a bit if it exists in eather operand. Example − ($a || $b) is true. 5 not Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. Example − not($a and $b) is true. Quote-like Operators There are following Quote-like operators supported by Perl language. In the following table, a {} represents any pair of delimiters you choose. Show Example Sr.No. Operator & Description 1 q{ } Encloses a string with-in single quotes Example − q{abcd} gives 'abcd' 2 qq{ } Encloses a string with-in double quotes Example − qq{abcd} gives "abcd" 3 qx{ } Encloses a string with-in invert quotes Example − qx{abcd} gives `abcd` Miscellaneous Operators There are following miscellaneous operators supported by Perl language. Assume variable a holds 10 and variable b holds 20 then − Show Example Sr.No. Operator & Description 1 . Binary operator dot (.) concatenates two strings. Example − If $a = "abc", $b = "def" then $a.$b will give "abcdef" 2 x The repetition operator x returns a string consisting of the left operand repeated the number of times specified by the right operand. Example − ('-' x 3) will give ---. 3 .. The range operator .. returns a list of values counting (up by ones) from the left value to the right value Example − (2..5) will give (2, 3, 4, 5) 4 ++ Auto Increment operator increases integer value by one Example − $a++ will give 11 5 -- Auto Decrement operator decreases integer value by one Example − $a-- will give 9 6 -> The arrow operator is mostly used in dereferencing a method or variable from an object or a class name Example − $obj->$a is an example to access variable $a from object $obj. Perl Operators Precedence The following table lists all operators from highest precedence to lowest. Show Example left terms and list operators (leftward) left -> nonassoc ++ -- right ** right ! ~ \ and unary + and - left =~ !~ left * / % x left + - . left << >> nonassoc named unary operators nonassoc < > <= >= lt gt le ge nonassoc == != <=> eq ne cmp ~~ left & left | ^ left && left || // nonassoc .. ... right ?: right = += -= *= etc. left , => nonassoc list operators (rightward) right not left and left or xor Perl - Date and Time This chapter will give you the basic understanding on how to process and manipulate dates and times in Perl. Current Date and Time Let's start with localtime() function, which returns values for the current date and time if given no arguments. Following is the 9-element list returned by the localtime function while using in list context − sec, # seconds of minutes from 0 to 61 min, # minutes of hour from 0 to 59 hour, # hours of day from 0 to 24 mday, # day of month from 1 to 31 mon, # month of year from 0 to 11 year, # year since 1900 wday, # days since sunday yday, # days since January 1st isdst # hours of daylight savings time Try the following example to print different elements returned by localtime() function − #!/usr/local/bin/perl @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); @days = qw(Sun Mon Tue Wed Thu Fri Sat Sun); ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); print "$mday $months[$mon] $days[$wday]\n"; When the above code is executed, it produces the following result − 16 Feb Sat If you will use localtime() function in scalar context, then it will return date and time from the current time zone set in the system. Try the following example to print current date and time in full format − #!/usr/local/bin/perl $datestring = localtime(); print "Local date and time $datestring\n"; When the above code is executed, it produces the following result − Local date and time Sat Feb 16 06:50:45 2013 GMT Time The function gmtime() works just like localtime() function but the returned values are localized for the standard Greenwich time zone. When called in list context, $isdst, the last value returned by gmtime, is always 0. There is no Daylight Saving Time in GMT. You should make a note on the fact that localtime() will return the current local time on the machine that runs the script and gmtime() will return the universal Greenwich Mean Time, or GMT (or UTC). Try the following example to print the current date and time but on GMT scale − #!/usr/local/bin/perl $datestring = gmtime(); print "GMT date and time $datestring\n"; When the above code is executed, it produces the following result − GMT date and time Sat Feb 16 13:50:45 2013 Format Date and Time You can use localtime() function to get a list of 9-elements and later you can use the printf() function to format date and time based on your requirements as follows − #!/usr/local/bin/perl ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); printf("Time Format - HH:MM:SS\n"); printf("%02d:%02d:%02d", $hour, $min, $sec); When the above code is executed, it produces the following result − Time Format - HH:MM:SS 06:58:52 Epoch time You can use the time() function to get epoch time, i.e., the numbers of seconds that have elapsed since a given date, in Unix is January 1, 1970. #!/usr/local/bin/perl $epoc = time(); print "Number of seconds since Jan 1, 1970 - $epoc\n"; When the above code is executed, it produces the following result − Number of seconds since Jan 1, 1970 - 1361022130 You can convert a given number of seconds into date and time string as follows − #!/usr/local/bin/perl $datestring = localtime(); print "Current date and time $datestring\n"; $epoc = time(); $epoc = $epoc - 24 * 60 * 60; # one day before of current date. $datestring = localtime($epoc); print "Yesterday's date and time $datestring\n"; When the above code is executed, it produces the following result − Current date and time Tue Jun 5 05:54:43 2018 Yesterday's date and time Mon Jun 4 05:54:43 2018 POSIX Function strftime() You can use the POSIX function strftime() to format date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent. Specifier Replaced by Example %a Abbreviated weekday name * Thu %A Full weekday name * Thursday %b Abbreviated month name * Aug %B Full month name * August %c Date and time representation * Thu Aug 23 14:55:02 2001 %C Year divided by 100 and truncated to integer (00-99) 20 %d Day of the month, zero-padded (01-31) 23 %D Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01 %e Day of the month, space-padded ( 1-31) 23 %F Short YYYY-MM-DD date, equivalent to %Y-%m-%d 2001-08-23 %g Week-based year, last two digits (00-99) 01 %G Week-based year 2001 %h Abbreviated month name * (same as %b) Aug %H Hour in 24h format (00-23) 14 %I Hour in 12h format (01-12) 02 %j Day of the year (001-366) 235 %m Month as a decimal number (01-12) 08 %M Minute (00-59) 55 %n New-line character ('\n') %p AM or PM designation PM %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %S Second (00-61) 02 %t Horizontal-tab character ('\t') %T ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S 14:55 %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %U Week number with the first Sunday as the first day of week one (00-53) 33 %V ISO 8601 week number (00-53) 34 %w Weekday as a decimal number with Sunday as 0 (0-6) 4 %W Week number with the first Monday as the first day of week one (00-53) 34 %x Date representation * 08/23/01 %X Time representation * 14:55:02 %y Year, last two digits (00-99) 01 %Y Year 2001 %z ISO 8601 offset from UTC in timezone (1 minute = 1, 1 hour = 100) If timezone cannot be termined, no characters +100 %Z Timezone name or abbreviation * If timezone cannot be termined, no characters CDT %% A % sign % Let's check the following example to understand the usage − #!/usr/local/bin/perl use POSIX qw(strftime); $datestring = strftime "%a %b %e %H:%M:%S %Y", localtime; printf("date and time - $datestring\n"); # or for GMT formatted appropriately for your locale: $datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime; printf("date and time - $datestring\n"); When the above code is executed, it produces the following result − date and time - Sat Feb 16 07:10:23 2013 date and time - Sat Feb 16 14:10:23 2013 Perl - Subroutines A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task. Perl uses the terms subroutine, method and function interchangeably. Define and Call a Subroutine The general form of a subroutine definition in Perl programming language is as follows − sub subroutine_name { body of the subroutine } The typical way of calling that Perl subroutine is as follows − subroutine_name( list of arguments ); In versions of Perl before 5.0, the syntax for calling subroutines was slightly different as shown below. This still works in the newest versions of Perl, but it is not recommended since it bypasses the subroutine prototypes. &subroutine_name( list of arguments ); Let's have a look into the following example, which defines a simple function and then call it. Because Perl compiles your program before executing it, it doesn't matter where you declare your subroutine. #!/usr/bin/perl # Function definition sub Hello { print "Hello, World!\n"; } # Function call Hello(); When above program is executed, it produces the following result − Hello, World! Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on. You can pass arrays and hashes as arguments like any scalar but passing more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to pass any array or hash. Let's try the following example, which takes a list of numbers and then prints their average − #!/usr/bin/perl # Function definition sub Average { # get total number of arguments passed. $n = scalar(@_); $sum = 0; foreach $item (@_) { $sum += $item; } $average = $sum / $n; print "Average for the given numbers : $average\n"; } # Function call Average(10, 20, 30); When above program is executed, it produces the following result − Average for the given numbers : 20 Passing Lists to Subroutines Because the @_ variable is an array, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument as shown below − #!/usr/bin/perl # Function definition sub PrintList { my @list = @_; print "Given list is @list\n"; } $a = 10; @b = (1, 2, 3, 4); # Function call with list parameter PrintList($a, @b); When above program is executed, it produces the following result − Given list is 10 1 2 3 4 Passing Hashes to Subroutines When you supply a hash to a subroutine or operator that accepts a list, then hash is automatically translated into a list of key/value pairs. For example − #!/usr/bin/perl # Function definition sub PrintHash { my (%hash) = @_; foreach my $key ( keys %hash ) { my $value = $hash{$key}; print "$key : $value\n"; } } %hash = ('name' => 'Tom', 'age' => 19); # Function call with hash parameter PrintHash(%hash); When above program is executed, it produces the following result − name : Tom age : 19 Returning Value from a Subroutine You can return a value from subroutine like you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value. You can return arrays and hashes from the subroutine like any scalar but returning more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to return any array or hash from a function. Let's try the following example, which takes a list of numbers and then returns their average − #!/usr/bin/perl # Function definition sub Average { # get total number of arguments passed. $n = scalar(@_); $sum = 0; foreach $item (@_) { $sum += $item; } $average = $sum / $n; return $average; } # Function call $num = Average(10, 20, 30); print "Average for the given numbers : $num\n"; When above program is executed, it produces the following result − Average for the given numbers : 20 Private Variables in a Subroutine By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator. The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. This region is called its scope. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements. Following is an example showing you how to define a single or multiple private variables using my operator − sub somefunc { my $variable; # $variable is invisible outside somefunc() my ($another, @an_array, %a_hash); # declaring many variables at once } Let's check the following example to distinguish between global and private variables − #!/usr/bin/perl # Global variable $string = "Hello, World!"; # Function definition sub PrintHello { # Private variable for PrintHello function my $string; $string = "Hello, Perl!"; print "Inside the function $string\n"; } # Function call PrintHello(); print "Outside the function $string\n"; When above program is executed, it produces the following result − Inside the function Hello, Perl! Outside the function Hello, World! Temporary Values via local() The local is mostly used when the current value of a variable must be visible to called subroutines. A local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping. Lexical scoping is done with my, which works more like C's auto declarations. If more than one variable or expression is given to local, they must be placed in parentheses. This operator works by saving the current values of those variables in its argument list on a hidden stack and restoring them upon exiting the block, subroutine, or eval. Let's check the following example to distinguish between global and local variables − #!/usr/bin/perl # Global variable $string = "Hello, World!"; sub PrintHello { # Private variable for PrintHello function local $string; $string = "Hello, Perl!"; PrintMe(); print "Inside the function PrintHello $string\n"; } sub PrintMe { print "Inside the function PrintMe $string\n"; } # Function call PrintHello(); print "Outside the function $string\n"; When above program is executed, it produces the following result − Inside the function PrintMe Hello, Perl! Inside the function PrintHello Hello, Perl! Outside the function Hello, World! State Variables via state() There are another type of lexical variables, which are similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl 5.9.4. Let's check the following example to demonstrate the use of state variables − #!/usr/bin/perl use feature 'state'; sub PrintCount { state $count = 0; # initial value print "Value of counter is $count\n"; $count++; } for (1..5) { PrintCount(); } When above program is executed, it produces the following result − Value of counter is 0 Value of counter is 1 Value of counter is 2 Value of counter is 3 Value of counter is 4 Prior to Perl 5.10, you would have to write it like this − #!/usr/bin/perl { my $count = 0; # initial value sub PrintCount { print "Value of counter is $count\n"; $count++; } } for (1..5) { PrintCount(); } Subroutine Call Context The context of a subroutine or statement is defined as the type of return value that is expected. This allows you to use a single function that returns different values based on what the user is expecting to receive. For example, the following localtime() returns a string when it is called in scalar context, but it returns a list when it is called in list context. my $datestring = localtime( time ); In this example, the value of $timestr is now a string made up of the current date and time, for example, Thu Nov 30 15:21:33 2000. Conversely − ($sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst) = localtime(time); Now the individual variables contain the corresponding values returned by localtime() subroutine. Perl - References A Perl reference is a scalar data type that holds the location of another value which could be scalar, arrays, or hashes. Because of its scalar nature, a reference can be used anywhere, a scalar can be used. You can construct lists containing references to other lists, which can contain references to hashes, and so on. This is how the nested data structures are built in Perl. Create References It is easy to create a reference for any variable, subroutine or value by prefixing it with a backslash as follows − $scalarref = \$foo; $arrayref = \@ARGV; $hashref = \%ENV; $coderef = \&handler; $globref = \*foo; You cannot create a reference on an I/O handle (filehandle or dirhandle) using the backslash operator but a reference to an anonymous array can be created using the square brackets as follows − $arrayref = [1, 2, ['a', 'b', 'c']]; Similar way you can create a reference to an anonymous hash using the curly brackets as follows − $hashref = { 'Adam' => 'Eve', 'Clyde' => 'Bonnie', }; A reference to an anonymous subroutine can be created by using sub without a subname as follows − $coderef = sub { print "Boink!\n" }; Dereferencing Dereferencing returns the value from a reference point to the location. To dereference a reference simply use $, @ or % as prefix of the reference variable depending on whether the reference is pointing to a scalar, array, or hash. Following is the example to explain the concept − #!/usr/bin/perl $var = 10; # Now $r has reference to $var scalar. $r = \$var; # Print value available at the location stored in $r. print "Value of $var is : ", $$r, "\n"; @var = (1, 2, 3); # Now $r has reference to @var array. $r = \@var; # Print values available at the location stored in $r. print "Value of @var is : ", @$r, "\n"; %var = ('key1' => 10, 'key2' => 20); # Now $r has reference to %var hash. $r = \%var; # Print values available at the location stored in $r. print "Value of %var is : ", %$r, "\n"; When above program is executed, it produces the following result − Value of 10 is : 10 Value of 1 2 3 is : 123 Value of %var is : key220key110 If you are not sure about a variable type, then its easy to know its type using ref, which returns one of the following strings if its argument is a reference. Otherwise, it returns false − SCALAR ARRAY HASH CODE GLOB REF Let's try the following example − #!/usr/bin/perl $var = 10; $r = \$var; print "Reference type in r : ", ref($r), "\n"; @var = (1, 2, 3); $r = \@var; print "Reference type in r : ", ref($r), "\n"; %var = ('key1' => 10, 'key2' => 20); $r = \%var; print "Reference type in r : ", ref($r), "\n"; When above program is executed, it produces the following result − Reference type in r : SCALAR Reference type in r : ARRAY Reference type in r : HASH Circular References A circular reference occurs when two references contain a reference to each other. You have to be careful while creating references otherwise a circular reference can lead to memory leaks. Following is an example − #!/usr/bin/perl my $foo = 100; $foo = \$foo; print "Value of foo is : ", $$foo, "\n"; When above program is executed, it produces the following result − Value of foo is : REF(0x9aae38) References to Functions This might happen if you need to create a signal handler so you can produce a reference to a function by preceding that function name with \& and to dereference that reference you simply need to prefix reference variable using ampersand &. Following is an example − #!/usr/bin/perl # Function definition sub PrintHash { my (%hash) = @_; foreach $item (%hash) { print "Item : $item\n"; } } %hash = ('name' => 'Tom', 'age' => 19); # Create a reference to above function. $cref = \&PrintHash; # Function call using reference. &$cref(%hash); When above program is executed, it produces the following result − Item : name Item : Tom Item : age Item : 19 Perl - Formats Perl uses a writing template called a 'format' to output reports. To use the format feature of Perl, you have to define a format first and then you can use that format to write formatted data. Define a Format Following is the syntax to define a Perl format − format FormatName = fieldline value_one, value_two, value_three fieldline value_one, value_two . Here FormatName represents the name of the format. The fieldline is the specific way, the data should be formatted. The values lines represent the values that will be entered into the field line. You end the format with a single period. Next fieldline can contain any text or fieldholders. The fieldholders hold space for data that will be placed there at a later date. A fieldholder has the format − @<<<< This fieldholder is left-justified, with a field space of 5. You must count the @ sign and the < signs to know the number of spaces in the field. Other field holders include − @>>>> right-justified @|||| centered @####.## numeric field holder @* multiline field holder An example format would be − format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== . In this example, $name would be written as left justify within 22 character spaces and after that age will be written in two spaces. Using the Format In order to invoke this format declaration, we would use the write keyword − write EMPLOYEE; The problem is that the format name is usually the name of an open file handle, and the write statement will send the output to this file handle. As we want the data sent to the STDOUT, we must associate EMPLOYEE with the STDOUT filehandle. First, however, we must make sure that that STDOUT is our selected file handle, using the select() function. select(STDOUT); We would then associate EMPLOYEE with STDOUT by setting the new format name with STDOUT, using the special variable $~ or $FORMAT_NAME as follows − $~ = "EMPLOYEE"; When we now do a write(), the data would be sent to STDOUT. Remember: if you are going to write your report in any other file handle instead of STDOUT then you can use select() function to select that file handle and rest of the logic will remain the same. Let's take the following example. Here we have hard coded values just for showing the usage. In actual usage you will read values from a file or database to generate actual reports and you may need to write final report again into a file. #!/usr/bin/perl format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== . select(STDOUT); $~ = EMPLOYEE; @n = ("Ali", "Raza", "Jaffer"); @a = (20,30, 40); @s = (2000.00, 2500.00, 4000.000); $i = 0; foreach (@n) { $name = $_; $age = $a[$i]; $salary = $s[$i++]; write; } When executed, this will produce the following result − =================================== Ali 20 2000.00 =================================== =================================== Raza 30 2500.00 =================================== =================================== Jaffer 40 4000.00 =================================== Define a Report Header Everything looks fine. But you would be interested in adding a header to your report. This header will be printed on top of each page. It is very simple to do this. Apart from defining a template you would have to define a header and assign it to $^ or $FORMAT_TOP_NAME variable − #!/usr/bin/perl format EMPLOYEE = =================================== @<<<<<<<<<<<<<<<<<<<<<< @<< $name $age @#####.## $salary =================================== . format EMPLOYEE_TOP = =================================== Name Age =================================== . select(STDOUT); $~ = EMPLOYEE; $^ = EMPLOYEE_TOP; @n = ("Ali", "Raza", "Jaffer"); @a = (20,30, 40); @s = (2000.00, 2500.00, 4000.000); $i = 0; foreach (@n) { $name = $_; $age = $a[$i]; $salary = $s[$i++]; write; } Now your report will look like − =================================== Name Age =================================== =================================== Ali 20 2000.00 =================================== =================================== Raza 30 2500.00 =================================== =================================== Jaffer 40 4000.00 =================================== Define a Pagination What about if your report is taking more than one page? You have a solution for that, simply use $% or $FORMAT_PAGE_NUMBER vairable along with header as follows − format EMPLOYEE_TOP = =================================== Name Age Page @< $% =================================== . Now your output will look like as follows − =================================== Name Age Page 1 =================================== =================================== Ali 20 2000.00 =================================== =================================== Raza 30 2500.00 =================================== =================================== Jaffer 40 4000.00 =================================== Number of Lines on a Page You can set the number of lines per page using special variable $= ( or $FORMAT_LINES_PER_PAGE ), By default $= will be 60. Define a Report Footer While $^ or $FORMAT_TOP_NAME contains the name of the current header format, there is no corresponding mechanism to automatically do the same thing for a footer. If you have a fixed-size footer, you can get footers by checking variable $- or $FORMAT_LINES_LEFT before each write() and print the footer yourself if necessary using another format defined as follows − format EMPLOYEE_BOTTOM = End of Page @< $% . For a complete set of variables related to formating, please refer to the Perl Special Variables section. Perl - File I/O The basics of handling files are simple: you associate a filehandle with an external entity (usually a file) and then use a variety of operators and functions within Perl to read and update the data stored within the data stream associated with the filehandle. A filehandle is a named internal Perl structure that associates a physical file with a name. All filehandles are capable of read/write access, so you can read from and update any file or device associated with a filehandle. However, when you associate a filehandle, you can specify the mode in which the filehandle is opened. Three basic file handles are - STDIN, STDOUT, and STDERR, which represent standard input, standard output and standard error devices respectively. Opening and Closing Files There are following two functions with multiple forms, which can be used to open any new or existing file in Perl. open FILEHANDLE, EXPR open FILEHANDLE sysopen FILEHANDLE, FILENAME, MODE, PERMS sysopen FILEHANDLE, FILENAME, MODE Here FILEHANDLE is the file handle returned by the open function and EXPR is the expression having file name and mode of opening the file. Open Function Following is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode. open(DATA, "<file.txt"); Here DATA is the file handle, which will be used to read the file. Here is the example, which will open a file and will print its content over the screen. #!/usr/bin/perl open(DATA, "<file.txt") or die "Couldn't open file file.txt, $!"; while(<DATA>) { print "$_"; } Following is the syntax to open file.txt in writing mode. Here less than > sign indicates that file has to be opend in the writing mode. open(DATA, ">file.txt") or die "Couldn't open file file.txt, $!"; This example actually truncates (empties) the file before opening it for writing, which may not be the desired effect. If you want to open a file for reading and writing, you can put a plus sign before the > or < characters. For example, to open a file for updating without truncating it − open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!"; To truncate the file first − open DATA, "+>file.txt" or die "Couldn't open file file.txt, $!"; You can open a file in the append mode. In this mode, writing point will be set to the end of the file. open(DATA,">>file.txt") || die "Couldn't open file file.txt, $!"; A double >> opens the file for appending, placing the file pointer at the end, so that you can immediately start appending information. However, you can't read from it unless you also place a plus sign in front of it − open(DATA,"+>>file.txt") || die "Couldn't open file file.txt, $!"; Following is the table, which gives the possible values of different modes Sr.No. Entities & Definition 1 < or r Read Only Access 2 > or w Creates, Writes, and Truncates 3 >> or a Writes, Appends, and Creates 4 +< or r+ Reads and Writes 5 +> or w+ Reads, Writes, Creates, and Truncates 6 +>> or a+ Reads, Writes, Appends, and Creates Sysopen Function The sysopen function is similar to the main open function, except that it uses the system open() function, using the parameters supplied to it as the parameters for the system function − For example, to open a file for updating, emulating the +<filename format from open − sysopen(DATA, "file.txt", O_RDWR); Or to truncate the file before updating − sysopen(DATA, "file.txt", O_RDWR|O_TRUNC ); You can use O_CREAT to create a new file and O_WRONLY- to open file in write only mode and O_RDONLY - to open file in read only mode. The PERMS argument specifies the file permissions for the file specified, if it has to be created. By default it takes 0x666. Following is the table, which gives the possible values of MODE. Sr.No. Entities & Definition 1 O_RDWR Read and Write 2 O_RDONLY Read Only 3 O_WRONLY Write Only 4 O_CREAT Create the file 5 O_APPEND Append the file 6 O_TRUNC Truncate the file 7 O_EXCL Stops if file already exists 8 O_NONBLOCK Non-Blocking usability Close Function To close a filehandle, and therefore disassociate the filehandle from the corresponding file, you use the close function. This flushes the filehandle's buffers and closes the system's file descriptor. close FILEHANDLE close If no FILEHANDLE is specified, then it closes the currently selected filehandle. It returns true only if it could successfully flush the buffers and close the file. close(DATA) || die "Couldn't close file properly"; Reading and Writing Files Once you have an open filehandle, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file. The <FILEHANDL> Operator The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, it returns a single line from the filehandle. For example − #!/usr/bin/perl print "What is your name?\n"; $name = <STDIN>; print "Hello $name\n"; When you use the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array − #!/usr/bin/perl open(DATA,"<import.txt") or die "Can't open data"; @lines = <DATA>; close(DATA); getc Function The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified − getc FILEHANDLE getc If there was an error, or the filehandle is at end of file, then undef is returned instead. read Function The read function reads a block of information from the buffered filehandle: This function is used to read binary data from the file. read FILEHANDLE, SCALAR, LENGTH, OFFSET read FILEHANDLE, SCALAR, LENGTH The length of the data read is defined by LENGTH, and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function returns the number of bytes read on success, zero at end of file, or undef if there was an error. print Function For all the different methods used for reading information from filehandles, the main function for writing information back is the print function. print FILEHANDLE LIST print LIST print The print function prints the evaluated value of LIST to FILEHANDLE, or to the current output filehandle (STDOUT by default). For example − print "Hello World!\n"; Copying Files Here is the example, which opens an existing file file1.txt and read it line by line and generate another copy file file2.txt. #!/usr/bin/perl # Open file to read open(DATA1, "<file1.txt"); # Open new file to write open(DATA2, ">file2.txt"); # Copy data from one file to another. while(<DATA1>) { print DATA2 $_; } close( DATA1 ); close( DATA2 ); Renaming a file Here is an example, which shows how we can rename a file file1.txt to file2.txt. Assuming file is available in /usr/test directory. #!/usr/bin/perl rename ("/usr/test/file1.txt", "/usr/test/file2.txt" ); This function renames takes two arguments and it just renames the existing file. Deleting an Existing File Here is an example, which shows how to delete a file file1.txt using the unlink function. #!/usr/bin/perl unlink ("/usr/test/file1.txt"); Positioning inside a File You can use to tell function to know the current position of a file and seek function to point a particular position inside the file. tell Function The first requirement is to find your position within a file, which you do using the tell function − tell FILEHANDLE tell This returns the position of the file pointer, in bytes, within FILEHANDLE if specified, or the current default selected filehandle if none is specified. seek Function The seek function positions the file pointer to the specified number of bytes within a file − seek FILEHANDLE, POSITION, WHENCE The function uses the fseek system function, and you have the same ability to position relative to three different points: the start, the end, and the current position. You do this by specifying a value for WHENCE. Zero sets the positioning relative to the start of the file. For example, the line sets the file pointer to the 256th byte in the file. seek DATA, 256, 0; File Information You can test certain features very quickly within Perl using a series of test operators known collectively as -X tests. For example, to perform a quick test of the various permissions on a file, you might use a script like this − #/usr/bin/perl my $file = "/usr/test/file1.txt"; my (@description, $size); if (-e $file) { push @description, 'binary' if (-B _); push @description, 'a socket' if (-S _); push @description, 'a text file' if (-T _); push @description, 'a block special file' if (-b _); push @description, 'a character special file' if (-c _); push @description, 'a directory' if (-d _); push @description, 'executable' if (-x _); push @description, (($size = -s _)) ? "$size bytes" : 'empty'; print "$file is ", join(', ',@description),"\n"; } Here is the list of features, which you can check for a file or directory − Sr.No. Operator & Definition 1 -A Script start time minus file last access time, in days. 2 -B Is it a binary file? 3 -C Script start time minus file last inode change time, in days. 3 -M Script start time minus file modification time, in days. 4 -O Is the file owned by the real user ID? 5 -R Is the file readable by the real user ID or real group? 6 -S Is the file a socket? 7 -T Is it a text file? 8 -W Is the file writable by the real user ID or real group? 9 -X Is the file executable by the real user ID or real group? 10 -b Is it a block special file? 11 -c Is it a character special file? 12 -d Is the file a directory? 13 -e Does the file exist? 14 -f Is it a plain file? 15 -g Does the file have the setgid bit set? 16 -k Does the file have the sticky bit set? 17 -l Is the file a symbolic link? 18 -o Is the file owned by the effective user ID? 19 -p Is the file a named pipe? 20 -r Is the file readable by the effective user or group ID? 21 -s Returns the size of the file, zero size = empty file. 22 -t Is the filehandle opened by a TTY (terminal)? 23 -u Does the file have the setuid bit set? 24 -w Is the file writable by the effective user or group ID? 25 -x Is the file executable by the effective user or group ID? 26 -z Is the file size zero? Perl - Directories Following are the standard functions used to play with directories. opendir DIRHANDLE, EXPR # To open a directory readdir DIRHANDLE # To read a directory rewinddir DIRHANDLE # Positioning pointer to the begining telldir DIRHANDLE # Returns current position of the dir seekdir DIRHANDLE, POS # Pointing pointer to POS inside dir closedir DIRHANDLE # Closing a directory. Display all the Files There are various ways to list down all the files available in a particular directory. First let's use the simple way to get and list down all the files using the glob operator − #!/usr/bin/perl # Display all the files in /tmp directory. $dir = "/tmp/*"; my @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; } # Display all the C source files in /tmp directory. $dir = "/tmp/*.c"; @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; } # Display all the hidden files. $dir = "/tmp/.*"; @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; } # Display all the files from /tmp and /home directories. $dir = "/tmp/* /home/*"; @files = glob( $dir ); foreach (@files ) { print $_ . "\n"; } Here is another example, which opens a directory and list out all the files available inside this directory. #!/usr/bin/perl opendir (DIR, '.') or die "Couldn't open directory, $!"; while ($file = readdir DIR) { print "$file\n"; } closedir DIR; One more example to print the list of C source files you might use is − #!/usr/bin/perl opendir(DIR, '.') or die "Couldn't open directory, $!"; foreach (sort grep(/^.*\.c$/,readdir(DIR))) { print "$_\n"; } closedir DIR; Create new Directory You can use mkdir function to create a new directory. You will need to have the required permission to create a directory. #!/usr/bin/perl $dir = "/tmp/perl"; # This creates perl directory in /tmp directory. mkdir( $dir ) or die "Couldn't create $dir directory, $!"; print "Directory created successfully\n"; Remove a directory You can use rmdir function to remove a directory. You will need to have the required permission to remove a directory. Additionally this directory should be empty before you try to remove it. #!/usr/bin/perl $dir = "/tmp/perl"; # This removes perl directory from /tmp directory. rmdir( $dir ) or die "Couldn't remove $dir directory, $!"; print "Directory removed successfully\n"; Change a Directory You can use chdir function to change a directory and go to a new location. You will need to have the required permission to change a directory and go inside the new directory. #!/usr/bin/perl $dir = "/home"; # This changes perl directory and moves you inside /home directory. chdir( $dir ) or die "Couldn't go inside $dir directory, $!"; print "Your new location is $dir\n"; Perl - Error Handling The execution and the errors always go together. If you are opening a file which does not exist. then if you did not handle this situation properly then your program is considered to be of bad quality. The program stops if an error occurs. So a proper error handling is used to handle various type of errors, which may occur during a program execution and take appropriate action instead of halting program completely. You can identify and trap an error in a number of different ways. Its very easy to trap errors in Perl and then handling them properly. Here are few methods which can be used. The if statement The if statement is the obvious choice when you need to check the return value from a statement; for example − if(open(DATA, $file)) { ... } else { die "Error: Couldn't open the file - $!"; } Here variable $! returns the actual error message. Alternatively, we can reduce the statement to one line in situations where it makes sense to do so; for example − open(DATA, $file) || die "Error: Couldn't open the file $!"; The unless Function The unless function is the logical opposite to if: statements can completely bypass the success status and only be executed if the expression returns false. For example − unless(chdir("/etc")) { die "Error: Can't change directory - $!"; } The unless statement is best used when you want to raise an error or alternative only if the expression fails. The statement also makes sense when used in a single-line statement − die "Error: Can't change directory!: $!" unless(chdir("/etc")); Here we die only if the chdir operation fails, and it reads nicely. The ternary Operator For very short tests, you can use the conditional operator ?: print(exists($hash{value}) ? 'There' : 'Missing',"\n"); It's not quite so clear here what we are trying to achieve, but the effect is the same as using an if or unless statement. The conditional operator is best used when you want to quickly return one of the two values within an expression or statement. The warn Function The warn function just raises a warning, a message is printed to STDERR, but no further action is taken. So it is more useful if you just want to print a warning for the user and proceed with rest of the operation − chdir('/etc') or warn "Can't change directory"; The die Function The die function works just like warn, except that it also calls exit. Within a normal script, this function has the effect of immediately terminating execution. You should use this function in case it is useless to proceed if there is an error in the program − chdir('/etc') or die "Can't change directory"; Errors within Modules There are two different situations we should be able to handle − • Reporting an error in a module that quotes the module's filename and line number - this is useful when debugging a module, or when you specifically want to raise a module-related, rather than script-related, error. • Reporting an error within a module that quotes the caller's information so that you can debug the line within the script that caused the error. Errors raised in this fashion are useful to the end-user, because they highlight the error in relation to the calling script's origination line. The warn and die functions work slightly differently than you would expect when called from within a module. For example, the simple module − package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { warn "Error in module!"; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at T.pm line 9. This is more or less what you might expected, but not necessarily what you want. From a module programmer's perspective, the information is useful because it helps to point to a bug within the module itself. For an end-user, the information provided is fairly useless, and for all but the hardened programmer, it is completely pointless. The solution for such problems is the Carp module, which provides a simplified method for reporting errors within modules that return information about the calling script. The Carp module provides four functions: carp, cluck, croak, and confess. These functions are discussed below. The carp Function The carp function is the basic equivalent of warn and prints the message to STDERR without actually exiting the script and printing the script name. package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { carp "Error in module!"; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at test.pl line 4 The cluck Function The cluck function is a sort of supercharged carp, it follows the same basic principle but also prints a stack trace of all the modules that led to the function being called, including the information on the original script. package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp qw(cluck); sub function { cluck "Error in module!"; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at T.pm line 9 T::function() called at test.pl line 4 The croak Function The croak function is equivalent to die, except that it reports the caller one level up. Like die, this function also exits the script after reporting the error to STDERR − package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { croak "Error in module!"; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at test.pl line 4 As with carp, the same basic rules apply regarding the including of line and file information according to the warn and die functions. The confess Function The confess function is like cluck; it calls die and then prints a stack trace all the way up to the origination script. package T; require Exporter; @ISA = qw/Exporter/; @EXPORT = qw/function/; use Carp; sub function { confess "Error in module!"; } 1; When called from a script like below − use T; function(); It will produce the following result − Error in module! at T.pm line 9 T::function() called at test.pl line 4 Perl - Special Variables There are some variables which have a predefined and special meaning in Perl. They are the variables that use punctuation characters after the usual variable indicator ($, @, or %), such as $_ ( explained below ). Most of the special variables have an english like long name, e.g., Operating System Error variable $! can be written as $OS_ERROR. But if you are going to use english like names, then you would have to put one line use English; at the top of your program file. This guides the interpreter to pickup exact meaning of the variable. The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; } When executed, this will produce the following result − hickory dickory doc Again, let's check the same example without using $_ variable explicitly − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print; print "\n"; } When executed, this will also produce the following result − hickory dickory doc The first time the loop is executed, "hickory" is printed. The second time around, "dickory" is printed, and the third time, "doc" is printed. That's because in each iteration of the loop, the current string is placed in $_, and is used by default by print. Here are the places where Perl will assume $_ even if you don't specify it − • Various unary functions, including functions like ord and int, as well as the all file tests (-f, -d) except for -t, which defaults to STDIN. • Various list functions like print and unlink. • The pattern-matching operations m//, s///, and tr/// when used without an =~ operator. • The default iterator variable in a foreach loop if no other variable is supplied. • The implicit iterator variable in the grep and map functions. • The default place to put an input record when a line-input operation's result is tested by itself as the sole criterion of a while test (i.e., ). Note that outside of a while test, this will not happen. Special Variable Types Based on the usage and nature of special variables, we can categorize them in the following categories − • Global Scalar Special Variables. • Global Array Special Variables. • Global Hash Special Variables. • Global Special Filehandles. • Global Special Constants. • Regular Expression Special Variables. • Filehandle Special Variables. Global Scalar Special Variables Here is the list of all the scalar special variables. We have listed corresponding english like names along with the symbolic names. $_ The default input and pattern-searching space. $ARG $. The current input line number of the last filehandle that was read. An explicit close on the filehandle resets the line number. $NR $/ The input record separator; newline by default. If set to the null string, it treats blank lines as delimiters. $RS $, The output field separator for the print operator. $OFS $\ The output record separator for the print operator. $ORS $" Like "$," except that it applies to list values interpolated into a double-quoted string (or similar interpreted string). Default is a space. $LIST_SEPARATOR $; The subscript separator for multidimensional array emulation. Default is "\034". $SUBSCRIPT_SEPARATOR $^L What a format outputs to perform a formfeed. Default is "\f". $FORMAT_FORMFEED $: The current set of characters after which a string may be broken to fill continuation fields (starting with ^) in a format. Default is "\n"". $FORMAT_LINE_BREAK_CHARACTERS $^A The current value of the write accumulator for format lines. $ACCUMULATOR $# Contains the output format for printed numbers (deprecated). $OFMT $? The status returned by the last pipe close, backtick (``) command, or system operator. $CHILD_ERROR $! If used in a numeric context, yields the current value of the errno variable, identifying the last system call error. If used in a string context, yields the corresponding system error string. $OS_ERROR or $ERRNO $@ The Perl syntax error message from the last eval command. $EVAL_ERROR $$ The pid of the Perl process running this script. $PROCESS_ID or $PID $< The real user ID (uid) of this process. $REAL_USER_ID or $UID $> The effective user ID of this process. $EFFECTIVE_USER_ID or $EUID $( The real group ID (gid) of this process. $REAL_GROUP_ID or $GID $) The effective gid of this process. $EFFECTIVE_GROUP_ID or $EGID $0 Contains the name of the file containing the Perl script being executed. $PROGRAM_NAME $[ The index of the first element in an array and of the first character in a substring. Default is 0. $] Returns the version plus patchlevel divided by 1000. $PERL_VERSION $^D The current value of the debugging flags. $DEBUGGING $^E Extended error message on some platforms. $EXTENDED_OS_ERROR $^F The maximum system file descriptor, ordinarily 2. $SYSTEM_FD_MAX $^H Contains internal compiler hints enabled by certain pragmatic modules. $^I The current value of the inplace-edit extension. Use undef to disable inplace editing. $INPLACE_EDIT $^M The contents of $M can be used as an emergency memory pool in case Perl dies with an out-of-memory error. Use of $M requires a special compilation of Perl. See the INSTALL document for more information. $^O Contains the name of the operating system that the current Perl binary was compiled for. $OSNAME $^P The internal flag that the debugger clears so that it doesn't debug itself. $PERLDB $^T The time at which the script began running, in seconds since the epoch. $BASETIME $^W The current value of the warning switch, either true or false. $WARNING $^X The name that the Perl binary itself was executed as. $EXECUTABLE_NAME $ARGV Contains the name of the current file when reading from <ARGV>. Global Array Special Variables @ARGV The array containing the command-line arguments intended for the script. @INC The array containing the list of places to look for Perl scripts to be evaluated by the do, require, or use constructs. @F The array into which the input lines are split when the -a command-line switch is given. Global Hash Special Variables %INC The hash containing entries for the filename of each file that has been included via do or require. %ENV The hash containing your current environment. %SIG The hash used to set signal handlers for various signals. Global Special Filehandles ARGV The special filehandle that iterates over command line filenames in @ARGV. Usually written as the null filehandle in <>. STDERR The special filehandle for standard error in any package. STDIN The special filehandle for standard input in any package. STDOUT The special filehandle for standard output in any package. DATA The special filehandle that refers to anything following the __END__ token in the file containing the script. Or, the special filehandle for anything following the __DATA__ token in a required file, as long as you're reading data in the same package __DATA__ was found in. _ (underscore) The special filehandle used to cache the information from the last stat, lstat, or file test operator. Global Special Constants __END__ Indicates the logical end of your program. Any following text is ignored, but may be read via the DATA filehandle. __FILE__ Represents the filename at the point in your program where it's used. Not interpolated into strings. __LINE__ Represents the current line number. Not interpolated into strings. __PACKAGE__ Represents the current package name at compile time, or undefined if there is no current package. Not interpolated into strings. Regular Expression Special Variables $digit Contains the text matched by the corresponding set of parentheses in the last pattern matched. For example, $1 matches whatever was contained in the first set of parentheses in the previous regular expression. $& The string matched by the last successful pattern match. $MATCH $` The string preceding whatever was matched by the last successful pattern match. $PREMATCH $' The string following whatever was matched by the last successful pattern match. $POSTMATCH $+ The last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns was matched. For example : /Version: (.*)|Revision: (.*)/ && ($rev = $+); $LAST_PAREN_MATCH Filehandle Special Variables $| If set to nonzero, forces an fflush(3) after every write or print on the currently selected output channel. $OUTPUT_AUTOFLUSH $% The current page number of the currently selected output channel. $FORMAT_PAGE_NUMBER $= The current page length (printable lines) of the currently selected output channel. Default is 60. $FORMAT_LINES_PER_PAGE $- The number of lines left on the page of the currently selected output channel. $FORMAT_LINES_LEFT $~ The name of the current report format for the currently selected output channel. Default is the name of the filehandle. $FORMAT_NAME $^ The name of the current top-of-page format for the currently selected output channel. Default is the name of the filehandle with _TOP appended. $FORMAT_TOP_NAME Perl - Coding Standard Each programmer will, of course, have his or her own preferences in regards to formatting, but there are some general guidelines that will make your programs easier to read, understand, and maintain. The most important thing is to run your programs under the -w flag at all times. You may turn it off explicitly for particular portions of code via the no warnings pragma or the $^W variable if you must. You should also always run under use strict or know the reason why not. The use sigtrap and even use diagnostics pragmas may also prove useful. Regarding aesthetics of code lay out, about the only thing Larry cares strongly about is that the closing curly bracket of a multi-line BLOCK should line up with the keyword that started the construct. Beyond that, he has other preferences that aren't so strong − • 4-column indent. • Opening curly on same line as keyword, if possible, otherwise line up. • Space before the opening curly of a multi-line BLOCK. • One-line BLOCK may be put on one line, including curlies. • No space before the semicolon. • Semicolon omitted in "short" one-line BLOCK. • Space around most operators. • Space around a "complex" subscript (inside brackets). • Blank lines between chunks that do different things. • Uncuddled elses. • No space between function name and its opening parenthesis. • Space after each comma. • Long lines broken after an operator (except and and or). • Space after last parenthesis matching on current line. • Line up corresponding items vertically. • Omit redundant punctuation as long as clarity doesn't suffer. Here are some other more substantive style issues to think about: Just because you CAN do something a particular way doesn't mean that you SHOULD do it that way. Perl is designed to give you several ways to do anything, so consider picking the most readable one. For instance − open(FOO,$foo) || die "Can't open $foo: $!"; Is better than − die "Can't open $foo: $!" unless open(FOO,$foo); Because the second way hides the main point of the statement in a modifier. On the other hand, print "Starting analysis\n" if $verbose; Is better than − $verbose && print "Starting analysis\n"; Because the main point isn't whether the user typed -v or not. Don't go through silly contortions to exit a loop at the top or the bottom, when Perl provides the last operator so you can exit in the middle. Just "outdent" it a little to make it more visible − LINE: for (;;) { statements; last LINE if $foo; next LINE if /^#/; statements; } Let's see few more important points − • Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the previous example. • Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead. • For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed. • Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem. • While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS. • Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for "pragma" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes. • If you have a really hairy regular expression, use the /x modifier and put in some whitespace to make it look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or backslashes. • Always check the return codes of system calls. Good error messages should go to STDERR, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple but sufficient example − opendir(D, $dir) or die "can't opendir $dir: $!"; • Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and use warnings (or -w) in effect. Consider giving away your code. Consider changing your whole world view. Consider... oh, never mind. • Be consistent. • Be nice. Perl - Regular Expressions A regular expression is a string of characters that defines the pattern or patterns you are viewing. The syntax of regular expressions in Perl is very similar to what you will find within other regular expression.supporting programs, such as sed, grep, and awk. The basic method for applying a regular expression is to use the pattern binding operators =~ and !~. The first operator is a test and assignment operator. There are three regular expression operators within Perl. • Match Regular Expression - m// • Substitute Regular Expression - s/// • Transliterate Regular Expression - tr/// The forward slashes in each case act as delimiters for the regular expression (regex) that you are specifying. If you are comfortable with any other delimiter, then you can use in place of forward slash. The Match Operator The match operator, m//, is used to match a string or statement to a regular expression. For example, to match the character sequence "foo" against the scalar $bar, you might use a statement like this − #!/usr/bin/perl $bar = "This is foo and again foo"; if ($bar =~ /foo/) { print "First time is matching\n"; } else { print "First time is not matching\n"; } $bar = "foo"; if ($bar =~ /foo/) { print "Second time is matching\n"; } else { print "Second time is not matching\n"; } When above program is executed, it produces the following result − First time is matching Second time is matching The m// actually works in the same fashion as the q// operator series.you can use any combination of naturally matching characters to act as delimiters for the expression. For example, m{}, m(), and m>< are all valid. So above example can be re-written as follows − #!/usr/bin/perl $bar = "This is foo and again foo"; if ($bar =~ m[foo]) { print "First time is matching\n"; } else { print "First time is not matching\n"; } $bar = "foo"; if ($bar =~ m{foo}) { print "Second time is matching\n"; } else { print "Second time is not matching\n"; } You can omit m from m// if the delimiters are forward slashes, but for all other delimiters you must use the m prefix. Note that the entire match expression, that is the expression on the left of =~ or !~ and the match operator, returns true (in a scalar context) if the expression matches. Therefore the statement − $true = ($foo =~ m/foo/); will set $true to 1 if $foo matches the regex, or 0 if the match fails. In a list context, the match returns the contents of any grouped expressions. For example, when extracting the hours, minutes, and seconds from a time string, we can use − my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/); Match Operator Modifiers The match operator supports its own set of modifiers. The /g modifier allows for global matching. The /i modifier will make the match case insensitive. Here is the complete list of modifiers Sr.No. Modifier & Description 1 i Makes the match case insensitive. 2 m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary. 3 o Evaluates the expression only once. 4 s Allows use of . to match a newline character. 5 x Allows you to use white space in the expression for clarity. 6 g Globally finds all matches. 7 cg Allows the search to continue even after a global match fails. Matching Only Once There is also a simpler version of the match operator - the ?PATTERN? operator. This is basically identical to the m// operator except that it only matches once within the string you are searching between each call to reset. For example, you can use this to get the first and last elements within a list − #!/usr/bin/perl @list = qw/food foosball subeo footnote terfoot canic footbrdige/; foreach (@list) { $first = $1 if /(foo.*?)/; $last = $1 if /(foo.*)/; } print "First: $first, Last: $last\n"; When above program is executed, it produces the following result − First: foo, Last: footbrdige Regular Expression Variables Regular expression variables include $, which contains whatever the last grouping match matched; $&, which contains the entire matched string; $`, which contains everything before the matched string; and $', which contains everything after the matched string. Following code demonstrates the result − #!/usr/bin/perl $string = "The food is in the salad bar"; $string =~ m/foo/; print "Before: $`\n"; print "Matched: $&\n"; print "After: $'\n"; When above program is executed, it produces the following result − Before: The Matched: foo After: d is in the salad bar The Substitution Operator The substitution operator, s///, is really just an extension of the match operator that allows you to replace the text matched with some new text. The basic form of the operator is − s/PATTERN/REPLACEMENT/; The PATTERN is the regular expression for the text that we are looking for. The REPLACEMENT is a specification for the text or regular expression that we want to use to replace the found text with. For example, we can replace all occurrences of dog with cat using the following regular expression − #/user/bin/perl $string = "The cat sat on the mat"; $string =~ s/cat/dog/; print "$string\n"; When above program is executed, it produces the following result − The dog sat on the mat Substitution Operator Modifiers Here is the list of all the modifiers used with substitution operator. Sr.No. Modifier & Description 1 i Makes the match case insensitive. 2 m Specifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary. 3 o Evaluates the expression only once. 4 s Allows use of . to match a newline character. 5 x Allows you to use white space in the expression for clarity. 6 g Replaces all occurrences of the found expression with the replacement text. 7 e Evaluates the replacement as if it were a Perl statement, and uses its return value as the replacement text. The Translation Operator Translation is similar, but not identical, to the principles of substitution, but unlike substitution, translation (or transliteration) does not use regular expressions for its search on replacement values. The translation operators are − tr/SEARCHLIST/REPLACEMENTLIST/cds y/SEARCHLIST/REPLACEMENTLIST/cds The translation replaces all occurrences of the characters in SEARCHLIST with the corresponding characters in REPLACEMENTLIST. For example, using the "The cat sat on the mat." string we have been using in this chapter − #/user/bin/perl $string = 'The cat sat on the mat'; $string =~ tr/a/o/; print "$string\n"; When above program is executed, it produces the following result − The cot sot on the mot. Standard Perl ranges can also be used, allowing you to specify ranges of characters either by letter or numerical value. To change the case of the string, you might use the following syntax in place of the uc function. $string =~ tr/a-z/A-Z/; Translation Operator Modifiers Following is the list of operators related to translation. Sr.No. Modifier & Description 1 c Complements SEARCHLIST. 2 d Deletes found but unreplaced characters. 3 s Squashes duplicate replaced characters. The /d modifier deletes the characters matching SEARCHLIST that do not have a corresponding entry in REPLACEMENTLIST. For example − #!/usr/bin/perl $string = 'the cat sat on the mat.'; $string =~ tr/a-z/b/d; print "$string\n"; When above program is executed, it produces the following result − b b b. The last modifier, /s, removes the duplicate sequences of characters that were replaced, so − #!/usr/bin/perl $string = 'food'; $string = 'food'; $string =~ tr/a-z/a-z/s; print "$string\n"; When above program is executed, it produces the following result − fod More Complex Regular Expressions You don't just have to match on fixed strings. In fact, you can match on just about anything you could dream of by using more complex regular expressions. Here's a quick cheat sheet − Following table lists the regular expression syntax that is available in Python. Sr.No. Pattern & Description 1 ^ Matches beginning of line. 2 $ Matches end of line. 3 . Matches any single character except newline. Using m option allows it to match newline as well. 4 [...] Matches any single character in brackets. 5 [^...] Matches any single character not in brackets. 6 * Matches 0 or more occurrences of preceding expression. 7 + Matches 1 or more occurrence of preceding expression. 8 ? Matches 0 or 1 occurrence of preceding expression. 9 { n} Matches exactly n number of occurrences of preceding expression. 10 { n,} Matches n or more occurrences of preceding expression. 11 { n, m} Matches at least n and at most m occurrences of preceding expression. 12 a| b Matches either a or b. 13 \w Matches word characters. 14 \W Matches nonword characters. 15 \s Matches whitespace. Equivalent to [\t\n\r\f]. 16 \S Matches nonwhitespace. 17 \d Matches digits. Equivalent to [0-9]. 18 \D Matches nondigits. 19 \A Matches beginning of string. 20 \Z Matches end of string. If a newline exists, it matches just before newline. 21 \z Matches end of string. 22 \G Matches point where last match finished. 23 \b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. 24 \B Matches nonword boundaries. 25 \n, \t, etc. Matches newlines, carriage returns, tabs, etc. 26 \1...\9 Matches nth grouped subexpression. 27 \10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code. 28 [aeiou] Matches a single character in the given set 29 [^aeiou] Matches a single character outside the given set The ^ metacharacter matches the beginning of the string and the $ metasymbol matches the end of the string. Here are some brief examples. # nothing in the string (start and end are adjacent) /^$/ # a three digits, each followed by a whitespace # character (eg "3 4 5 ") /(\d\s) {3}/ # matches a string in which every # odd-numbered letter is a (eg "abacadaf") /(a.)+/ # string starts with one or more digits /^\d+/ # string that ends with one or more digits /\d+$/ Lets have a look at another example. #!/usr/bin/perl $string = "Cats go Catatonic\nWhen given Catnip"; ($start) = ($string =~ /\A(.*?) /); @lines = $string =~ /^(.*?) /gm; print "First word: $start\n","Line starts: @lines\n"; When above program is executed, it produces the following result − First word: Cats Line starts: Cats When Matching Boundaries The \b matches at any word boundary, as defined by the difference between the \w class and the \W class. Because \w includes the characters for a word, and \W the opposite, this normally means the termination of a word. The \B assertion matches any position that is not a word boundary. For example − /\bcat\b/ # Matches 'the cat sat' but not 'cat on the mat' /\Bcat\B/ # Matches 'verification' but not 'the cat on the mat' /\bcat\B/ # Matches 'catatonic' but not 'polecat' /\Bcat\b/ # Matches 'polecat' but not 'catatonic' Selecting Alternatives The | character is just like the standard or bitwise OR within Perl. It specifies alternate matches within a regular expression or group. For example, to match "cat" or "dog" in an expression, you might use this − if ($string =~ /cat|dog/) You can group individual elements of an expression together in order to support complex matches. Searching for two people’s names could be achieved with two separate tests, like this − if (($string =~ /Martin Brown/) || ($string =~ /Sharon Brown/)) This could be written as follows if ($string =~ /(Martin|Sharon) Brown/) Grouping Matching From a regular-expression point of view, there is no difference between except, perhaps, that the former is slightly clearer. $string =~ /(\S+)\s+(\S+)/; and $string =~ /\S+\s+\S+/; However, the benefit of grouping is that it allows us to extract a sequence from a regular expression. Groupings are returned as a list in the order in which they appear in the original. For example, in the following fragment we have pulled out the hours, minutes, and seconds from a string. my ($hours, $minutes, $seconds) = ($time =~ m/(\d+):(\d+):(\d+)/); As well as this direct method, matched groups are also available within the special $x variables, where x is the number of the group within the regular expression. We could therefore rewrite the preceding example as follows − #!/usr/bin/perl $time = "12:05:30"; $time =~ m/(\d+):(\d+):(\d+)/; my ($hours, $minutes, $seconds) = ($1, $2, $3); print "Hours : $hours, Minutes: $minutes, Second: $seconds\n"; When above program is executed, it produces the following result − Hours : 12, Minutes: 05, Second: 30 When groups are used in substitution expressions, the $x syntax can be used in the replacement text. Thus, we could reformat a date string using this − #!/usr/bin/perl $date = '03/26/1999'; $date =~ s#(\d+)/(\d+)/(\d+)#$3/$1/$2#; print "$date\n"; When above program is executed, it produces the following result − 1999/03/26 The \G Assertion The \G assertion allows you to continue searching from the point where the last match occurred. For example, in the following code, we have used \G so that we can search to the correct position and then extract some information, without having to create a more complex, single regular expression − #!/usr/bin/perl $string = "The time is: 12:31:02 on 4/12/00"; $string =~ /:\s+/g; ($time) = ($string =~ /\G(\d+:\d+:\d+)/); $string =~ /.+\s+/g; ($date) = ($string =~ m{\G(\d+/\d+/\d+)}); print "Time: $time, Date: $date\n"; When above program is executed, it produces the following result − Time: 12:31:02, Date: 4/12/00 The \G assertion is actually just the metasymbol equivalent of the pos function, so between regular expression calls you can continue to use pos, and even modify the value of pos (and therefore \G) by using pos as an lvalue subroutine. Regular-expression Examples Literal Characters Sr.No. Example & Description 1 Perl Match "Perl". Character Classes Sr.No. Example & Description 1 [Pp]ython Matches "Python" or "python" 2 rub[ye] Matches "ruby" or "rube" 3 [aeiou] Matches any one lowercase vowel 4 [0-9] Matches any digit; same as [0123456789] 5 [a-z] Matches any lowercase ASCII letter 6 [A-Z] Matches any uppercase ASCII letter 7 [a-zA-Z0-9] Matches any of the above 8 [^aeiou] Matches anything other than a lowercase vowel 9 [^0-9] Matches anything other than a digit Special Character Classes Sr.No. Example & Description 1 . Matches any character except newline 2 \d Matches a digit: [0-9] 3 \D Matches a nondigit: [^0-9] 4 \s Matches a whitespace character: [ \t\r\n\f] 5 \S Matches nonwhitespace: [^ \t\r\n\f] 6 \w Matches a single word character: [A-Za-z0-9_] 7 \W Matches a nonword character: [^A-Za-z0-9_] Repetition Cases Sr.No. Example & Description 1 ruby? Matches "rub" or "ruby": the y is optional 2 ruby* Matches "rub" plus 0 or more ys 3 ruby+ Matches "rub" plus 1 or more ys 4 \d{3} Matches exactly 3 digits 5 \d{3,} Matches 3 or more digits 6. \d{3,5} Matches 3, 4, or 5 digits Nongreedy Repetition This matches the smallest number of repetitions − Sr.No. Example & Description 1 <.*> Greedy repetition: matches "<python>perl>" 2 <.*?> Nongreedy: matches "<python>" in "<python>perl>" Grouping with Parentheses Sr.No. Example & Description 1 \D\d+ No group: + repeats \d 2 (\D\d)+ Grouped: + repeats \D\d pair 3 ([Pp]ython(, )?)+ Match "Python", "Python, python, python", etc. Backreferences This matches a previously matched group again − Sr.No. Example & Description 1 ([Pp])ython&\1ails Matches python&pails or Python&Pails 2 (['"])[^\1]*\1 Single or double-quoted string. \1 matches whatever the 1st group matched. \2 matches whatever the 2nd group matched, etc. Alternatives Sr.No. Example & Description 1 python|perl Matches "python" or "perl" 2 rub(y|le)) Matches "ruby" or "ruble" 3 Python(!+|\?) "Python" followed by one or more ! or one ? Anchors This need to specify match positions. Sr.No. Example & Description 1 ^Python Matches "Python" at the start of a string or internal line 2 Python$ Matches "Python" at the end of a string or line 3 \APython Matches "Python" at the start of a string 4 Python\Z Matches "Python" at the end of a string 5 \bPython\b Matches "Python" at a word boundary 6 \brub\B \B is nonword boundary: match "rub" in "rube" and "ruby" but not alone 7 Python(?=!) Matches "Python", if followed by an exclamation point 8 Python(?!!) Matches "Python", if not followed by an exclamation point Special Syntax with Parentheses Sr.No. Example & Description 1 R(?#comment) Matches "R". All the rest is a comment 2 R(?i)uby Case-insensitive while matching "uby" 3 R(?i:uby) Same as above 4 rub(?:y|le)) Group only without creating \1 backreference Perl - Sending Email Using sendmail Utility Sending a Plain Message If you are working on Linux/Unix machine then you can simply use sendmail utility inside your Perl program to send email. Here is a sample script that can send an email to a given email ID. Just make sure the given path for sendmail utility is correct. This may be different for your Linux/Unix machine. #!/usr/bin/perl $to = '[email protected]'; $from = '[email protected]'; $subject = 'Test Email'; $message = 'This is test email sent by Perl Script'; open(MAIL, "|/usr/sbin/sendmail -t"); # Email Header print MAIL "To: $to\n"; print MAIL "From: $from\n"; print MAIL "Subject: $subject\n\n"; # Email Body print MAIL $message; close(MAIL); print "Email Sent Successfully\n"; Actually, the above script is a client email script, which will draft email and submit to the server running locally on your Linux/Unix machine. This script will not be responsible for sending email to actual destination. So you have to make sure email server is properly configured and running on your machine to send email to the given email ID. Sending an HTML Message If you want to send HTML formatted email using sendmail, then you simply need to add Content-type: text/html\n in the header part of the email as follows − #!/usr/bin/perl $to = '[email protected]'; $from = '[email protected]'; $subject = 'Test Email'; $message = '<h1>This is test email sent by Perl Script</h1>'; open(MAIL, "|/usr/sbin/sendmail -t"); # Email Header print MAIL "To: $to\n"; print MAIL "From: $from\n"; print MAIL "Subject: $subject\n\n"; print MAIL "Content-type: text/html\n"; # Email Body print MAIL $message; close(MAIL); print "Email Sent Successfully\n"; Using MIME::Lite Module If you are working on windows machine, then you will not have access on sendmail utility. But you have alternate to write your own email client using MIME:Lite perl module. You can download this module from MIME-Lite-3.01.tar.gz and install it on your either machine Windows or Linux/Unix. To install it follow the simple steps − $tar xvfz MIME-Lite-3.01.tar.gz $cd MIME-Lite-3.01 $perl Makefile.PL $make $make install That's it and you will have MIME::Lite module installed on your machine. Now you are ready to send your email with simple scripts explained below. Sending a Plain Message Now following is a script which will take care of sending email to the given email ID − #!/usr/bin/perl use MIME::Lite; $to = '[email protected]'; $cc = '[email protected]'; $from = '[email protected]'; $subject = 'Test Email'; $message = 'This is test email sent by Perl Script'; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Data => $message ); $msg->send; print "Email Sent Successfully\n"; Sending an HTML Message If you want to send HTML formatted email using sendmail, then you simply need to add Content-type: text/html\n in the header part of the email. Following is the script, which will take care of sending HTML formatted email − #!/usr/bin/perl use MIME::Lite; $to = '[email protected]'; $cc = '[email protected]'; $from = '[email protected]'; $subject = 'Test Email'; $message = '<h1>This is test email sent by Perl Script</h1>'; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Data => $message ); $msg->attr("content-type" => "text/html"); $msg->send; print "Email Sent Successfully\n"; Sending an Attachment If you want to send an attachment, then following script serves the purpose − #!/usr/bin/perl use MIME::Lite; $to = '[email protected]'; $cc = '[email protected]'; $from = '[email protected]'; $subject = 'Test Email'; $message = 'This is test email sent by Perl Script'; $msg = MIME::Lite->new( From => $from, To => $to, Cc => $cc, Subject => $subject, Type => 'multipart/mixed' ); # Add your text message. $msg->attach(Type => 'text', Data => $message ); # Specify your file as attachement. $msg->attach(Type => 'image/gif', Path => '/tmp/logo.gif', Filename => 'logo.gif', Disposition => 'attachment' ); $msg->send; print "Email Sent Successfully\n"; You can attach as many files as you like in your email using attach() method. Using SMTP Server If your machine is not running an email server then you can use any other email server available at the remote location. But to use any other email server you will need to have an id, its password, URL, etc. Once you have all the required information, you simple need to provide that information in send() method as follows − $msg->send('smtp', "smtp.myisp.net", AuthUser=>"id", AuthPass=>"password" ); You can contact your email server administrator to have the above used information and if a user id and password is not already available then your administrator can create it in minutes. Perl - Socket Programming What is a Socket? Socket is a Berkeley UNIX mechanism of creating a virtual duplex connection between different processes. This was later ported on to every known OS enabling communication between systems across geographical location running on different OS software. If not for the socket, most of the network communication between systems would never ever have happened. Taking a closer look; a typical computer system on a network receives and sends information as desired by the various applications running on it. This information is routed to the system, since a unique IP address is designated to it. On the system, this information is given to the relevant applications, which listen on different ports. For example an internet browser listens on port 80 for information received from the web server. Also we can write our custom applications which may listen and send/receive information on a specific port number. For now, let's sum up that a socket is an IP address and a port, enabling connection to send and recieve data over a network. To explain above mentioned socket concept we will take an example of Client - Server Programming using Perl. To complete a client server architecture we would have to go through the following steps − To Create a Server • Create a socket using socket call. • Bind the socket to a port address using bind call. • Listen to the socket at the port address using listen call. • Accept client connections using accept call. To Create a Client • Create a socket with socket call. • Connect (the socket) to the server using connect call. Following diagram shows the complete sequence of the calls used by Client and Server to communicate with each other − Perl Socket Server Side Socket Calls The socket() call The socket() call is the first call in establishing a network connection is creating a socket. This call has the following syntax − socket( SOCKET, DOMAIN, TYPE, PROTOCOL ); The above call creates a SOCKET and other three arguments are integers which should have the following values for TCP/IP connections. • DOMAIN should be PF_INET. It's probable 2 on your computer. • TYPE should be SOCK_STREAM for TCP/IP connection. • PROTOCOL should be (getprotobyname('tcp'))[2]. It is the particular protocol such as TCP to be spoken over the socket. So socket function call issued by the server will be something like this − use Socket # This defines PF_INET and SOCK_STREAM socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]); The bind() call The sockets created by socket() call are useless until they are bound to a hostname and a port number. Server uses the following bind() function to specify the port at which they will be accepting connections from the clients. bind( SOCKET, ADDRESS ); Here SOCKET is the descriptor returned by socket() call and ADDRESS is a socket address ( for TCP/IP ) containing three elements − • The address family (For TCP/IP, that's AF_INET, probably 2 on your system). • The port number (for example 21). • The internet address of the computer (for example 10.12.12.168). As the bind() is used by a server, which does not need to know its own address so the argument list looks like this − use Socket # This defines PF_INET and SOCK_STREAM $port = 12345; # The unique port used by the sever to listen requests $server_ip_address = "10.12.12.168"; bind( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die "Can't bind to port $port! \n"; The or die clause is very important because if a server dies without outstanding connections, the port won't be immediately reusable unless you use the option SO_REUSEADDR using setsockopt() function. Here pack_sockaddr_in() function is being used to pack the Port and IP address into binary format. The listen() call If this is a server program, then it is required to issue a call to listen() on the specified port to listen, i.e., wait for the incoming requests. This call has the following syntax − listen( SOCKET, QUEUESIZE ); The above call uses SOCKET descriptor returned by socket() call and QUEUESIZE is the maximum number of outstanding connection request allowed simultaneously. The accept() call If this is a server program then it is required to issue a call to the access() function to accept the incoming connections. This call has the following syntax − accept( NEW_SOCKET, SOCKET ); The accept call receive SOCKET descriptor returned by socket() function and upon successful completion, a new socket descriptor NEW_SOCKET is returned for all future communication between the client and the server. If access() call fails, then it returns FLASE which is defined in Socket module which we have used initially. Generally, accept() is used in an infinite loop. As soon as one connection arrives the server either creates a child process to deal with it or serves it himself and then goes back to listen for more connections. while(1) { accept( NEW_SOCKET, SOCKT ); ....... } Now all the calls related to server are over and let us see a call which will be required by the client. Client Side Socket Calls The connect() call If you are going to prepare client program, then first you will use socket() call to create a socket and then you would have to use connect() call to connect to the server. You already have seen socket() call syntax and it will remain similar to server socket() call, but here is the syntax for connect() call − connect( SOCKET, ADDRESS ); Here SCOKET is the socket descriptor returned by socket() call issued by the client and ADDRESS is a socket address similar to bind call, except that it contains the IP address of the remote server. $port = 21; # For example, the ftp port $server_ip_address = "10.12.12.168"; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server_ip_address))) or die "Can't connect to port $port! \n"; If you connect to the server successfully, then you can start sending your commands to the server using SOCKET descriptor, otherwise your client will come out by giving an error message. Client - Server Example Following is a Perl code to implement a simple client-server program using Perl socket. Here server listens for incoming requests and once connection is established, it simply replies Smile from the server. The client reads that message and print on the screen. Let's see how it has been done, assuming we have our server and client on the same machine. Script to Create a Server #!/usr/bin/perl -w # Filename : server.pl use strict; use Socket; # use port 7890 as default my $port = shift || 7890; my $proto = getprotobyname('tcp'); my $server = "localhost"; # Host IP running the server # create a socket, make it reusable socket(SOCKET, PF_INET, SOCK_STREAM, $proto) or die "Can't open socket $!\n"; setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1) or die "Can't set socket option to SO_REUSEADDR $!\n"; # bind to a port, then listen bind( SOCKET, pack_sockaddr_in($port, inet_aton($server))) or die "Can't bind to port $port! \n"; listen(SOCKET, 5) or die "listen: $!"; print "SERVER started on port $port\n"; # accepting a connection my $client_addr; while ($client_addr = accept(NEW_SOCKET, SOCKET)) { # send them a message, close connection my $name = gethostbyaddr($client_addr, AF_INET ); print NEW_SOCKET "Smile from the server"; print "Connection recieved from $name\n"; close NEW_SOCKET; } To run the server in background mode issue the following command on Unix prompt − $perl sever.pl& Script to Create a Client !/usr/bin/perl -w # Filename : client.pl use strict; use Socket; # initialize host and port my $host = shift || 'localhost'; my $port = shift || 7890; my $server = "localhost"; # Host IP running the server # create the socket, connect to the port socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2]) or die "Can't create a socket $!\n"; connect( SOCKET, pack_sockaddr_in($port, inet_aton($server))) or die "Can't connect to port $port! \n"; my $line; while ($line = <SOCKET>) { print "$line\n"; } close SOCKET or die "close: $!"; Now let's start our client at the command prompt, which will connect to the server and read message sent by the server and displays the same on the screen as follows − $perl client.pl Smile from the server NOTE − If you are giving the actual IP address in dot notation, then it is recommended to provide IP address in the same format in both client as well as server to avoid any confusion. Object Oriented Programming in PERL We have already studied references in Perl and Perl anonymous arrays and hashes. Object Oriented concept in Perl is very much based on references and anonymous array and hashes. Let's start learning basic concepts of Object Oriented Perl. Object Basics There are three main terms, explained from the point of view of how Perl handles objects. The terms are object, class, and method. • An object within Perl is merely a reference to a data type that knows what class it belongs to. The object is stored as a reference in a scalar variable. Because a scalar only contains a reference to the object, the same scalar can hold different objects in different classes. • A class within Perl is a package that contains the corresponding methods required to create and manipulate objects. • A method within Perl is a subroutine, defined with the package. The first argument to the method is an object reference or a package name, depending on whether the method affects the current object or the class. Perl provides a bless() function, which is used to return a reference which ultimately becomes an object. Defining a Class It is very simple to define a class in Perl. A class is corresponding to a Perl Package in its simplest form. To create a class in Perl, we first build a package. A package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again. Perl Packages provide a separate namespace within a Perl program which keeps subroutines and variables independent from conflicting with those in other packages. To declare a class named Person in Perl we do − package Person; The scope of the package definition extends to the end of the file, or until another package keyword is encountered. Creating and Using Objects To create an instance of a class (an object) we need an object constructor. This constructor is a method defined within the package. Most programmers choose to name this object constructor method new, but in Perl you can use any name. You can use any kind of Perl variable as an object in Perl. Most Perl programmers choose either references to arrays or hashes. Let's create our constructor for our Person class using a Perl hash reference. When creating an object, you need to supply a constructor, which is a subroutine within a package that returns an object reference. The object reference is created by blessing a reference to the package's class. For example − package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print "First Name is $self->{_firstName}\n"; print "Last Name is $self->{_lastName}\n"; print "SSN is $self->{_ssn}\n"; bless $self, $class; return $self; } Now Let us see how to create an Object. $object = new Person( "Mohammad", "Saleem", 23234345); You can use simple hash in your consturctor if you don't want to assign any value to any class variable. For example − package Person; sub new { my $class = shift; my $self = {}; bless $self, $class; return $self; } Defining Methods Other object-oriented languages have the concept of security of data to prevent a programmer from changing an object data directly and they provide accessor methods to modify object data. Perl does not have private variables but we can still use the concept of helper methods to manipulate object data. Lets define a helper method to get person’s first name − sub getFirstName { return $self->{_firstName}; } Another helper function to set person’s first name − sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } Now lets have a look into complete example: Keep Person package and helper functions into Person.pm file. #!/usr/bin/perl package Person; sub new { my $class = shift; my $self = { _firstName => shift, _lastName => shift, _ssn => shift, }; # Print all the values just for clarification. print "First Name is $self->{_firstName}\n"; print "Last Name is $self->{_lastName}\n"; print "SSN is $self->{_ssn}\n"; bless $self, $class; return $self; } sub setFirstName { my ( $self, $firstName ) = @_; $self->{_firstName} = $firstName if defined($firstName); return $self->{_firstName}; } sub getFirstName { my( $self ) = @_; return $self->{_firstName}; } 1; Now let's make use of Person object in employee.pl file as follows − #!/usr/bin/perl use Person; $object = new Person( "Mohammad", "Saleem", 23234345); # Get first name which is set using constructor. $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n"; # Now Set first name using helper function. $object->setFirstName( "Mohd." ); # Now get first name set by helper function. $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n"; When we execute above program, it produces the following result − First Name is Mohammad Last Name is Saleem SSN is 23234345 Before Setting First Name is : Mohammad Before Setting First Name is : Mohd. Inheritance Object-oriented programming has very good and useful concept called inheritance. Inheritance simply means that properties and methods of a parent class will be available to the child classes. So you don't have to write the same code again and again, you can just inherit a parent class. For example, we can have a class Employee, which inherits from Person. This is referred to as an "isa" relationship because an employee is a person. Perl has a special variable, @ISA, to help with this. @ISA governs (method) inheritance. Following are the important points to be considered while using inheritance − • Perl searches the class of the specified object for the given method or attribute, i.e., variable. • Perl searches the classes defined in the object class's @ISA array. • If no method is found in steps 1 or 2, then Perl uses an AUTOLOAD subroutine, if one is found in the @ISA tree. • If a matching method still cannot be found, then Perl searches for the method within the UNIVERSAL class (package) that comes as part of the standard Perl library. • If the method still has not found, then Perl gives up and raises a runtime exception. So to create a new Employee class that will inherit methods and attributes from our Person class, we simply code as follows: Keep this code into Employee.pm. #!/usr/bin/perl package Employee; use Person; use strict; our @ISA = qw(Person); # inherits from Person Now Employee Class has all the methods and attributes inherited from Person class and you can use them as follows: Use main.pl file to test it − #!/usr/bin/perl use Employee; $object = new Employee( "Mohammad", "Saleem", 23234345); # Get first name which is set using constructor. $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n"; # Now Set first name using helper function. $object->setFirstName( "Mohd." ); # Now get first name set by helper function. $firstName = $object->getFirstName(); print "After Setting First Name is : $firstName\n"; When we execute above program, it produces the following result − First Name is Mohammad Last Name is Saleem SSN is 23234345 Before Setting First Name is : Mohammad Before Setting First Name is : Mohd. Method Overriding The child class Employee inherits all the methods from the parent class Person. But if you would like to override those methods in your child class then you can do it by giving your own implementation. You can add your additional functions in child class or you can add or modify the functionality of an existing methods in its parent class. It can be done as follows: modify Employee.pm file. #!/usr/bin/perl package Employee; use Person; use strict; our @ISA = qw(Person); # inherits from Person # Override constructor sub new { my ($class) = @_; # Call the constructor of the parent class, Person. my $self = $class->SUPER::new( $_[1], $_[2], $_[3] ); # Add few more attributes $self->{_id} = undef; $self->{_title} = undef; bless $self, $class; return $self; } # Override helper function sub getFirstName { my( $self ) = @_; # This is child class function. print "This is child class helper function\n"; return $self->{_firstName}; } # Add more methods sub setLastName{ my ( $self, $lastName ) = @_; $self->{_lastName} = $lastName if defined($lastName); return $self->{_lastName}; } sub getLastName { my( $self ) = @_; return $self->{_lastName}; } 1; Now let's again try to use Employee object in our main.pl file and execute it. #!/usr/bin/perl use Employee; $object = new Employee( "Mohammad", "Saleem", 23234345); # Get first name which is set using constructor. $firstName = $object->getFirstName(); print "Before Setting First Name is : $firstName\n"; # Now Set first name using helper function. $object->setFirstName( "Mohd." ); # Now get first name set by helper function. $firstName = $object->getFirstName(); print "After Setting First Name is : $firstName\n"; When we execute above program, it produces the following result − First Name is Mohammad Last Name is Saleem SSN is 23234345 This is child class helper function Before Setting First Name is : Mohammad This is child class helper function After Setting First Name is : Mohd. Default Autoloading Perl offers a feature which you would not find in any other programming languages: a default subroutine. Which means, if you define a function called AUTOLOAD(), then any calls to undefined subroutines will call AUTOLOAD() function automatically. The name of the missing subroutine is accessible within this subroutine as $AUTOLOAD. Default autoloading functionality is very useful for error handling. Here is an example to implement AUTOLOAD, you can implement this function in your own way. sub AUTOLOAD { my $self = shift; my $type = ref ($self) || croak "$self is not an object"; my $field = $AUTOLOAD; $field =~ s/.*://; unless (exists $self->{$field}) { croak "$field does not exist in object/class $type"; } if (@_) { return $self->($name) = shift; } else { return $self->($name); } } Destructors and Garbage Collection If you have programmed using object oriented programming before, then you will be aware of the need to create a destructor to free the memory allocated to the object when you have finished using it. Perl does this automatically for you as soon as the object goes out of scope. In case you want to implement your destructor, which should take care of closing files or doing some extra processing then you need to define a special method called DESTROY. This method will be called on the object just before Perl frees the memory allocated to it. In all other respects, the DESTROY method is just like any other method, and you can implement whatever logic you want inside this method. A destructor method is simply a member function (subroutine) named DESTROY, which will be called automatically in following cases − • When the object reference's variable goes out of scope. • When the object reference's variable is undef-ed. • When the script terminates • When the perl interpreter terminates For Example, you can simply put the following method DESTROY in your class − package MyClass; ... sub DESTROY { print "MyClass::DESTROY called\n"; } Object Oriented Perl Example Here is another nice example, which will help you to understand Object Oriented Concepts of Perl. Put this source code into any perl file and execute it. #!/usr/bin/perl # Following is the implementation of simple Class. package MyClass; sub new { print "MyClass::new called\n"; my $type = shift; # The package/type name my $self = {}; # Reference to empty hash return bless $self, $type; } sub DESTROY { print "MyClass::DESTROY called\n"; } sub MyMethod { print "MyClass::MyMethod called!\n"; } # Following is the implemnetation of Inheritance. package MySubClass; @ISA = qw( MyClass ); sub new { print "MySubClass::new called\n"; my $type = shift; # The package/type name my $self = MyClass->new; # Reference to empty hash return bless $self, $type; } sub DESTROY { print "MySubClass::DESTROY called\n"; } sub MyMethod { my $self = shift; $self->SUPER::MyMethod(); print " MySubClass::MyMethod called!\n"; } # Here is the main program using above classes. package main; print "Invoke MyClass method\n"; $myObject = MyClass->new(); $myObject->MyMethod(); print "Invoke MySubClass method\n"; $myObject2 = MySubClass->new(); $myObject2->MyMethod(); print "Create a scoped object\n"; { my $myObject2 = MyClass->new(); } # Destructor is called automatically here print "Create and undef an object\n"; $myObject3 = MyClass->new(); undef $myObject3; print "Fall off the end of the script...\n"; # Remaining destructors are called automatically here When we execute above program, it produces the following result − Invoke MyClass method MyClass::new called MyClass::MyMethod called! Invoke MySubClass method MySubClass::new called MyClass::new called MyClass::MyMethod called! MySubClass::MyMethod called! Create a scoped object MyClass::new called MyClass::DESTROY called Create and undef an object MyClass::new called MyClass::DESTROY called Fall off the end of the script... MyClass::DESTROY called MySubClass::DESTROY called Perl - Database Access This chapter teaches you how to access a database inside your Perl script. Starting from Perl 5 has become very easy to write database applications using DBI module. DBI stands for Database Independent Interface for Perl, which means DBI provides an abstraction layer between the Perl code and the underlying database, allowing you to switch database implementations really easily. The DBI is a database access module for the Perl programming language. It provides a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used. Architecture of a DBI Application DBI is independent of any database available in backend. You can use DBI whether you are working with Oracle, MySQL or Informix, etc. This is clear from the following architure diagram. Perl Database Module DBI Architecture Here DBI is responsible of taking all SQL commands through the API, (i.e., Application Programming Interface) and to dispatch them to the appropriate driver for actual execution. And finally, DBI is responsible of taking results from the driver and giving back it to the calling scritp. Notation and Conventions Throughout this chapter following notations will be used and it is recommended that you should also follow the same convention. $dsn Database source name $dbh Database handle object $sth Statement handle object $h Any of the handle types above ($dbh, $sth, or $drh) $rc General Return Code (boolean: true=ok, false=error) $rv General Return Value (typically an integer) @ary List of values returned from the database. $rows Number of rows processed (if available, else -1) $fh A filehandle undef NULL values are represented by undefined values in Perl \%attr Reference to a hash of attribute values passed to methods Database Connection Assuming we are going to work with MySQL database. Before connecting to a database make sure of the followings. You can take help of our MySQL tutorial in case you are not aware about how to create database and tables in MySQL database. • You have created a database with a name TESTDB. • You have created a table with a name TEST_TABLE in TESTDB. • This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME. • User ID "testuser" and password "test123" are set to access TESTDB. • Perl Module DBI is installed properly on your machine. • You have gone through MySQL tutorial to understand MySQL Basics. Following is the example of connecting with MySQL database "TESTDB" − #!/usr/bin/perl use DBI use strict; my $driver = "mysql"; my $database = "TESTDB"; my $dsn = "DBI:$driver:database=$database"; my $userid = "testuser"; my $password = "test123"; my $dbh = DBI->connect($dsn, $userid, $password ) or die $DBI::errstr; If a connection is established with the datasource then a Database Handle is returned and saved into $dbh for further use otherwise $dbh is set to undef value and $DBI::errstr returns an error string. INSERT Operation INSERT operation is required when you want to create some records into a table. Here we are using table TEST_TABLE to create our records. So once our database connection is established, we are ready to create records into TEST_TABLE. Following is the procedure to create single record into TEST_TABLE. You can create as many as records you like using the same concept. Record creation takes the following steps − • Preparing SQL statement with INSERT statement. This will be done using prepare() API. • Executing SQL query to select all the results from the database. This will be done using execute() API. • Releasing Stattement handle. This will be done using finish() API. • If everything goes fine then commit this operation otherwise you can rollback complete transaction. Commit and Rollback are explained in next sections. my $sth = $dbh->prepare("INSERT INTO TEST_TABLE (FIRST_NAME, LAST_NAME, SEX, AGE, INCOME ) values ('john', 'poul', 'M', 30, 13000)"); $sth->execute() or die $DBI::errstr; $sth->finish(); $dbh->commit or die $DBI::errstr; Using Bind Values There may be a case when values to be entered is not given in advance. So you can use bind variables which will take the required values at run time. Perl DBI modules make use of a question mark in place of actual value and then actual values are passed through execute() API at the run time. Following is the example − my $first_name = "john"; my $last_name = "poul"; my $sex = "M"; my $income = 13000; my $age = 30; my $sth = $dbh->prepare("INSERT INTO TEST_TABLE (FIRST_NAME, LAST_NAME, SEX, AGE, INCOME ) values (?,?,?,?)"); $sth->execute($first_name,$last_name,$sex, $age, $income) or die $DBI::errstr; $sth->finish(); $dbh->commit or die $DBI::errstr; READ Operation READ Operation on any databasse means to fetch some useful information from the database, i.e., one or more records from one or more tables. So once our database connection is established, we are ready to make a query into this database. Following is the procedure to query all the records having AGE greater than 20. This will take four steps − • Preparing SQL SELECT query based on required conditions. This will be done using prepare() API. • Executing SQL query to select all the results from the database. This will be done using execute() API. • Fetching all the results one by one and printing those results.This will be done using fetchrow_array() API. • Releasing Stattement handle. This will be done using finish() API. my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME FROM TEST_TABLE WHERE AGE > 20"); $sth->execute() or die $DBI::errstr; print "Number of rows found :" + $sth->rows; while (my @row = $sth->fetchrow_array()) { my ($first_name, $last_name ) = @row; print "First Name = $first_name, Last Name = $last_name\n"; } $sth->finish(); Using Bind Values There may be a case when condition is not given in advance. So you can use bind variables, which will take the required values at run time. Perl DBI modules makes use of a question mark in place of actual value and then the actual values are passed through execute() API at the run time. Following is the example − $age = 20; my $sth = $dbh->prepare("SELECT FIRST_NAME, LAST_NAME FROM TEST_TABLE WHERE AGE > ?"); $sth->execute( $age ) or die $DBI::errstr; print "Number of rows found :" + $sth->rows; while (my @row = $sth->fetchrow_array()) { my ($first_name, $last_name ) = @row; print "First Name = $first_name, Last Name = $last_name\n"; } $sth->finish(); UPDATE Operation UPDATE Operation on any database means to update one or more records already available in the database tables. Following is the procedure to update all the records having SEX as 'M'. Here we will increase AGE of all the males by one year. This will take three steps − • Preparing SQL query based on required conditions. This will be done using prepare() API. • Executing SQL query to select all the results from the database. This will be done using execute() API. • Releasing Stattement handle. This will be done using finish() API. • If everything goes fine then commit this operation otherwise you can rollback complete transaction. See next section for commit and rollback APIs. my $sth = $dbh->prepare("UPDATE TEST_TABLE SET AGE = AGE + 1 WHERE SEX = 'M'"); $sth->execute() or die $DBI::errstr; print "Number of rows updated :" + $sth->rows; $sth->finish(); $dbh->commit or die $DBI::errstr; Using Bind Values There may be a case when condition is not given in advance. So you can use bind variables, which will take required values at run time. Perl DBI modules make use of a question mark in place of actual value and then the actual values are passed through execute() API at the run time. Following is the example − $sex = 'M'; my $sth = $dbh->prepare("UPDATE TEST_TABLE SET AGE = AGE + 1 WHERE SEX = ?"); $sth->execute('$sex') or die $DBI::errstr; print "Number of rows updated :" + $sth->rows; $sth->finish(); $dbh->commit or die $DBI::errstr; In some case you would like to set a value, which is not given in advance so you can use binding value as follows. In this example income of all males will be set to 10000. $sex = 'M'; $income = 10000; my $sth = $dbh->prepare("UPDATE TEST_TABLE SET INCOME = ? WHERE SEX = ?"); $sth->execute( $income, '$sex') or die $DBI::errstr; print "Number of rows updated :" + $sth->rows; $sth->finish(); DELETE Operation DELETE operation is required when you want to delete some records from your database. Following is the procedure to delete all the records from TEST_TABLE where AGE is equal to 30. This operation will take the following steps. • Preparing SQL query based on required conditions. This will be done using prepare() API. • Executing SQL query to delete required records from the database. This will be done using execute() API. • Releasing Stattement handle. This will be done using finish() API. • If everything goes fine then commit this operation otherwise you can rollback complete transaction. $age = 30; my $sth = $dbh->prepare("DELETE FROM TEST_TABLE WHERE AGE = ?"); $sth->execute( $age ) or die $DBI::errstr; print "Number of rows deleted :" + $sth->rows; $sth->finish(); $dbh->commit or die $DBI::errstr; Using do Statement If you're doing an UPDATE, INSERT, or DELETE there is no data that comes back from the database, so there is a short cut to perform this operation. You can use do statement to execute any of the command as follows. $dbh->do('DELETE FROM TEST_TABLE WHERE age =30'); do returns a true value if it succeeded, and a false value if it failed. Actually, if it succeeds it returns the number of affected rows. In the example it would return the number of rows that were actually deleted. COMMIT Operation Commit is the operation which gives a green signal to database to finalize the changes and after this operation no change can be reverted to its orignal position. Here is a simple example to call commit API. $dbh->commit or die $dbh->errstr; ROLLBACK Operation If you are not satisfied with all the changes or you encounter an error in between of any operation , you can revert those changes to use rollback API. Here is a simple example to call rollback API. $dbh->rollback or die $dbh->errstr; Begin Transaction Many databases support transactions. This means that you can make a whole bunch of queries which would modify the databases, but none of the changes are actually made. Then at the end, you issue the special SQL query COMMIT, and all the changes are made simultaneously. Alternatively, you can issue the query ROLLBACK, in which case all the changes are thrown away and database remains unchanged. Perl DBI module provided begin_work API, which enables transactions (by turning AutoCommit off) until the next call to commit or rollback. After the next commit or rollback, AutoCommit will automatically be turned on again. $rc = $dbh->begin_work or die $dbh->errstr; AutoCommit Option If your transactions are simple, you can save yourself the trouble of having to issue a lot of commits. When you make the connect call, you can specify an AutoCommit option which will perform an automatic commit operation after every successful query. Here's what it looks like − my $dbh = DBI->connect($dsn, $userid, $password, {AutoCommit => 1}) or die $DBI::errstr; Here AutoCommit can take value 1 or 0, where 1 means AutoCommit is on and 0 means AutoCommit is off. Automatic Error Handling When you make the connect call, you can specify a RaiseErrors option that handles errors for you automatically. When an error occurs, DBI will abort your program instead of returning a failure code. If all you want is to abort the program on an error, this can be convenient. Here's what it looks like − my $dbh = DBI->connect($dsn, $userid, $password, {RaiseError => 1}) or die $DBI::errstr; Here RaiseError can take value 1 or 0. Disconnecting Database To disconnect Database connection, use disconnect API as follows − $rc = $dbh->disconnect or warn $dbh->errstr; The transaction behaviour of the disconnect method is, sadly, undefined. Some database systems (such as Oracle and Ingres) will automatically commit any outstanding changes, but others (such as Informix) will rollback any outstanding changes. Applications not using AutoCommit should explicitly call commit or rollback before calling disconnect. Using NULL Values Undefined values, or undef, are used to indicate NULL values. You can insert and update columns with a NULL value as you would a non-NULL value. These examples insert and update the column age with a NULL value − $sth = $dbh->prepare(qq { INSERT INTO TEST_TABLE (FIRST_NAME, AGE) VALUES (?, ?) }); $sth->execute("Joe", undef); Here qq{} is used to return a quoted string to prepare API. However, care must be taken when trying to use NULL values in a WHERE clause. Consider − SELECT FIRST_NAME FROM TEST_TABLE WHERE age = ? Binding an undef (NULL) to the placeholder will not select rows, which have a NULL age! At least for database engines that conform to the SQL standard. Refer to the SQL manual for your database engine or any SQL book for the reasons for this. To explicitly select NULLs you have to say "WHERE age IS NULL". A common issue is to have a code fragment handle a value that could be either defined or undef (non-NULL or NULL) at runtime. A simple technique is to prepare the appropriate statement as needed, and substitute the placeholder for non-NULL cases − $sql_clause = defined $age? "age = ?" : "age IS NULL"; $sth = $dbh->prepare(qq { SELECT FIRST_NAME FROM TEST_TABLE WHERE $sql_clause }); $sth->execute(defined $age ? $age : ()); Some Other DBI Functions available_drivers @ary = DBI->available_drivers; @ary = DBI->available_drivers($quiet); Returns a list of all available drivers by searching for DBD::* modules through the directories in @INC. By default, a warning is given if some drivers are hidden by others of the same name in earlier directories. Passing a true value for $quiet will inhibit the warning. installed_drivers %drivers = DBI->installed_drivers(); Returns a list of driver name and driver handle pairs for all drivers 'installed' (loaded) into the current process. The driver name does not include the 'DBD::' prefix. data_sources @ary = DBI->data_sources($driver); Returns a list of data sources (databases) available via the named driver. If $driver is empty or undef, then the value of the DBI_DRIVER environment variable is used. quote $sql = $dbh->quote($value); $sql = $dbh->quote($value, $data_type); Quote a string literal for use as a literal value in an SQL statement, by escaping any special characters (such as quotation marks) contained within the string and adding the required type of outer quotation marks. $sql = sprintf "SELECT foo FROM bar WHERE baz = %s", $dbh->quote("Don't"); For most database types, quote would return 'Don''t' (including the outer quotation marks). It is valid for the quote() method to return an SQL expression that evaluates to the desired string. For example − $quoted = $dbh->quote("one\ntwo\0three") may produce results which will be equivalent to CONCAT('one', CHAR(12), 'two', CHAR(0), 'three') Methods Common to All Handles err $rv = $h->err; or $rv = $DBI::err or $rv = $h->err Returns the native database engine error code from the last driver method called. The code is typically an integer but you should not assume that. This is equivalent to $DBI::err or $h->err. errstr $str = $h->errstr; or $str = $DBI::errstr or $str = $h->errstr Returns the native database engine error message from the last DBI method called. This has the same lifespan issues as the "err" method described above. This is equivalent to $DBI::errstr or $h->errstr. rows $rv = $h->rows; or $rv = $DBI::rows This returns the number of rows effected by previous SQL statement and equivalent to $DBI::rows. trace $h->trace($trace_settings); DBI sports an extremely useful ability to generate runtime tracing information of what it's doing, which can be a huge time-saver when trying to track down strange problems in your DBI programs. You can use different values to set trace level. These values varies from 0 to 4. The value 0 means disable trace and 4 means generate complete trace. Interpolated Statements are Prohibited It is highly recommended not to use interpolated statements as follows − while ($first_name = <>) { my $sth = $dbh->prepare("SELECT * FROM TEST_TABLE WHERE FIRST_NAME = '$first_name'"); $sth->execute(); # and so on ... } Thus don't use interpolated statement instead use bind value to prepare dynamic SQL statement. Perl - CGI Programming What is CGI ? • A Common Gateway Interface, or CGI, is a set of standards that defines how information is exchanged between the web server and a custom script. • The CGI specs are currently maintained by the NCSA and NCSA defines CGI is as follows − • The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers. • The current version is CGI/1.1 and CGI/1.2 is under progress. Web Browsing To understand the concept of CGI, lets see what happens when we click a hyper link available on a web page to browse a particular web page or URL. • Your browser contacts web server using HTTP protocol and demands for the URL, i.e., web page filename. • Web Server will check the URL and will look for the filename requested. If web server finds that file then it sends the file back to the browser without any further execution otherwise sends an error message indicating that you have requested a wrong file. • Web browser takes response from web server and displays either the received file content or an error message in case file is not found. However, it is possible to set up HTTP server in such a way so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs as a result, that is sent back for your browser to display. This can be done by using a special functionality available in the web server and it is called Common Gateway Interface or CGI and such programs which are executed by the server to produce final result, are called CGI scripts. These CGI programs can be a PERL Script, Shell Script, C or C++ program, etc. CGI Architecture Diagram CGI Architecture Web Server Support and Configuration Before you proceed with CGI Programming, make sure that your Web Server supports CGI functionality and it is configured to handle CGI programs. All the CGI programs to be executed by the web server are kept in a pre-configured directory. This directory is called CGI directory and by convention it is named as /cgi-bin. By convention Perl CGI files will have extention as .cgi. First CGI Program Here is a simple link which is linked to a CGI script called hello.cgi. This file has been kept in /cgi-bin/ directory and it has the following content. Before running your CGI program, make sure you have change mode of file using chmod 755 hello.cgi UNIX command. #!/usr/bin/perl print "Content-type:text/html\r\n\r\n"; print '<html>'; print '<head>'; print '<title>Hello Word - First CGI Program</title>'; print '</head>'; print '<body>'; print '<h2>Hello Word! This is my first CGI program</h2>'; print '</body>'; print '</html>'; 1; Now if you click hello.cgi link then request goes to web server who search for hello.cgi in /cgi-bin directory, execute it and whatever result got generated, web server sends that result back to the web browser, which is as follows − Hello Word! This is my first CGI program This hello.cgi script is a simple Perl script which is writing its output on STDOUT file, i.e., screen. There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n. This line is sent back to the browser and specifies the content type to be displayed on the browser screen. Now you must have undertood basic concept of CGI and you can write many complicated CGI programs using Perl. This script can interact with any other exertnal system also to exchange information such as a database, web services, or any other complex interfaces. Understanding HTTP Header The very first line Content-type:text/html\r\n\r\n is a part of HTTP header, which is sent to the browser so that browser can understand the incoming content from server side. All the HTTP header will be in the following form − HTTP Field Name: Field Content For Example − Content-type:text/html\r\n\r\n There are few other important HTTP headers, which you will use frequently in your CGI Programming. Sr.No. Header & Description 1 Content-type: String A MIME string defining the format of the content being returned. Example is Content-type:text/html 2 Expires: Date String The date when the information becomes invalid. This should be used by the browser to decide when a page needs to be refreshed. A valid date string should be in the format 01 Jan 1998 12:00:00 GMT. 3 Location: URL String The URL that should be returned instead of the URL requested. You can use this filed to redirect a request to any other location. 4 Last-modified: String The date of last modification of the file. 5 Content-length: String The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file. 6 Set-Cookie: String Set the cookie passed through the string CGI Environment Variables All the CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program. Sr.No. Variables Names & Description 1 CONTENT_TYPE The data type of the content. Used when the client is sending attached content to the server. For example file upload, etc. 2 CONTENT_LENGTH The length of the query information. It's available only for POST requests 3 HTTP_COOKIE Returns the set cookies in the form of key & value pair. 4 HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser. 5 PATH_INFO The path for the CGI script. 6 QUERY_STRING The URL-encoded information that is sent with GET method request. 7 REMOTE_ADDR The IP address of the remote host making the request. This can be useful for logging or for authentication purpose. 8 REMOTE_HOST The fully qualified name of the host making the request. If this information is not available then REMOTE_ADDR can be used to get IR address. 9 REQUEST_METHOD The method used to make the request. The most common methods are GET and POST. 10 SCRIPT_FILENAME The full path to the CGI script. 11 SCRIPT_NAME The name of the CGI script. 12 SERVER_NAME The server's hostname or IP Address. 13 SERVER_SOFTWARE The name and version of the software the server is running. Here is a small CGI program to list down all the CGI variables supported by your Web server. Click this link to see the result Get Environment #!/usr/bin/perl print "Content-type: text/html\n\n"; print "<font size=+1>Environment</font>\n"; foreach (sort keys %ENV) { print "<b>$_</b>: $ENV{$_}<br>\n"; } 1; Raise a "File Download" Dialog Box? Sometime it is desired that you want to give option where a user will click a link and it will pop up a "File Download" dialogue box to the user instead of displaying actual content. This is very easy and will be achived through HTTP header. This HTTP header will be different from the header mentioned in previous section. For example, if you want to make a FileName file downloadable from a given link then it's syntax will be as follows − #!/usr/bin/perl # HTTP Header print "Content-Type:application/octet-stream; name = \"FileName\"\r\n"; print "Content-Disposition: attachment; filename = \"FileName\"\r\n\n"; # Actual File Content will go hear. open( FILE, "<FileName" ); while(read(FILE, $buffer, 100) ) { print("$buffer"); } GET and POST Methods You must have come across many situations when you need to pass some information from your browser to the web server and ultimately to your CGI Program handling your requests. Most frequently browser uses two methods to pass this information to the web server. These methods are GET Method and POST Method. Let's check them one by one. Passing Information using GET Method The GET method sends the encoded user information appended to the page URL itself. The page and the encoded information are separated by the ? character as follows − http://www.test.com/cgi-bin/hello.cgi?key1=value1&key2=value2 The GET method is the defualt method to pass information from a browser to the web server and it produces a long string that appears in your browser's Location:box. You should never use GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be passed in a request string. This information is passed using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable which you can parse and use in your CGI program. You can pass information by simply concatenating key and value pairs alongwith any URL or you can use HTML <FORM> tags to pass information using GET method. Simple URL Example: Get Method Here is a simple URL which will pass two values to hello_get.cgi program using GET method. http://www.tutorialspoint.com/cgi-bin/hello_get.cgi?first_name=ZARA&last_name=ALI Below is hello_get.cgi script to handle input given by web browser. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "GET") { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $first_name = $FORM{first_name}; $last_name = $FORM{last_name}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Hello - Second CGI Program</title>"; print "</head>"; print "<body>"; print "<h2>Hello $first_name $last_name - Second CGI Program</h2>"; print "</body>"; print "</html>"; 1; Simple FORM Example: GET Method Here is a simple example, which passes two values using HTML FORM and submit button. We are going to use the same CGI script hello_get.cgi to handle this input. <FORM action = "/cgi-bin/hello_get.cgi" method = "GET"> First Name: <input type = "text" name = "first_name"> <br> Last Name: <input type = "text" name = "last_name"> <input type = "submit" value = "Submit"> </FORM> Here is the actual output of the above form coding. Now you can enter First and Last Name and then click submit button to see the result. First Name: Last Name: Passing Information using POST Method A more reliable method of passing information to a CGI program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL, it sends it as a separate message as a part of HTTP header. Web server provides this message to the CGI script in the form of the standard input. Below is the modified hello_post.cgi script to handle input given by the web browser. This script will handle GET as well as POST method. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); } else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $first_name = $FORM{first_name}; $last_name = $FORM{last_name}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Hello - Second CGI Program</title>"; print "</head>"; print "<body>"; print "<h2>Hello $first_name $last_name - Second CGI Program</h2>"; print "</body>"; print "</html>"; 1; Let us take again same examle as above, which passes two values using HTML FORM and submit button. We are going to use CGI script hello_post.cgi to handle this input. <FORM action = "/cgi-bin/hello_post.cgi" method = "POST"> First Name: <input type = "text" name = "first_name"> <br> Last Name: <input type = "text" name = "last_name"> <input type = "submit" value = "Submit"> </FORM> Here is the actual output of the above form coding, You enter First and Last Name and then click submit button to see the result. First Name: Last Name: Passing Checkbox Data to CGI Program Checkboxes are used when more than one option is required to be selected. Here is an example HTML code for a form with two checkboxes. <form action = "/cgi-bin/checkbox.cgi" method = "POST" target = "_blank"> <input type = "checkbox" name = "maths" value = "on"> Maths <input type = "checkbox" name = "physics" value = "on"> Physics <input type = "submit" value = "Select Subject"> </form> The result of this code is the following form − Maths Physics Below is checkbox.cgi script to handle input given by web browser for radio button. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); } else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } if( $FORM{maths} ) { $maths_flag ="ON"; } else { $maths_flag ="OFF"; } if( $FORM{physics} ) { $physics_flag ="ON"; } else { $physics_flag ="OFF"; } print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Checkbox - Third CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> CheckBox Maths is : $maths_flag</h2>"; print "<h2> CheckBox Physics is : $physics_flag</h2>"; print "</body>"; print "</html>"; 1; Passing Radio Button Data to CGI Program Radio Buttons are used when only one option is required to be selected. Here is an example HTML code for a form with two radio button − <form action = "/cgi-bin/radiobutton.cgi" method = "POST" target = "_blank"> <input type = "radio" name = "subject" value = "maths"> Maths <input type = "radio" name = "subject" value = "physics"> Physics <input type = "submit" value = "Select Subject"> </form> The result of this code is the following form − Maths Physics Below is radiobutton.cgi script to handle input given by the web browser for radio button. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); } else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $subject = $FORM{subject}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Radio - Fourth CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> Selected Subject is $subject</h2>"; print "</body>"; print "</html>"; 1; Passing Text Area Data to CGI Program A textarea element is used when multiline text has to be passed to the CGI Program. Here is an example HTML code for a form with a TEXTAREA box − <form action = "/cgi-bin/textarea.cgi" method = "POST" target = "_blank"> <textarea name = "textcontent" cols = 40 rows = 4> Type your text here... </textarea> <input type = "submit" value = "Submit"> </form> The result of this code is the following form − Below is the textarea.cgi script to handle input given by the web browser. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); } else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $text_content = $FORM{textcontent}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Text Area - Fifth CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> Entered Text Content is $text_content</h2>"; print "</body>"; print "</html>"; 1; Passing Drop Down Box Data to CGI Program A drop down box is used when we have many options available but only one or two will be selected. Here is example HTML code for a form with one drop down box <form action = "/cgi-bin/dropdown.cgi" method = "POST" target = "_blank"> <select name = "dropdown"> <option value = "Maths" selected>Maths</option> <option value = "Physics">Physics</option> </select> <input type = "submit" value = "Submit"> </form> The result of this code is the following form − Below is the dropdown.cgi script to handle input given by web browser. #!/usr/bin/perl local ($buffer, @pairs, $pair, $name, $value, %FORM); # Read in text $ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/; if ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}); } else { $buffer = $ENV{'QUERY_STRING'}; } # Split information into name/value pairs @pairs = split(/&/, $buffer); foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%(..)/pack("C", hex($1))/eg; $FORM{$name} = $value; } $subject = $FORM{dropdown}; print "Content-type:text/html\r\n\r\n"; print "<html>"; print "<head>"; print "<title>Dropdown Box - Sixth CGI Program</title>"; print "</head>"; print "<body>"; print "<h2> Selected Subject is $subject</h2>"; print "</body>"; print "</html>"; 1; Using Cookies in CGI HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain session information among different pages. For example one user registration ends after transactions which spans through many pages. But how to maintain user's session information across all the web pages? In many situations, using cookies is the most efficient method of remembering and tracking preferences, purchases, commissions, and other information required for better visitor experience or site statistics. How It Works Your server sends some data to the visitor's browser in the form of a cookie. The browser may accept the cookie. If it does, it is stored as a plain text record on the visitor's hard drive. Now, when the visitor arrives at another page on your site, the cookie is available for retrieval. Once retrieved, your server knows/remembers what was stored. Cookies are a plain text data record of 5 variable-length fields − • Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor quits the browser. • Domain − The domain name of your site. • Path − The path to the directory or web page that set the cookie. This may be blank if you want to retrieve the cookie from any directory or page. • Secure − If this field contains the word "secure" then the cookie may only be retrieved with a secure server. If this field is blank, no such restriction exists. • Name = Value − Cookies are set and retrviewed in the form of key and value pairs. Setting up Cookies It is very easy to send cookies to browser. These cookies will be sent along with the HTTP Header. Assuming you want to set UserID and Password as cookies. So it will be done as follows − #!/usr/bin/perl print "Set-Cookie:UserID = XYZ;\n"; print "Set-Cookie:Password = XYZ123;\n"; print "Set-Cookie:Expires = Tuesday, 31-Dec-2007 23:12:40 GMT";\n"; print "Set-Cookie:Domain = www.tutorialspoint.com;\n"; print "Set-Cookie:Path = /perl;\n"; print "Content-type:text/html\r\n\r\n"; ...........Rest of the HTML Content goes here.... Here we used Set-Cookie HTTP header to set cookies. It is optional to set cookies attributes like Expires, Domain, and Path. It is important to note that cookies are set before sending magic line "Content-type:text/html\r\n\r\n. Retrieving Cookies It is very easy to retrieve all the set cookies. Cookies are stored in CGI environment variable HTTP_COOKIE and they will have following form. key1 = value1;key2 = value2;key3 = value3.... Here is an example of how to retrieve cookies. #!/usr/bin/perl $rcvd_cookies = $ENV{'HTTP_COOKIE'}; @cookies = split /;/, $rcvd_cookies; foreach $cookie ( @cookies ) { ($key, $val) = split(/=/, $cookie); # splits on the first =. $key =~ s/^\s+//; $val =~ s/^\s+//; $key =~ s/\s+$//; $val =~ s/\s+$//; if( $key eq "UserID" ) { $user_id = $val; } elsif($key eq "Password") { $password = $val; } } print "User ID = $user_id\n"; print "Password = $password\n"; This will produce the following result, provided above cookies have been set before calling retrieval cookies script. User ID = XYZ Password = XYZ123 CGI Modules and Libraries You will find many built-in modules over the internet which provides you direct functions to use in your CGI program. Following are the important once. Perl - Packages and Modules What are Packages? The package statement switches the current naming context to a specified namespace (symbol table). Thus − • A package is a collection of code which lives in its own namespace. • A namespace is a named collection of unique variable names (also called a symbol table). • Namespaces prevent variable name collisions between packages. • Packages enable the construction of modules which, when used, won't clobber variables and functions outside of the modules's own namespace. • The package stays in effect until either another package statement is invoked, or until the end of the current block or file. • You can explicitly refer to variables within a package using the :: package qualifier. Following is an example having main and Foo packages in a file. Here special variable __PACKAGE__ has been used to print the package name. #!/usr/bin/perl # This is main package $i = 1; print "Package name : " , __PACKAGE__ , " $i\n"; package Foo; # This is Foo package $i = 10; print "Package name : " , __PACKAGE__ , " $i\n"; package main; # This is again main package $i = 100; print "Package name : " , __PACKAGE__ , " $i\n"; print "Package name : " , __PACKAGE__ , " $Foo::i\n"; 1; When above code is executed, it produces the following result − Package name : main 1 Package name : Foo 10 Package name : main 100 Package name : main 10 BEGIN and END Blocks You may define any number of code blocks named BEGIN and END, which act as constructors and destructors respectively. BEGIN { ... } END { ... } BEGIN { ... } END { ... } • Every BEGIN block is executed after the perl script is loaded and compiled but before any other statement is executed. • Every END block is executed just before the perl interpreter exits. • The BEGIN and END blocks are particularly useful when creating Perl modules. Following example shows its usage − #!/usr/bin/perl package Foo; print "Begin and Block Demo\n"; BEGIN { print "This is BEGIN Block\n" } END { print "This is END Block\n" } 1; When above code is executed, it produces the following result − This is BEGIN Block Begin and Block Demo This is END Block What are Perl Modules? A Perl module is a reusable package defined in a library file whose name is the same as the name of the package with a .pm as extension. A Perl module file called Foo.pm might contain statements like this. #!/usr/bin/perl package Foo; sub bar { print "Hello $_[0]\n" } sub blat { print "World $_[0]\n" } 1; Few important points about Perl modules • The functions require and use will load a module. • Both use the list of search paths in @INC to find the module. • Both functions require and use call the eval function to process the code. • The 1; at the bottom causes eval to evaluate to TRUE (and thus not fail). The Require Function A module can be loaded by calling the require function as follows − #!/usr/bin/perl require Foo; Foo::bar( "a" ); Foo::blat( "b" ); You must have noticed that the subroutine names must be fully qualified to call them. It would be nice to enable the subroutine bar and blat to be imported into our own namespace so we wouldn't have to use the Foo:: qualifier. The Use Function A module can be loaded by calling the use function. #!/usr/bin/perl use Foo; bar( "a" ); blat( "b" ); Notice that we didn't have to fully qualify the package's function names. The use function will export a list of symbols from a module given a few added statements inside a module. require Exporter; @ISA = qw(Exporter); Then, provide a list of symbols (scalars, lists, hashes, subroutines, etc) by filling the list variable named @EXPORT: For Example − package Module; require Exporter; @ISA = qw(Exporter); @EXPORT = qw(bar blat); sub bar { print "Hello $_[0]\n" } sub blat { print "World $_[0]\n" } sub splat { print "Not $_[0]\n" } # Not exported! 1; Create the Perl Module Tree When you are ready to ship your Perl module, then there is standard way of creating a Perl Module Tree. This is done using h2xs utility. This utility comes along with Perl. Here is the syntax to use h2xs − $h2xs -AX -n ModuleName For example, if your module is available in Person.pm file, then simply issue the following command − $h2xs -AX -n Person This will produce the following result − Writing Person/lib/Person.pm Writing Person/Makefile.PL Writing Person/README Writing Person/t/Person.t Writing Person/Changes Writing Person/MANIFEST Here is the descritpion of these options − • -A omits the Autoloader code (best used by modules that define a large number of infrequently used subroutines). • -X omits XS elements (eXternal Subroutine, where eXternal means external to Perl, i.e., C). • -n specifies the name of the module. So above command creates the following structure inside Person directory. Actual result is shown above. • Changes • Makefile.PL • MANIFEST (contains the list of all files in the package) • README • t/ (test files) • lib/ ( Actual source code goes here So finally, you tar this directory structure into a file Person.tar.gz and you can ship it. You will have to update README file with the proper instructions. You can also provide some test examples files in t directory. Installing Perl Module Download a Perl module in the form tar.gz file. Use the following sequence to install any Perl Module Person.pm which has been downloaded in as Person.tar.gz file. tar xvfz Person.tar.gz cd Person perl Makefile.PL make make install The Perl interpreter has a list of directories in which it searches for modules (global array @INC). Perl - Process Management You can use Perl in various ways to create new processes as per your requirements. This tutorial will list down few important and most frequently used methods of creating and managing Perl processes. • You can use special variables $$ or $PROCESS_ID to get current process ID. • Every process created using any of the mentioned methods, maintains its own virtual environment with-in %ENV variable. • The exit() function always exits just the child process which executes this function and the main process as a whole will not exit unless all running child-processes have exited. • All open handles are dup()-ed in child-processes, so that closing any handles in one process does not affect the others. Backstick Operator This simplest way of executing any Unix command is by using backstick operator. You simply put your command inside the backstick operator, which will result in execution of the command and returns its result which can be stored as follows − #!/usr/bin/perl @files = `ls -l`; foreach $file (@files) { print $file; } 1; When the above code is executed, it lists down all the files and directories available in the current directory − drwxr-xr-x 3 root root 4096 Sep 14 06:46 9-14 drwxr-xr-x 4 root root 4096 Sep 13 07:54 android -rw-r--r-- 1 root root 574 Sep 17 15:16 index.htm drwxr-xr-x 3 544 401 4096 Jul 6 16:49 MIME-Lite-3.01 -rw-r--r-- 1 root root 71 Sep 17 15:16 test.pl drwx------ 2 root root 4096 Sep 17 15:11 vAtrJdy The system() Function You can also use system() function to execute any Unix command, whose output will go to the output of the perl script. By default, it is the screen, i.e., STDOUT, but you can redirect it to any file by using redirection operator > − #!/usr/bin/perl system( "ls -l") 1; When above code is executed, it lists down all the files and directories available in the current directory − drwxr-xr-x 3 root root 4096 Sep 14 06:46 9-14 drwxr-xr-x 4 root root 4096 Sep 13 07:54 android -rw-r--r-- 1 root root 574 Sep 17 15:16 index.htm drwxr-xr-x 3 544 401 4096 Jul 6 16:49 MIME-Lite-3.01 -rw-r--r-- 1 root root 71 Sep 17 15:16 test.pl drwx------ 2 root root 4096 Sep 17 15:11 vAtrJdy Be careful when your command contains shell environmental variables like $PATH or $HOME. Try following three scenarios − #!/usr/bin/perl $PATH = "I am Perl Variable"; system('echo $PATH'); # Treats $PATH as shell variable system("echo $PATH"); # Treats $PATH as Perl variable system("echo \$PATH"); # Escaping $ works. 1; When above code is executed, it produces the following result depending on what is set in shell variable $PATH. /usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin I am Perl Variable /usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin The fork() Function Perl provides a fork() function that corresponds to the Unix system call of the same name. On most Unix-like platforms where the fork() system call is available, Perl's fork() simply calls it. On some platforms such as Windows where the fork() system call is not available, Perl can be built to emulate fork() at the interpreter level. The fork() function is used to clone a current process. This call create a new process running the same program at the same point. It returns the child pid to the parent process, 0 to the child process, or undef if the fork is unsuccessful. You can use exec() function within a process to launch the requested executable, which will be executed in a separate process area and exec() will wait for it to complete before exiting with the same exit status as that process. #!/usr/bin/perl if(!defined($pid = fork())) { # fork returned undef, so unsuccessful die "Cannot fork a child: $!"; } elsif ($pid == 0) { print "Printed by child process\n"; exec("date") || die "can't exec date: $!"; } else { # fork returned 0 nor undef # so this branch is parent print "Printed by parent process\n"; $ret = waitpid($pid, 0); print "Completed process id: $ret\n"; } 1; When above code is executed, it produces the following result − Printed by parent process Printed by child process Tue Sep 17 15:41:08 CDT 2013 Completed process id: 17777 The wait() and waitpid() can be passed as a pseudo-process ID returned by fork(). These calls will properly wait for the termination of the pseudo-process and return its status. If you fork without ever waiting on your children using waitpid() function, you will accumulate zombies. On Unix systems, you can avoid this by setting $SIG{CHLD} to "IGNORE" as follows − #!/usr/bin/perl local $SIG{CHLD} = "IGNORE"; if(!defined($pid = fork())) { # fork returned undef, so unsuccessful die "Cannot fork a child: $!"; } elsif ($pid == 0) { print "Printed by child process\n"; exec("date") || die "can't exec date: $!"; } else { # fork returned 0 nor undef # so this branch is parent print "Printed by parent process\n"; $ret = waitpid($pid, 0); print "Completed process id: $ret\n"; } 1; When above code is executed, it produces the following result − Printed by parent process Printed by child process Tue Sep 17 15:44:07 CDT 2013 Completed process id: -1 The kill() Function Perl kill('KILL', (Process List)) function can be used to terminate a pseudo-process by passing it the ID returned by fork(). Note that using kill('KILL', (Process List)) on a pseudo-process() may typically cause memory leaks, because the thread that implements the pseudo-process does not get a chance to clean up its resources. You can use kill() function to send any other signal to target processes, for example following will send SIGINT to a process IDs 104 and 102 − #!/usr/bin/perl kill('INT', 104, 102); 1; Perl - Embedded Documentation You can embed Pod (Plain Old Text) documentation in your Perl modules and scripts. Following is the rule to use embedded documentation in your Perl Code − Start your documentation with an empty line, a =head1 command at the beginning, and end it with a =cut Perl will ignore the Pod text you entered in the code. Following is a simple example of using embedded documentation inside your Perl code − #!/usr/bin/perl print "Hello, World\n"; =head1 Hello, World Example This example demonstrate very basic syntax of Perl. =cut print "Hello, Universe\n"; When above code is executed, it produces the following result − Hello, World Hello, Universe If you're going to put your Pod at the end of the file, and you're using an __END__ or __DATA__ cut mark, make sure to put an empty line there before the first Pod command as follows, otherwise without an empty line before the =head1, many translators wouldn't have recognized the =head1 as starting a Pod block. #!/usr/bin/perl print "Hello, World\n"; while(<DATA>) { print $_; } __END__ =head1 Hello, World Example This example demonstrate very basic syntax of Perl. print "Hello, Universe\n"; When above code is executed, it produces the following result − Hello, World =head1 Hello, World Example This example demonstrate very basic syntax of Perl. print "Hello, Universe\n"; Let's take one more example for the same code without reading DATA part − #!/usr/bin/perl print "Hello, World\n"; __END__ =head1 Hello, World Example This example demonstrate very basic syntax of Perl. print "Hello, Universe\n"; When above code is executed, it produces the following result − Hello, World What is POD? Pod is a simple-to-use markup language used for writing documentation for Perl, Perl programs, and Perl modules. There are various translators available for converting Pod to various formats like plain text, HTML, man pages, and more. Pod markup consists of three basic kinds of paragraphs − • Ordinary Paragraph − You can use formatting codes in ordinary paragraphs, for bold, italic, code-style , hyperlinks, and more. • Verbatim Paragraph − Verbatim paragraphs are usually used for presenting a codeblock or other text which does not require any special parsing or formatting, and which shouldn't be wrapped. • Command Paragraph − A command paragraph is used for special treatment of whole chunks of text, usually as headings or parts of lists. All command paragraphs start with =, followed by an identifier, followed by arbitrary text that the command can use however it pleases. Currently recognized commands are − =pod =head1 Heading Text =head2 Heading Text =head3 Heading Text =head4 Heading Text =over indentlevel =item stuff =back =begin format =end format =for format text... =encoding type =cut POD Examples Consider the following POD − =head1 SYNOPSIS Copyright 2005 [TUTORIALSOPOINT]. =cut You can use pod2html utility available on Linux to convert above POD into HTML, so it will produce following result − Copyright 2005 [TUTORIALSOPOINT]. Next, consider the following example − =head2 An Example List =over 4 =item * This is a bulleted list. =item * Here's another item. =back =begin html <p> Here's some embedded HTML. In this block I can include images, apply <span style="color: green"> styles</span>, or do anything else I can do with HTML. pod parsers that aren't outputting HTML will completely ignore it. </p> =end html When you convert the above POD into HTML using pod2html, it will produce the following result − An Example List This is a bulleted list. Here's another item. Here's some embedded HTML. In this block I can include images, apply styles, or do anything else I can do with HTML. pod parsers that aren't outputting HTML will completely ignore it. Perl - Functions References Here is the list of all the important functions supported by standard Perl. • abs - absolute value function • accept - accept an incoming socket connect • alarm - schedule a SIGALRM • atan2 - arctangent of Y/X in the range -PI to PI • bind - binds an address to a socket • binmode - prepare binary files for I/O • bless - create an object • caller - get context of the current subroutine call • chdir - change your current working directory • chmod - changes the permissions on a list of files • chomp - remove a trailing record separator from a string • chop - remove the last character from a string • chown - change the owership on a list of files • chr - get character this number represents • chroot - make directory new root for path lookups • close - close file (or pipe or socket) handle • closedir - close directory handle • connect - connect to a remote socket • continue - optional trailing block in a while or foreach • cos - cosine function • crypt - one-way passwd-style encryption • dbmclose - breaks binding on a tied dbm file • dbmopen - create binding on a tied dbm file • defined - test whether a value, variable, or function is defined or not • delete - deletes a value from a hash • die - raise an exception or bail out • do - turn a BLOCK into a TERM • dump - create an immediate core dump • each - retrieve the next key/value pair from a hash • endgrent - be done using group file • endhostent - be done using hosts file • endnetent - be done using networks file • endprotoent - be done using protocols file • endpwent - be done using passwd file • endservent - be done using services file • eof - test a filehandle for its end • eval - catch exceptions or compile and run code • exec - abandon this program to run another • exists - test whether a hash key is present • exit - terminate this program • exp - raise I to a power • fcntl - file control system call • fileno - return file descriptor from filehandle • flock - lock an entire file with an advisory lock • fork - create a new process just like this one • format - declare a picture format with use by the write() function • formline - internal function used for formats • getc - get the next character from the filehandle • getgrent - get next group record • getgrgid - get group record given group user ID • getgrnam - get group record given group name • gethostbyaddr - get host record given its address • gethostbyname - get host record given name • gethostent - get next hosts record • getlogin - return who logged in at this tty • getnetbyaddr - get network record given its address • getnetbyname - get networks record given name • getnetent - get next networks record • getpeername - find the other end of a socket connection • getpgrp - get process group • getppid - get parent process ID • getpriority - get current nice value • getprotobyname - get protocol record given name • getprotobynumber - get protocol record numeric protocol • getprotoent - get next protocols record • getpwent - get next passwd record • getpwnam - get passwd record given user login name • getpwuid - get passwd record given user ID • getservbyname - get services record given its name • getservbyport - get services record given numeric port • getservent - get next services record • getsockname - retrieve the sockaddr for a given socket • getsockopt - get socket options on a given socket • glob - expand filenames using wildcards • gmtime - convert UNIX time into record or string using Greenwich time format. • goto - create spaghetti code • grep - locate elements in a list test true against a given criterion • hex - convert a string to a hexadecimal number • import - patch a module's namespace into your own • index - find a substring within a string • int - get the integer portion of a number • ioctl - system-dependent device control system call • join - join a list into a string using a separator • keys - retrieve list of indices from a hash • kill - send a signal to a process or process group • last - exit a block prematurely • lc - return lower-case version of a string • lcfirst - return a string with just the next letter in lower case • length - return the number of bytes in a string • link - create a hard link in the filesytem • listen - register your socket as a server • local - create a temporary value for a global variable (dynamic scoping) • localtime - convert UNIX time into record or string using local time • lock - get a thread lock on a variable, subroutine, or method • log - retrieve the natural logarithm for a number • lstat - stat a symbolic link • m - match a string with a regular expression pattern • map - apply a change to a list to get back a new list with the changes • mkdir - create a directory • msgctl - SysV IPC message control operations • msgget - get SysV IPC message queue • msgrcv - receive a SysV IPC message from a message queue • msgsnd - send a SysV IPC message to a message queue • my - declare and assign a local variable (lexical scoping) • next - iterate a block prematurely • no - unimport some module symbols or semantics at compile time • oct - convert a string to an octal number • open - open a file, pipe, or descriptor • opendir - open a directory • ord - find a character's numeric representation • our - declare and assign a package variable (lexical scoping) • pack - convert a list into a binary representation • package - declare a separate global namespace • pipe - open a pair of connected filehandles • pop - remove the last element from an array and return it • pos - find or set the offset for the last/next m//g search • print - output a list to a filehandle • printf - output a formatted list to a filehandle • prototype - get the prototype (if any) of a subroutine • push - append one or more elements to an array • q - singly quote a string • qq - doubly quote a string • qr - Compile pattern • quotemeta - quote regular expression magic characters • qw - quote a list of words • qx - backquote quote a string • rand - retrieve the next pseudorandom number • read - fixed-length buffered input from a filehandle • readdir - get a directory from a directory handle • readline - fetch a record from a file • readlink - determine where a symbolic link is pointing • readpipe - execute a system command and collect standard output • recv - receive a message over a Socket • redo - start this loop iteration over again • ref - find out the type of thing being referenced • rename - change a filename • require - load in external functions from a library at runtime • reset - clear all variables of a given name • return - get out of a function early • reverse - flip a string or a list • rewinddir - reset directory handle • rindex - right-to-left substring search • rmdir - remove a directory • s - replace a pattern with a string • scalar - force a scalar context • seek - reposition file pointer for random-access I/O • seekdir - reposition directory pointer • select - reset default output or do I/O multiplexing • semctl - SysV semaphore control operations • semget - get set of SysV semaphores • semop - SysV semaphore operations • send - send a message over a socket • setgrent - prepare group file for use • sethostent - prepare hosts file for use • setnetent - prepare networks file for use • setpgrp - set the process group of a process • setpriority - set a process's nice value • setprotoent - prepare protocols file for use • setpwent - prepare passwd file for use • setservent - prepare services file for use • setsockopt - set some socket options • shift - remove the first element of an array, and return it • shmctl - SysV shared memory operations • shmget - get SysV shared memory segment identifier • shmread - read SysV shared memory • shmwrite - write SysV shared memory • shutdown - close down just half of a socket connection • sin - return the sine of a number • sleep - block for some number of seconds • socket - create a socket • socketpair - create a pair of sockets • sort - sort a list of values • splice - add or remove elements anywhere in an array • split - split up a string using a regexp delimiter • sprintf - formatted print into a string • sqrt - square root function • srand - seed the random number generator • stat - get a file's status information • study - optimize input data for repeated searches • sub - declare a subroutine, possibly anonymously • substr - get or alter a portion of a stirng • symlink - create a symbolic link to a file • syscall - execute an arbitrary system call • sysopen - open a file, pipe, or descriptor • sysread - fixed-length unbuffered input from a filehandle • sysseek - position I/O pointer on handle used with sysread and syswrite • system - run a separate program • syswrite - fixed-length unbuffered output to a filehandle • tell - get current seekpointer on a filehandle • telldir - get current seekpointer on a directory handle • tie - bind a variable to an object class • tied - get a reference to the object underlying a tied variable • time - return number of seconds since 1970 • times - return elapsed time for self and child processes • tr - transliterate a string • truncate - shorten a file • uc - return upper-case version of a string • ucfirst - return a string with just the next letter in upper case • umask - set file creation mode mask • undef - remove a variable or function definition • unlink - remove one link to a file • unpack - convert binary structure into normal perl variables • unshift - prepend more elements to the beginning of a list • untie - break a tie binding to a variable • use - load in a module at compile time • utime - set a file's last access and modify times • values - return a list of the values in a hash • vec - test or set particular bits in a string • wait - wait for any child process to die • waitpid - wait for a particular child process to die • wantarray - get void vs scalar vs list context of current subroutine call • warn - print debugging info • write - print a picture record • -X - a file test (-r, -x, etc) • y - transliterate a string Advertisements
__label__pos
0.870523
Generic ECharts: Provide line of error & highlight failing code Hi, using K-AI to color the data it inserted code which triggered an error. Furthermore, the error shows no relation to a the line making nor is the line of code in any sort of way highlighted. Thus, making debugging unnecessarily difficult. I’d like to suggest to align the debugging features more closely to those in the Chrome developer console. Why Chrome? Because that console is, from my perspective, the most mature and convenient one. Best Mike
__label__pos
0.619107
Boost C++ Libraries ...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards This is the documentation for an old version of Boost. Click here to view this page for the latest version. libs/signals/test/signal_n_test.cpp // Boost.Signals library // Copyright Douglas Gregor 2001-2003. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // For more information, see http://www.boost.org #include <boost/test/minimal.hpp> #include <boost/signal.hpp> #include <functional> template<typename T> struct max_or_default { typedef T result_type; template<typename InputIterator> typename InputIterator::value_type operator()(InputIterator first, InputIterator last) const { if (first == last) return T(); T max = *first++; for (; first != last; ++first) max = (*first > max)? *first : max; return max; } }; struct make_int { make_int(int n, int cn) : N(n), CN(n) {} int operator()() { return N; } int operator()() const { return CN; } int N; int CN; }; template<int N> struct make_increasing_int { make_increasing_int() : n(N) {} int operator()() const { return n++; } mutable int n; }; int get_37() { return 37; } static void test_zero_args() { make_int i42(42, 41); make_int i2(2, 1); make_int i72(72, 71); make_int i63(63, 63); make_int i62(62, 61); { boost::signal0<int, max_or_default<int>, std::string> s0; boost::BOOST_SIGNALS_NAMESPACE::connection c2 = s0.connect(i2); boost::BOOST_SIGNALS_NAMESPACE::connection c72 = s0.connect("72", i72); boost::BOOST_SIGNALS_NAMESPACE::connection c62 = s0.connect("6x", i62); boost::BOOST_SIGNALS_NAMESPACE::connection c42 = s0.connect(i42); boost::BOOST_SIGNALS_NAMESPACE::connection c37 = s0.connect(&get_37); BOOST_TEST(s0() == 72); s0.disconnect("72"); BOOST_TEST(s0() == 62); c72.disconnect(); // Double-disconnect should be safe BOOST_TEST(s0() == 62); s0.disconnect("72"); // Triple-disconect should be safe BOOST_TEST(s0() == 62); // Also connect 63 in the same group as 62 s0.connect("6x", i63); BOOST_TEST(s0() == 63); // Disconnect all of the 60's s0.disconnect("6x"); BOOST_TEST(s0() == 42); c42.disconnect(); BOOST_TEST(s0() == 37); c37.disconnect(); BOOST_TEST(s0() == 2); c2.disconnect(); BOOST_TEST(s0() == 0); } { boost::signal0<int, max_or_default<int> > s0; boost::BOOST_SIGNALS_NAMESPACE::connection c2 = s0.connect(i2); boost::BOOST_SIGNALS_NAMESPACE::connection c72 = s0.connect(i72); boost::BOOST_SIGNALS_NAMESPACE::connection c62 = s0.connect(i62); boost::BOOST_SIGNALS_NAMESPACE::connection c42 = s0.connect(i42); const boost::signal0<int, max_or_default<int> >& cs0 = s0; BOOST_TEST(cs0() == 72); } { make_increasing_int<7> i7; make_increasing_int<10> i10; boost::signal0<int, max_or_default<int> > s0; boost::BOOST_SIGNALS_NAMESPACE::connection c7 = s0.connect(i7); boost::BOOST_SIGNALS_NAMESPACE::connection c10 = s0.connect(i10); BOOST_TEST(s0() == 10); BOOST_TEST(s0() == 11); } } static void test_one_arg() { boost::signal1<int, int, max_or_default<int> > s1; s1.connect(std::negate<int>()); s1.connect(std::bind1st(std::multiplies<int>(), 2)); BOOST_TEST(s1(1) == 2); BOOST_TEST(s1(-1) == 1); } static void test_signal_signal_connect() { boost::signal1<int, int, max_or_default<int> > s1; s1.connect(std::negate<int>()); BOOST_TEST(s1(3) == -3); { boost::signal1<int, int, max_or_default<int> > s2; s1.connect(s2); s2.connect(std::bind1st(std::multiplies<int>(), 2)); s2.connect(std::bind1st(std::multiplies<int>(), -3)); BOOST_TEST(s2(-3) == 9); BOOST_TEST(s1(3) == 6); } // s2 goes out of scope and disconnects BOOST_TEST(s1(3) == -3); } struct EventCounter { EventCounter() : count(0) {} void operator()() { ++count; } int count; }; static void test_ref() { EventCounter ec; boost::signal0<void> s; { boost::BOOST_SIGNALS_NAMESPACE::scoped_connection c = s.connect(boost::ref(ec)); BOOST_TEST(ec.count == 0); s(); BOOST_TEST(ec.count == 1); } s(); BOOST_TEST(ec.count == 1); } int test_main(int, char* []) { test_zero_args(); test_one_arg(); test_signal_signal_connect(); test_ref(); return 0; }
__label__pos
0.820084
Two questions about blogging & the internet........ Discussion in 'Et Cetera, Et Cetera' started by Miscer, May 24, 2011. 1. Miscer Miscer New Member Joined: Feb 2, 2011 Messages: 267 Likes Received: 6 I'm no computer wizard, so help a guy out 1. Do web caches eventually get deleted? Specifically, if I post a blog entry (on blogger.com), and then later delete it, does the cache of the deleted post float in cyberspace forever? 2. On blogger.com, can your "followers" tell if you edit your post? i.e. do they get notified. I assume they can be notified when you make a new post, but are they notified when you edit an old post? I suspect this is a long shot, but maybe someone will know the answers :cool:   2. Pendlum Verified Gold Member Joined: Feb 24, 2008 Messages: 2,143 Albums: 2 Likes Received: 5 Gender: Male Verified: Photo They say once something is on the internet, it's on there forever. This more applies to images and videos really, since this are things people actually save and reupload places. How often do you save a blog page? Only if someone uses your blog in their own webpage or something and quotes it you will it really live on. So you always run the risk of it being out there after you delete the source. The very definition of cache is that it is temporary. Sometimes things like google cache will log dead sites, but it all eventually goes dead and I wouldn't worry about that. I don't know about your second question since I don't blog and don't know anything about that site.   3. MsThang Verified Gold Member Joined: Jan 8, 2011 Messages: 527 Albums: 3 Likes Received: 328 Gender: Female Location: South Florida (recently relocated from NYC) Verified: Photo oh shit, my tits are on the Internet forever   4. monel Gold Member Joined: Aug 23, 2007 Messages: 1,677 Likes Received: 8 Gender: Male The internet's gain.   5. Miscer Miscer New Member Joined: Feb 2, 2011 Messages: 267 Likes Received: 6 Ah, ok, cool. Not entirely sure what you mean when you ask how often I save a blog page - I just started a blog today, and I'm just trying to ensure I don't put something up there I can't take back. Mine too.   6. Pendlum Verified Gold Member Joined: Feb 24, 2008 Messages: 2,143 Albums: 2 Likes Received: 5 Gender: Male Verified: Photo What I meant is when you read someone else's blog, how often do you save the text or webpage of said blog, so it has nothing to do with your own blog. Then compare that to how often you save other things like images, videos, music, porn. Chances are you'll always be able to take back the source, but you don't have much control on what others do with what you post.   7. Miscer Miscer New Member Joined: Feb 2, 2011 Messages: 267 Likes Received: 6 Gotcha, cheers.   8. Enid Gold Member Joined: Jul 3, 2008 Messages: 4,391 Albums: 1 Likes Received: 207 Gender: Female Location: My home is wherever reality seems elastic and the Internet Archive: Digital Library of Free Books, Movies, Music & Wayback Machine check out the wayback machine. i've found old web pages that way including blogs just to let you know.   #8 Enid, May 25, 2011 Last edited: May 25, 2011 Draft saved Draft deleted
__label__pos
0.978484
Bird configuration Neil Alexander has provided his Bird config for those who want to run a CRXN router using enterprise software. Obviously there is a blacholed route, you won't want that and also the IP numbers must be changed to suit your configuration. filter crxn4 { if source = RTS_STATIC then accept; if net ~ [ 10.0.0.0/8+ ] then accept; reject; }; filter crxn6 { if source = RTS_STATIC then accept; if net ~ [ fd8a:6111:3b1a::/48+ ] then accept; reject; }; protocol static { ipv4; route 10.4.3.0/24 blackhole; } protocol static { ipv6; route fd8a:6111:3b1a:eeee::/64 blackhole; } protocol babel { randomize router id yes; ipv4 { import filter crxn4; export filter crxn4; }; ipv6 { import filter crxn6; export filter crxn6; }; interface "crxn*" { type wired; }; } protocol device { scan time 60; } protocol direct { ipv4; ipv6; } protocol kernel { ipv4 { export all; import none; }; }
__label__pos
0.999611
The tag has no usage guidance. learn more… | top users | synonyms 2 votes 1answer 162 views Non-diffeomorphic smooth structures on the quotient of a manifold by an integrable distribution In geometric quantization, one of the important ingredients is an integrable distribution $D$ (let's say real) on some manifold $M$ (symplectic, but this is not important). The resulting object is ... 1 vote 1answer 52 views Analytic conjugacy of vanishing holonomy groups implies analytic conjugacy of foliations i am reading and trying to do some exercises and problems of the book Lectures on Analytic Differential Equations- Y. Ilyashenko, S. Yakovenko. I can not solve the problem 11.6 that says Consider ... 1 vote 2answers 77 views Nonlinear PDE for a 2D foliation I am trying to solve a 4th order nonlinear PDE for a real function $u(x,y)$ of two variables. It is too complicated to reproduce here but it exhibits the following two very nice properties: 1) if ... 1 vote 0answers 79 views A specific type of first-order nonlinear ordinary differential equation I am trying to divide $\mathbb{R}^+\times \mathbb{R}^+$ into some curves so that the integration of the function $ h(x)h(y) $(where $h(x)$ is a $C^1$ function from $\mathbb{R}^+\to \mathbb{R}^+$ that ... 3 votes 1answer 135 views Euler Class constant on Fibered Face of Unit Thurston Norm Ball? I am reading about the Thurston norm out of Candel and Conlon's "Foliations 2" and Calegari's "Foliations and the Geometry of 3-Manifolds". I'm trying to work through the proof of the "Fibered ... 2 votes 0answers 83 views Pulled back foliation is completely integrable There is a question that arises, while I'm trying to understand Guillemin & Sternbergs paper "On collective complete integrability according to the method of Thimm". Assume $M$ is a symplectic ... 2 votes 2answers 344 views algebraic leaves of foliation on a product of two curves Let $S=E\times C$ be a product of two curves, where $E$ is an elliptic curve and $C$ is a curve of genus at least two. Consider a foliation on $S$ generated by a global holomorphic 1-form ... 31 votes 3answers 2k views What is a foliation and why should I care? The title says everything but while it is a little bit provocative let me elaborate a bit about my question. First time when I met the foliation it was just an isolated example in the differential ... 4 votes 1answer 107 views Glueing together functions defined on the leaves of a foliation Even though my question can be asked for very general types of foliations, I am interesetd only in its answer for Poisson manifolds, which are what I am currently studying. Consider a Poisson ... 1 vote 0answers 44 views Smoothness of the twistor space of a lorentzian manifold, or “convexity wrt null geodesics” Null lines in Minkowski space form a 5-dimensional manifold, represented as a (real) quadric $\mathbf{PN}\subset\mathbb{C}\mathbf{P}^3$. This is a well-known fact, on which R. Penrose’s twistor ... 0 votes 0answers 43 views Integrability of the orthogonal complement of a holomorphic vector field on $\mathbb{C}^{2}$ Assume that $$\begin{cases}\dot x=P(x,y)\\\dot y=Q(x,y)\end{cases}$$ is a non vanishing holomorphic vector field on an open subset $U$ of $\mathbb{C}^{2}\simeq \mathbb{R}^{4}$. It defines a two ... 3 votes 2answers 125 views When are simple foliations strictly simple? Any submersion $f: M → N$ defines a foliation of M whose leaves are the connected components of the fibres of $f$. Foliations associated to the submersions are called simple foliations. The foliations ... 5 votes 0answers 80 views On Holonomy in (regular) Riemannian Foliations Right now, I am trying to understanding the role of holonomy fields on Riemannian foliations, which lead me to the following (probably topological) groupoid: Let $\mathcal{F}\subset M$ be a ... 9 votes 1answer 216 views Conformal changes of metric and geodesics Suppose $(M,g)$ is a Riemannian manifold. Let us assume that $X$ denotes a vector field in this manifold and consider the integral curves of this vector field. Does there exist a conformal factor $c$ ... 5 votes 0answers 95 views A finiteness question for integrable polynomial distributions on $\mathbb{R}^3$ This question is motivated by the finitness of limit cycles for polynomial vector fields on $\mathbb{R}^2$ Assume that $X,Y$ are two independent polynomial vector fields on $\mathbb{R}^{3}$ such ... 6 votes 1answer 135 views Closed leaves of a foliation Let $M$ be a differentiable manifold of dimension $n + k$, let $\Delta$ be an $n$-dimensional integrable distribution (à la Frobenius), let $N$ be an $n$-dimensional connected integral manifold of ... 0 votes 0answers 114 views The complex leaves containing real limit cycles of Lienard equation According to the answer and comments to this question we realize that a useful approach to such type of questions is to consider algebraic vector field which possess algebraic solutions. On the ... 2 votes 0answers 61 views Can we foliate the anti-de sitter space in 3 dimensions by Riemann surfaces? Can we foliate the anti-de sitter spacetime in 3 dimensions by hyperbolic Riemann surfaces? -- I think this is possible, but got stuck at finding the particular projective mapping that does this. Can ... 13 votes 1answer 219 views Three-manifolds having a Reebless foliation but not a taut one A straightforward argument reveals that a taut foliation is Reebless, and of course there are many examples of Reebless foliations that are not taut. I guess that there are many examples of ... 1 vote 0answers 118 views Taylor expansion in Riemannian foliations Take: $M$ a Riemannian manifold, ${X_0}\in M$, $N_{X_0}$ a submanifold of $M$ going through ${X_0}$, and $Z \in N_{X_0}$ in a neighborhood of ${X_0}$. At ${X_0} \in N_{X_0}$, we consider the ... 7 votes 1answer 177 views Smooth conditional measures for strong stable foliations of Anosov flows I am trying to prove an analytic result for gesodesic flows on negatively curved manifolds and I encountered the following dynamical-system porblem. Let $B^n$ be $n$-dimensional balls and ... 1 vote 1answer 124 views Stability of singularity in singular holomorphic foliation For an open subset $U$ of $\mathbb{C}^{2}$ containing $0$ and a holomorphic map $f:U\to \mathbb{C}^{2}$ which has a unique zero at the origin we associate a natural singular holomorphic ... 1 vote 1answer 57 views Comparision of two $C^{*}$ algebras associated to a non vanishing vector field on a compact manifold Let $X$ be a non vanishing vector field on a compact manifold $M$ so we have a one dimensional foliation $F$ of $M$ with orbits of $X$. This foliation defines a $C^{*}$ algebra $C^{*}(F)$. On the ... 1 vote 0answers 95 views A noncommutative vector bundle associated with a codimension one foliation Assume that we have a codimension one foliation of a manifold $M$ which is generated by a one form $\alpha$. So the following $\phi$ satisfies $\phi \circ \phi =0$:$$\phi:\Omega^{i}(M)\to ... 0 votes 0answers 113 views Product of two foliations 1.What is an example of a manifold $M$ with two foliations $F$ and $F'$ which are not topological equivalent but the product foliations $F\times F$ and $F'\times F'$, as foliations on $M\times M$, ... 3 votes 2answers 338 views Is this a $C^0$ foliation of $\mathbb{R}^2$? Let $f(x)=\frac{1}{\sin(\pi x)}$ for $x\in (0, 1)$ and let $\Gamma=\left\{(x,f(x)): x\in (0, 1)\subset \mathbb{R}^2\right\}$ be its graph. For any set $X\subset \mathbb{R}^2$ and $\lambda>0$ and ... 1 vote 0answers 94 views Regularity of the taut foliation In Eliashberg-Thurston's famous paper "Confoliations" Corollary 3.2.11, they proved that Irreducible three manifold with $b_{1}>0$ admits semi-fillable contact structure using Gabai's theorem in ... 1 vote 0answers 55 views A cohomology associated with a codimension one foliation(2) What is an example of a codimension one foliation of a manifold for which this cohomology is finite dimension for all dimension $*$? Moreover what is the description of this cohomology for ... 1 vote 0answers 200 views A Lie algebra associated with a one dimensional foliation A non vanishing vector field $X$ on a manifold is called "well behaved" if for every non vanishing smooth function $f$ we have $$C(X)\simeq C(fX)$$ This means that the centralizer Lie algebras ... 1 vote 1answer 101 views A cohomology associated with a codimension one foliation Let $\alpha$ be a non vanishing one form on a manifold which which defines a codimension one foliation. With this $\alpha$ we define the following complex: $$\phi:\Omega^{i}(M)\to ... 8 votes 1answer 201 views Foliation with leaves which are and are not dense Do there exist a foliation on a closed surface (i.e. real dimension 2) which has a dense leaf and also a leaf which is not dense? 5 votes 0answers 246 views Topology of the space of foliations on a 3-manifold Denote by $\mathcal{P} (M)$ the space of smooth plane fields(oriented and transversely oriented) on a given closed and orientable 3-manifold $M$ with the $C^{\infty}$ topology, and by $\mathcal{F}(M)$ ... 5 votes 0answers 261 views When does a leaf space admit a (non-Hausdorff) manifold structure? If $f:M \to N$ is a submersion with connected fibers, then the fibers of $f$ foliate $M$. This is called a simple foliation of $M$ and the leaf space can be identified with $N$. Suppose that a ... 3 votes 0answers 258 views Classification of complex Kronecker foliations Let $\theta \in \mathbb{C}$ be a fixed complex number. The submersion $f:\mathbb{C}^{2}\to \mathbb{C}\; \text{with}\; f(x,y)=y-\theta x$ defines a complex foliation on $\mathbb{C}^{2}$. Consider the ... 2 votes 0answers 135 views A (different) foliation arising from Hopf fibration In this question, first we fix an isomorphism between $TS^{3}$ and $S^{3}\times \mathbb{R}^{3}$.(To be more precise we consider the global trivialization of $TS^{3}$ with help of $3$ global ... 4 votes 1answer 236 views A special non vanishing vector field on $S^{3}$ Is there a non vanishing vector field on $S^{3}$ with an infinite family $T_{\lambda}$ of invariant torus such that each $T_{\lambda}$ has an structure of a Kronecker foliation but for ... 1 vote 0answers 248 views Lifting a quadratic system to a non vanishing vector field on $S^{3}$ or $T^{1} S^{2}$ Let $P:S^{3}\to S^{2}$ be the Hopf fibration. For a vector field $X$ on $S^{2}$ there is a non vanishing vector field $\tilde{X}$ on $S^{3}$ such that $DP(\tilde{X})=X$. It is constructed in ... 1 vote 1answer 123 views On the realization of a compact surface as a leaf of an analytic foliation Let $S$ be a compact orientable surface of genus $g \geq 2$. Is there any transversely real (or complex) analytic codimension one foliation $\mathcal{F}$ such that $\mathcal{F}$ has $S$ as a leaf with ... 2 votes 2answers 208 views Complementary integrable vector fields Let $(M,g)$ be a Riemannian manifold. Assume that $X$ is a non vanishing vector field tangent to $M$.(Or assume that we have a one dimensional foliation of $M$). Under what geometric ... 3 votes 0answers 167 views Characterization of certain analytic vector fields on $S^{2}$ Let $X$ be a real analytic vector field on $S^{2}$ which satisfies: $X$ has a finite number of singularities on $S^{2}$ The equator is invariant under flow of $X$ 3.$g_{*}X=\pm X$ where $g$ ... 6 votes 1answer 222 views Are codimension one foliations of $\mathbb{R}^{n}-\{0\}$ with compact leaves, stable at origin? Assume that we have a codimension one foliation of $\mathbb{R}^{n}-\{0\}$ with compact leaves. Is it true to say that the foliation is stable at origin:That is: for every neighborhood $V$ of ... 8 votes 1answer 246 views “The” kronecker foliation or “a” kronecker foliation? Consider the following two foliations of torus: 1)The Kronecker foliation with slope $\sqrt{2}$ 2)The Kronecker foliation with slope $\pi$ As I learn from the literature, these two foliations are ... 2 votes 1answer 190 views The type of a Riemann surface arising from a polynomial vector field Consider the planar polynomial vector field $$\begin{cases} \dot x=P(x,y)\\ \dot y=Q(x,y)\end{cases}$$ It defines a singular foliation on $\mathbb{C}P^{2}$. Assume that a complex leaf contains ... 4 votes 1answer 321 views Holomorphic Foliations having transverse sections In the introduction to the paper "On the Geometry of Holomorphic Flows and Foliations Having Transverse Sections" by Ito and Scardua, one reads the following "a holomorphic codimension one foliation ... 3 votes 0answers 68 views Hessian eigenspaces form integrable distributions on a Riemannian manifold? Suppose $M$ is a Riemannian manifold and $f:M\to\mathbb{R}$ a differentiable function. I can form the Hessian $H$ of $f$ (with respect to the Levi-Civita connection); this is a symmetric bilinear ... 1 vote 0answers 158 views Foliation of the tangent bundle of $n$-sphere Is there a smooth $n$-dimensional foliation of $TS^{n}$,( here $n\neq1,3,7$) such that the zero section be a leaf of this foliation? 2 votes 1answer 154 views Anti_symplectic 2-forms A two form $\alpha$ on a n- manifold $M$ is called anti symplectic if for every $x\in M$, $\{ v\in T_{x} M \mid i_{v} \alpha=0 \}$ is a $n-2$ dimensional subspace of $T_{x}M$. So we obtain a $n-2$ ... 9 votes 3answers 854 views Limit cycles as closed geodesics(in negatively curved space) The classical Van der Pol equation is the following vector field on $\mathbb{R}^{2}$: \begin{equation}\cases{\dot{x}=y-(x^{3}-x)\\ \dot{y}=-x}\end{equation} This equation defines a foliation on ... 2 votes 0answers 67 views Extendability of Contact Structures; Foliations of $S^2$ I am currently reading Eliashberg's paper on the classification of overtwisted contact structures (http://bogomolov-lab.ru/G-sem/eliashberg-tight-overtwisted.pdf). In it, there is the following ... 0 votes 1answer 111 views Can an analytic set admit such a foliation? I confess to be not an expert of analytic geometry, but I have come across the following problem, for which I need an help from experts in this specific field. I was wondering myself if it is ...
__label__pos
0.850111
You can use the same below configs for other supported identity provider. # Configure # Docker-compose version: "3" services: pomerium: image: pomerium/pomerium:latest environment: # Generate new secret keys. e.g. `head -c32 /dev/urandom | base64` - COOKIE_SECRET=<reducted> volumes: # Mount your domain's certificates : https://www.pomerium.io/docs/reference/certificates - ./_wildcard.localhost.pomerium.io-key.pem:/pomerium/privkey.pem:ro - ./_wildcard.localhost.pomerium.io.pem:/pomerium/cert.pem:ro # Mount your config file : https://www.pomerium.io/docs/reference/reference/ - ./config.yaml:/pomerium/config.yaml ports: - 443:443 - 5443:5443 - 17946:7946 depends_on: - identityprovider httpbin: image: kennethreitz/httpbin:latest expose: - 80 identityprovider: image: qlik/simple-oidc-provider environment: - CONFIG_FILE=/etc/identityprovider.json - USERS_FILE=/etc/identityprovider-users.json volumes: - ./identityprovider.json:/etc/identityprovider.json:ro - ./identityprovider-users.json:/etc/identityprovider-users.json:ro ports: - 9000:9000 You can generate certificates for *.localhost.pomerium.io using this instruction # Pomerium config # config.yaml # See detailed configuration settings : https://www.pomerium.io/docs/reference/reference/ authenticate_service_url: https://authenticate.localhost.pomerium.io autocert: false certificate_file: /pomerium/cert.pem certificate_key_file: /pomerium/privkey.pem idp_provider_url: http://identityprovider:9000 idp_provider: oidc idp_client_id: foo idp_client_secret: bar # Generate 256 bit random keys e.g. `head -c32 /dev/urandom | base64` cookie_secret: <reducted> # https://www.pomerium.io/configuration/#policy policy: - from: https://httpbin.localhost.pomerium.io to: http://httpbin allowed_domains: - example.org # identityprovider.json { "idp_name": "http://identityprovider:9000", "port": 9000, "client_config": [ { "client_id": "foo", "client_secret": "bar", "redirect_uris": [ "https://authenticate.localhost.pomerium.io/oauth2/callback" ] } ], "claim_mapping": { "openid": [ "sub" ], "email": [ "email", "email_verified" ], "profile": [ "name", "nickname" ] } } # identityprovider-user.json [ { "id": "SIMPLE_OIDC_USER_ALICE", "email": "[email protected]", "email_verified": true, "name": "Alice Smith", "nickname": "al", "password": "abc", "groups": ["Everyone", "Engineering"] }, { "id": "SIMPLE_OIDC_USER_BOB", "email": "[email protected]", "email_verified": true, "name": "Bob Smith", "nickname": "bobby", "password": "abc", "groups": ["Everyone", "Sales"] } ] # Run # Edit hosts file Add following entry to /etc/hosts: 127.0.0.1 identityprovider # Start services $ docker-compose up -d identityprovider $ : wait identityprovider up $ docker-compose up -d Now accessing to https://httpbin.localhost.pomerium.io and you will be redireted to OIDC server for authentication.
__label__pos
0.999359
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I have a user defined function in SQL Server and there is a section in the code that I need help getting an explanation for its process. I've been interning for a couple of months now, learning SQL from scratch but I'm a afraid this is a bit of a beast for me and maybe someone with an experienced eye can help me. There are six points that work in priority order and I need to know where and how point 2 will take into effect when point 1 isn't. I know what Case, Datediff & Dateadd are on a few lines of code when I practice but as you can appreciate, this looks horribly convoluted when these Case statements are feeding into several steps, so I'm not looking for an explanation on Tsql etc.. Just what the code looks like it's doing and where point 2 feeds in. -- Fill missing periods with estimates -- Estimation methods (for missing data): -- 1. Month Average: take a daily average from existing month data and use for all days missing for the month -- 2. Previous Year Month Average: take a daily average from month in previous year and use for all days missing for the month -- 3. Quarter Average: take a daily average from quarterly data and use for all days missing for the quarter -- 4. Previous Year Quarter Average: take a daily average from quarter in previous year and use for all days missing for the quarter -- 5. Year Average: take a daily average from annual data and use for all days missing -- 6. Previous Year Average: take a daily average from previous year and use FilledConsumption as ( Select a.* , case when a.Begin_Date >= '2012-4-1' and DATEDIFF(dd,case when first_actual < dateadd(yy,a.CRC_Year-1,@StartDate) then dateadd(yy,a.CRC_Year-1,@StartDate) else first_actual end, last_actual)+1 >= (DATEDIFF(dd , case when Utility_Begin_Date > dateadd(yy,a.CRC_Year-1,@StartDate) then Utility_Begin_Date else dateadd(yy,a.CRC_Year-1,@StartDate) end , case when max_date < case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end and Utility_Status = 1 then max_date else case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end end )+1)/2 then 'Actual' -- Should match the previous Q4 report calculation when a.Begin_Date < '2012-4-1' and DATEDIFF(dd,year_first_actual, year_last_actual)+1 >= (DATEDIFF(dd , case when Utility_Begin_Date > dateadd(yy,a.CRC_Year-1,@StartDate) then Utility_Begin_Date else dateadd(yy,a.CRC_Year-1,@StartDate) end , case when max_date < case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end and Utility_Status = 1 then max_date else case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end end )+1)/2 then 'Actual' else 'Estimated' end as crc_actual , max(case when DATEDIFF(dd,case when first_actual < @StartDate then @StartDate else first_actual end, last_actual)+1 >= (DATEDIFF(dd , case when Utility_Begin_Date > @StartDate then Utility_Begin_Date else @StartDate end , case when max_date < @EndDate and Utility_Status = 1 then max_date else @EndDate end )+1)/2 and a.CRC_Year = 1 then 1 else 0 end) over (partition by a.utility_id) as crc_actual_this_year -- Estimates for missing this year , case when Days_Missing > 0 then a.month_avg_daily_cons end*Days_Missing as avg_same_month , case when Days_Missing > 0 then a.quarter_avg_daily_cons end*Days_Missing as avg_same_quarter , case when Days_Missing > 0 then a.year_avg_daily_cons end*Days_Missing as avg_same_year -- Estimates for missing previous year , case when Days_Missing > 0 then b.month_avg_daily_cons end*Days_Missing as avg_prev_month , case when Days_Missing > 0 then b.quarter_avg_daily_cons end*Days_Missing as avg_prev_quarter , case when Days_Missing > 0 then b.year_avg_daily_cons end*Days_Missing as avg_prev_year From ( Obviously, this is part of a code for filling in date gaps with estimated consumption values so I hope the field names are quite self explanatory and useful, but I'm open to anyone's suggestions and thoughts, as I assume that without the entire script this could be open to slight interpretation. Thanks as always and I look forward to chatting with you, Useless_Wizard share|improve this question add comment 1 Answer up vote 0 down vote accepted I am not sure I completely understand your question--are you asking how (i.e. what parameters are used) the code determines whether a value is 'Actual' or 'Estimated'? The first step in approaching the answer would be to reformat the query so that the CASE statements are in clearly-defined blocks (this is tricky since several of the DATEDIFF functions contain CASE statements themselves). Once this is done, it will be much easier to evaluate the statements. With a brief glance, I do not see any logic that actually fills in the previous month's average (at least, in the sample you provided). However, the first two columns (crc_actual and crc_actual_this_year) should probably be where you begin. These are the two columns that use many in-line CASE statements that are confusing unless you reformat them: case when a.Begin_Date >= '2012-4-1' and DATEDIFF(dd, case when first_actual < dateadd(yy,a.CRC_Year-1,@StartDate) then dateadd(yy,a.CRC_Year-1,@StartDate) else first_actual end, last_actual)+1 >= (DATEDIFF(dd, case when Utility_Begin_Date > dateadd(yy,a.CRC_Year-1,@StartDate) then Utility_Begin_Date else dateadd(yy,a.CRC_Year-1,@StartDate) end, case when max_date < case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end and Utility_Status = 1 then max_date else case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end end )+1)/2 then 'Actual' -- Should match the previous Q4 report calculation when a.Begin_Date < '2012-4-1' and DATEDIFF(dd,year_first_actual, year_last_actual)+1 >= (DATEDIFF(dd, case when Utility_Begin_Date > dateadd(yy,a.CRC_Year-1,@StartDate) then Utility_Begin_Date else dateadd(yy,a.CRC_Year-1,@StartDate) end, case when max_date < case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end and Utility_Status = 1 then max_date else case when a.CRC_Year = 1 then @EndDate else dateadd(dd,-1, @StartDate) end end )+1)/2 then 'Actual' else 'Estimated' end as crc_actual, max( case when DATEDIFF(dd, case when first_actual < @StartDate then @StartDate else first_actual end, last_actual)+1 >= (DATEDIFF(dd, case when Utility_Begin_Date > @StartDate then Utility_Begin_Date else @StartDate end, case when max_date < @EndDate and Utility_Status = 1 then max_date else @EndDate end )+1)/2 and a.CRC_Year = 1 then 1 else 0 end) over (partition by a.utility_id) as crc_actual_this_year, Does this help? share|improve this answer      Hey Borghm! Thanks for reading my post, a lot of my questions are vague I'm afraid as I've only been learning Tsql for a couple of months. My query is where in the script of CASE statements does point 2, "The previous month average i:e" is used. It's true I edited some of the comments out to reduce the size and it has been mentioned that the readability can be improved. Though as this works it doesn't need altering, I'm just trying to work out how point two is calculated and then calculate using data on our reports, as someone as noticed a disparity between two outputs. –  Useless_Wizard Feb 7 '13 at 11:32      I added some stuff to my answer--unfortunately I don't have time right now to look deeper. Hopefully, this will get you started. –  borghm Feb 8 '13 at 4:24      Thank you Borghm, I really do appreciate the amendment, and yes your right if the readability was improved then maybe I wouldn't have to be on here asking vague questions! But I would like to say that I have saved your script, as hopefully in the future we can start cleaning some of our functions up for auditing purposes. But just to add, I calculated the value front end and there's no discrepancy, meaning the code works.. Just I don't know how lol –  Useless_Wizard Feb 12 '13 at 17:06 add comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.665072
0 $\begingroup$ I'm trying to learn about DSU, and I came across a point stating if two vertices belong to the same sub-set, then a cycle exists. In terms of implementation of DSU, I'm unable to make sense of this. Could you share a proof or explain this? $\endgroup$ • 1 $\begingroup$ What is DSU? Could you please show the original source that states this assertion? $\endgroup$ – xskxzr Mar 20 at 12:14 • 1 $\begingroup$ DSU stands for Disjoint Set Union. The term "disjoint-set" or "union-find" is preferable much more. $\endgroup$ – Apass.Jack Mar 20 at 16:09 3 $\begingroup$ The way it works is that your sets are connected components of the graph. You build such components incrementally, adding one edge at a time. When you add each edge, you ask if the vertices are part of the same component, if so then you have a cycle, if not, then you join the two components (perform a set union). Keep adding edges until you run out of them or found a cycle. If we look at the definition of connected component, it implies that for each two vertices $u$ and $v$ in the same component, there's a path connecting them. The algorithm works as follows: you start adding a Singleton set for each vertex to your dsu. These are your first components. Then add the first edge, obviously, the two vertices will be on separate sets (components), and you just found an edge connecting them, so that means they belong to the same component. So you join the two sets (components) into a single one, as your edge is the path connecting them. You keep going, everytime you find an edge connecting two vertices in different components, you can join the components, as that edge will be a bridge connecting them: if the vertices are $u$ and $v$, and you have $w$ in $u$'s component, you can assert that there's a path from $w$ to $v$ passing through your current edge. Is easy to see now that all vertices in both components are now connecting. So join the two sets (components) in one. Finally, when you process an edge which vertices $u, v$ are on the same component, you just found a cycle: since both are on the same component, you know there's a path between them, and your new edge happens to close the cycle. DSU is typically used for implementing Kruskal's algorithm, and uses the same properties. You can do a quick Google search for Kruskal with DSU, for examples. $\endgroup$ Your Answer By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.960303
Up Centroid The centroid of the triangle is the point at which the three medians intersect, that is, the centroid is the point of intersection between the three lines, each of which pass through a vertex of the triangle and the midpoint of the opposite leg, as shown in the diagram below: Properties-of-Triangles-Finding-the-Centroid-1 It is relatively easy to find the centroid of a triangle that sits in the coordinate plane.  Let a triangle in the plane have vertices with coordinates \(\left( {{x_1},{y_1}} \right)\), \(\left( {{x_2},{y_2}} \right)\), and \(\left( {{x_3},{y_3}} \right)\). Then the centroid of the triangle is given by the coordinates \(\left( {\Large \frac{{{x_1} + {x_2} + {x_3}}}{3},\Large \frac{{{y_1} + {y_2} + {y_3}}}{3}} \right)\) EXAMPLE:  Find the coordinates of the centroid of the triangle given below Properties-of-Triangles-Finding-the-Centroid-2 SOLUTION:  The three coordinates of the vertices of the triangle are \(\left( { - 6, - 6} \right)\), \(\left( { - 3, - 2} \right)\), and \(\left( {1, - 2} \right)\). Then the centroid has coordinates \(\left( {\Large \frac{{{x_1} + {x_2} + {x_3}}}{3},\Large \frac{{{y_1} + {y_2} + {y_3}}}{3}} \right) = \left( {\Large \frac{{ - 6 + \left( { - 3} \right) + 1}}{3},\Large \frac{{ - 6 + \left( { - 2} \right) + \left( { - 2} \right)}}{3}} \right)\) \( = \left( { - \Large \frac{8}{3}, - \Large \frac{{10}}{3}} \right)\) So the centroid of the triangle is \(\left( { - \Large \frac{8}{3}, - \Large \frac{{10}}{3}} \right)\). Let’s try another example. EXAMPLE:  Find the coordinates of the centroid of the triangle given below Properties-of-Triangles-Finding-the-Centroid-3 SOLUTION:  The coordinates of the vertices of the triangle are \(\left( { - 4, - 1} \right)\), \(\left( { - 2, - 3} \right)\), and \(\left( {2, - 1} \right)\). Then the coordinates of the centroid of the triangle are \(\left( {\Large \frac{{{x_1} + {x_2} + {x_3}}}{3},\Large \frac{{{y_1} + {y_2} + {y_3}}}{3}} \right) = \left( {\Large \frac{{ - 4 + \left( { - 2} \right) + 2}}{3},\Large \frac{{ - 1 + \left( { - 3} \right) + \left( { - 1} \right)}}{3}} \right)\) \( = \left( { - \Large \frac{4}{3}, - \Large \frac{5}{3}} \right)\) So the coordinates of the centroid of the triangle are \(\left( { - \Large \frac{4}{3}, - \Large \frac{5}{3}} \right)\). So remember that anytime the vertices of the triangle are given as coordinates in the plane, we can easily find the centroid by simply plugging values into our simple formula.  It’s that easy! Below you can download some free math worksheets and practice. Downloads: 2248 x Find coordinates of the centroid of each triangle. This free worksheet contains 10 assignments each with 24 questions with answers. Example of one question: Properties-of-Triangles-Centroid-Easy Watch below how to solve this example:   Downloads: 1914 x Find coordinates of the centroid of each triangle. This free worksheet contains 10 assignments each with 24 questions with answers. Example of one question: Properties-of-Triangles-Centroid-Medium Watch below how to solve this example:   Downloads: 1813 x Find the coordinates of the centroid of each triangle given the three vertices. This free worksheet contains 10 assignments each with 24 questions with answers. Example of one question: Properties-of-Triangles-Centroid-Hard Watch below how to solve this example:       Facebook PageGoogle PlusTwitterYouTube Channel Algebra and Pre-Algebra Beginning Algebra Adding and subtracting integer numbers Dividing integer numbers Multiplying integer numbers Sets of numbers Order of operations The Distributive Property Verbal expressions Beginning Trigonometry Finding angles Finding missing sides of triangles Finding sine, cosine, tangent Equations Absolute value equations Distance, rate, time word problems Mixture word problems Work word problems One step equations Multi step equations Exponents Graphing exponential functions Operations and scientific notation Properties of exponents Writing scientific notation Factoring By grouping Common factor only Special cases Linear Equations and Inequalities Plotting points Slope Graphing absolute value equations Percents Percent of change Markup, discount, and tax Polynomials Adding and subtracting Dividing Multiplying Naming Quadratic Functions Completing the square by finding the constant Graphing Solving equations by completing the square Solving equations by factoring Solving equations by taking square roots Solving equations with The Quadratic Formula Understanding the discriminant Inequalities Absolute value inequalities Graphing Single Variable Inequalities Radical Expressions Adding and subtracting Dividing Equations Multiplying Simplifying single radicals The Distance Formula The Midpoint Formula Rational Expressions Adding and subtracting Equations Multiplying and dividing Simplifying and excluded values Systems of Equations and Inequalities Graphing systems of inequalities Solving by elimination Solving by graphing Solving by substitution Word problems
__label__pos
0.999989
Softcalocus Is not reachable I am not able to use Softcalocus but i am not able to use it. Where is the solution? Can you please fill out the template??? Saying “It no work” doesn’t help us at all. What actually happens? 1 Like He gives the connection timeout error trying to visiting the website Maybe you could search the forum first. You are not the first person to experience this. I solved it by myself This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
__label__pos
0.99992
OASIS Mailing List ArchivesView the OASIS mailing list archive below or browse/search using MarkMail.   Help: OASIS Mailing Lists Help | MarkMail Help dita-comment message [Date Prev] | [Thread Prev] | [Thread Next] | [Date Next] -- [Date Index] | [Thread Index] | [List Home] Subject: Re: Why are key reference ID targets restricted to non-topics elements? There are two reasons for the way key references work:   1. Topic references, which bind keys to resources, only address topics, not elements within topics, thus, keys defined on topic references can only be bound to DITA topics. Conversely, the only way to address a topic by key is to bind a key to that topic—you cannot address a literally-nested topic by key reference to an ancestor topic. 2. The ID name space for topics and the ID name space for elements within topics are separate ID name spaces. This means that the ID referenced on a key reference following the key can only refer to a non-topic element within the topic to which the key is bound.   For example, consider this topic, “topics/topic-01.dita”:   <topic id=”some-id”><title>Some Topic</title> <body>   <p id=”some-id”>This paragraph has the ID value “some-id”</p> </body> </topic>   And these topicrefs in some map:   <topicref keys=”topic-01” href=""> <topicref keys=”topic-02” href="">   And this key reference from topic topic-02.dita:   <p>See <xref keyref=”topic-01/some-id”/>.</p>   In the context of this map, the key reference “topic-01” resolves to the topic “topics/topic-01.dita” and the ID reference “some-id” can only resolve the non-topic element with the ID “some-id”—it could never refer to the topic element that happens to also have the ID value “some-id”.   This is also why you can’t use a key reference to a parent topic to refer to a child topic—the child topic must have its own key definition.   Within DITA topics, each topic defines a separate ID space, separate from the ID of the topic element itself and separate from the IDs of any nested topics. The @id attribute on topics is defined as type ID, meaning the IDs must be unique within the XML document that contains the topic, the but @id attribute on non-topic elements is defined as type NAME, so they do not have the usual uniqueness requirements of attributes of type ID.   As further example, consider this topic with a nested topic:   <topic id=”some-id”><title>Root Topic</title> <body>   <p id=”some-id”>This paragraph has the ID value “some-id”</p> </body> <topic id=”some-other-id”><title>Nested Topic</title> <body>   <p id=”some-id”>This paragraph has the ID value “some-id”</p> </body> </topic> </topic>   Here the two topic elements must have distinct @id values (“some-id” and “some-other-id”) but the <p> elements within them can both have the ID value “some-id” because each topic establishes a separate ID name space, so there is no conflict with either the root topic’s @id value or the two <p> elements with the same @id value in two different topics. Using the same @id value on non-topic elements within the same topic is an error per the DITA specification, but one that will not be detected by normal grammar validation. Within a topic, the first @id in document order with a given value is used as the target.   Cheers,   Eliot Kimber Member, DITA Technical Committee   Original request: Chris Trenkamp writes (https://lists.oasis-open.org/archives/dita-comment/202304/msg00000.html) For references to non-topic elements within topics, the value of the @keyref attribute is a key name, a slash ("/"), and the ID of the target element (for example, keyref="topic-key/some-element-id".) http://docs.oasis-open.org/dita/dita/v1.3/errata02/os/complete/part3-all-inclusive/archSpec/base/using-keys-for-addressing.html Why are keyref ID targets limited to non-topic elements?  I can’t find an explanation for this in the specification, and I can’t think of a reason why this restriction would be in place. In fact, this restriction seems to operate in direct contradiction to how the id attribute operates: http://docs.oasis-open.org/dita/dita/v1.3/errata02/os/complete/part3-all-inclusive/archSpec/base/id.html The specification states that id attributes on topic elements are XML attribute type ID’s, so they are strictly required to be unique by the XML parser.  All other id’s only have to be unique within the topic they are declared in.  It’s entirely possible to create a key reference to an element id that was declared multiple times in different sub-topics. I haven’t found anything in the specification that states how key references to an ID target that was redeclared multiple times is supposed to be resolved.  Does it take the first one?  Does it throw an error?  Is it up to the individual processor? At the very least, topic id’s are required to be unique by the XML parser, so you can be confident that when you create a key reference with an ID target to a topic, you know that target is unique. Can someone explain why this restriction is in place?  Is the reasoning still relevant?     _____________________________________________ Eliot Kimber Sr Staff Content Engineer O: 512 554 9368 M: 512 554 9368 servicenow.com LinkedIn | Twitter | YouTube | Facebook [Date Prev] | [Thread Prev] | [Thread Next] | [Date Next] -- [Date Index] | [Thread Index] | [List Home]
__label__pos
0.881844
Home Archives Categories Tags Docs ElasticSearch 安装使用 发布时间: 更新时间: 总字数:1194 阅读时间:3m 作者: 分享 ElasticSearch 是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。本文介绍 ElasticSearch 安装使用。 安装部署 略。 Lucene 介绍 lucene,就是一个jar包,里面包含了封装好的各种建立倒排索引,以及进行搜索的代码,包括各种算法。我们就用java开发的时候,引入lucene jar,然后基于lucene的api进行去进行开发就可以了。用lucene,我们就可以去将已有的数据建立索引,lucene会在本地磁盘上面,给我们组织索引的数据结构。另外的话,我们也可以用lucene提供的一些功能和api来针对磁盘上额 elasticsearch 底层封装 lucene: • 仅实时:秒级别 • 离线批处理:batch-processing 常用命令 version GET / { "name": "host-1", "cluster_name": "elasticsearch", "cluster_uuid": "sdfsfsdfsdfsd", "version": { "number": "5.1.2", "build_hash": "c8c4c16", "build_date": "2017-01-11T20:18:39.146Z", "build_snapshot": false, "lucene_version": "6.3.0" }, "tagline": "You Know, for Search" } 状态查询 GET _cat/health?v GET _cat/nodes?v GET _cluster/health GET _cluster/health?level=indices GET _cluster/health?level=shards GET /_cat/allocation?v GET _search { "query": { "match_all": {} } } 查询 elasticsearch-data-transform/ETL/clean/searchTemplate/ceilometer/cpu_util GET ceilometer_original-2018.01/_search { "query": { "constant_score": { "filter": { "bool": { "must": [ { "term": { "counter_name.keyword": { "value": "cpu_util" } } },{ "range": { "timestamp": { "gte": "now-3m", "lte": "now" } } } ] } } } } , "size": 10000, "_source": ["counter_name","counter_volume","resource_metadata.host","project_id","resource_metadata.instance_host","resource_metadata.vcpus","resource_metadata.memory_mb","resource_metadata.display_name","resource_metadata.name","resource_metadata.instance_id","timestamp","@timestamp"] } 执行查询 GET rollover_index_test/_search indices 查询: GET _cat/indices?v 删除: DELETE /test_xxb.2018.01 POST /_all/_forcemerge?only_expunge_deletes=true 为了安全起见,可以在配置文件中设置禁用_all和*通配符 action.destructive_requires_name = true https://www.elastic.co/guide/cn/elasticsearch/guide/current/_deleting_an_index.html#_deleting_an_index 设置副本数: PUT xxb_test.2018.01/_settings { "index":{ "number_of_replicas": 1 } } aliases GET _cat/aliases?v GET _cat/aliases/*unit_mb_memory_alias* https://www.elastic.co/guide/en/elasticsearch/reference/5.2/indices-aliases.html templates GET _cat/templates http://cwiki.apachecn.org/pages/viewpage.action?pageId=9406922 GET _template/sensu_storage_index_disk_iostats-metrics_template shard GET _cat/shards/applog-prod-2016.12.18* curl -XGET localhost:9200/_cat/shards?h=index,shard,prirep,state,unassigned.reason| grep UNASSIGNED GET /_cluster/allocation/explain?pretty command=/usr/share/logstash/bin/logstash -f /etc/logstash/conf.d/test.conf –path.data /data/01/logstash/sensu2es –http.port 9606 -b 1000 -w 4 GET _nodes/stats/process?filter_path=**.max_file_descriptors https://www.elastic.co/guide/cn/elasticsearch/guide/current/_cluster_health.html https://www.elastic.co/guide/cn/elasticsearch/guide/current/index-templates.html#index-templates settings GET /_cluster/settings 磁盘限额,为了保护节点数据安全。Elasticsearch会定时(cluster.info.update.interval默认为30秒)检查一下各节点的数据目录磁盘使用情况。在达到cluster.routing.allocation.disk.watermark.low(默认85%)的时候,新索引分片就不会再分配到这个节点上了。在达到cluster.routing.allocation.disk.watermark.high(默认90%)的时候就会触发该节点现存分片的数据平衡,把数据挪到其他节点上去。这两个值可以写成百分比或者具体字节数。可以适当修改参数配置: PUT _cluster/settings { "transient": { "cluster.routing.allocation.disk.watermark.low": "90%", "cluster.routing.allocation.disk.watermark.high": "50gb" } } https://www.elastic.co/guide/en/elasticsearch/reference/current/disk-allocator.html 数据迁移 下载 https://github.com/medcl/esm chmod +x esm # 导出数据 ./esm -s http://10.3.10.61:9200 -x "xxb_test_2018.1" -c 5000 -b 5 --refresh -o=xxb_test_2018.1.bin # 导入数据 ./esm -d http://10.3.10.61:9200 -y "xxb_test_2018.1" -c 5000 -b 5 --refresh -i=xxb_test_2018.1.bin 常见问题 Unassigned Shards 问题 解决elasticsearch集群Unassigned Shards 无法reroute的问题 https://www.jianshu.com/p/542ed5a5bdfc https://www.jianshu.com/p/329b9f92ac4c 解决方法: curl -XGET http://127.0.0.1:9200/_cat/shards | fgrep UNASSIGNED 删除对应的 index: DELETE /index-00000* POST /_all/_forcemerge?only_expunge_deletes=true 数据恢复 • 创建 reindex POST /_reindex { "source": { "index": "xxb_test.2018.01" }, "dest": { "index": "xxb_test.2018.01.bak", "version_type": "external" } } 查看 indices 和 shards 是否正常: GET _cat/indices/xxb_test.2018.01.bak GET _cat/shards/xxb_test.2018.01.bak 删除异常 index: DELETE /xxb_test.2018.01 es 是标记为删除,需要执行以下命令清除磁盘空间: POST /_all/_forcemerge?only_expunge_deletes=true 设置别名: PUT xxb_test.2018.01.bak/_alias/xxb_test.2018.01 内存错误 java.lang.OutOfMemoryError: Java heap space 调整jvm.options中如下参数: -Xms16g -Xmx16g elasticsearch 的 java heap : os memory 在 35%-45% 之间比较好,但是 java heap 不能超过 32G,超过32G,elasticsearch 不会使用指针压缩算法。 操作系统&JVM配置官方说明: 参考 相关文章 最近更新 最新评论 加载中...
__label__pos
0.60219
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute: Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top I have 2 tables side by side. Table 1 is dynamic and while table 2 is static (fixed content). I need to adjust the row height of table 2 which must be equal to total height of table 1 (like multirow) but I don't want to use multirow. \documentclass{article} \usepackage{subcaption} \begin{document} \begin{minipage}{0.8\linewidth} \begin{tabular}{ | p{5cm} | p{1cm} | p{2.5cm} | } \hline A clear day with lots of sunshine.However, the strong breeze will bring down the temperatures & 2 & 3 \\[2cm] \hline A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures & 5 & 6 \\[2cm] \hline A clear day with lots of sunshine. However, the strong breeze will bring down the temperatures & 8 & 9 \\[1cm] \hline \end{tabular} \end{minipage} \begin{minipage}{0.2\linewidth} \begin{tabular}{ |p{5cm}| } \hline For columns that will contain text whose length exceeds the column's width, it is recommended that you use the p attribute and specify the desired width of the column (although it may take some trial-and-error to get the result you want). \\[5cm] \hline \end{tabular} \end{minipage} \end{document} enter image description here How can I implement this? share|improve this question 2   Any reason why you don't want to use \multirow? – Xavier Sep 9 '13 at 7:27      I had lot of issues while using multirow specially formatting and coloring. – manish Sep 9 '13 at 7:44      Related question. tex.stackexchange.com/questions/130907/…. In that answer, \vphantoms of the one table's row were inserted into the other table, and vice-versa. – Steven B. Segletes Sep 9 '13 at 10:22      @manish Just my personal opinion, but for what it looks you're trying to achieve, solving the few issues you might have with \multirow seem easier than trying to do without it... – Xavier Sep 9 '13 at 14:12      @Xavier I am using multirow currently but row is dynamic and it is colored too. So i use /srr and use negative value of multirow but i need to add points to adjust the text in multibox. That is not good for dynamic table. tex.stackexchange.com/questions/129518/… – manish Sep 10 '13 at 2:46 Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Browse other questions tagged or ask your own question.
__label__pos
0.993464
{-# OPTIONS_GHC -XNoImplicitPrelude -funbox-strict-fields #-} {-# LANGUAGE BangPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Encoding.UTF8 -- Copyright : (c) The University of Glasgow, 2009 -- License : see libraries/base/LICENSE -- -- Maintainer : [email protected] -- Stability : internal -- Portability : non-portable -- -- UTF-8 Codec for the IO library -- -- Portions Copyright : (c) Tom Harper 2008-2009, -- (c) Bryan O'Sullivan 2009, -- (c) Duncan Coutts 2009 -- ----------------------------------------------------------------------------- module GHC.IO.Encoding.UTF8 ( utf8, utf8_bom, ) where import GHC.Base import GHC.Real import GHC.Num import GHC.IORef -- import GHC.IO import GHC.IO.Exception import GHC.IO.Buffer import GHC.IO.Encoding.Types import GHC.Word import Data.Bits import Data.Maybe utf8 :: TextEncoding utf8 = TextEncoding { mkTextDecoder = utf8_DF, mkTextEncoder = utf8_EF } utf8_DF :: IO (TextDecoder ()) utf8_DF = return (BufferCodec { encode = utf8_decode, close = return (), getState = return (), setState = const $ return () }) utf8_EF :: IO (TextEncoder ()) utf8_EF = return (BufferCodec { encode = utf8_encode, close = return (), getState = return (), setState = const $ return () }) utf8_bom :: TextEncoding utf8_bom = TextEncoding { mkTextDecoder = utf8_bom_DF, mkTextEncoder = utf8_bom_EF } utf8_bom_DF :: IO (TextDecoder Bool) utf8_bom_DF = do ref <- newIORef True return (BufferCodec { encode = utf8_bom_decode ref, close = return (), getState = readIORef ref, setState = writeIORef ref }) utf8_bom_EF :: IO (TextEncoder Bool) utf8_bom_EF = do ref <- newIORef True return (BufferCodec { encode = utf8_bom_encode ref, close = return (), getState = readIORef ref, setState = writeIORef ref }) utf8_bom_decode :: IORef Bool -> DecodeBuffer utf8_bom_decode ref input@Buffer{ bufRaw=iraw, bufL=ir, bufR=iw, bufSize=_ } output = do first <- readIORef ref if not first then utf8_decode input output else do let no_bom = do writeIORef ref False; utf8_decode input output if iw - ir < 1 then return (input,output) else do c0 <- readWord8Buf iraw ir if (c0 /= bom0) then no_bom else do if iw - ir < 2 then return (input,output) else do c1 <- readWord8Buf iraw (ir+1) if (c1 /= bom1) then no_bom else do if iw - ir < 3 then return (input,output) else do c2 <- readWord8Buf iraw (ir+2) if (c2 /= bom2) then no_bom else do -- found a BOM, ignore it and carry on writeIORef ref False utf8_decode input{ bufL = ir + 3 } output utf8_bom_encode :: IORef Bool -> EncodeBuffer utf8_bom_encode ref input output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow, bufSize=os } = do b <- readIORef ref if not b then utf8_encode input output else if os - ow < 3 then return (input,output) else do writeIORef ref False writeWord8Buf oraw ow bom0 writeWord8Buf oraw (ow+1) bom1 writeWord8Buf oraw (ow+2) bom2 utf8_encode input output{ bufR = ow+3 } bom0, bom1, bom2 :: Word8 bom0 = 0xef bom1 = 0xbb bom2 = 0xbf utf8_decode :: DecodeBuffer utf8_decode input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ } output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os } = let loop !ir !ow | ow >= os || ir >= iw = done ir ow | otherwise = do c0 <- readWord8Buf iraw ir case c0 of _ | c0 <= 0x7f -> do ow' <- writeCharBuf oraw ow (unsafeChr (fromIntegral c0)) loop (ir+1) ow' | c0 >= 0xc0 && c0 <= 0xdf -> if iw - ir < 2 then done ir ow else do c1 <- readWord8Buf iraw (ir+1) if (c1 < 0x80 || c1 >= 0xc0) then invalid else do ow' <- writeCharBuf oraw ow (chr2 c0 c1) loop (ir+2) ow' | c0 >= 0xe0 && c0 <= 0xef -> case iw - ir of 1 -> done ir ow 2 -> do -- check for an error even when we don't have -- the full sequence yet (#3341) c1 <- readWord8Buf iraw (ir+1) if not (validate3 c0 c1 0x80) then invalid else done ir ow _ -> do c1 <- readWord8Buf iraw (ir+1) c2 <- readWord8Buf iraw (ir+2) if not (validate3 c0 c1 c2) then invalid else do ow' <- writeCharBuf oraw ow (chr3 c0 c1 c2) loop (ir+3) ow' | c0 >= 0xf0 -> case iw - ir of 1 -> done ir ow 2 -> do -- check for an error even when we don't have -- the full sequence yet (#3341) c1 <- readWord8Buf iraw (ir+1) if not (validate4 c0 c1 0x80 0x80) then invalid else done ir ow 3 -> do c1 <- readWord8Buf iraw (ir+1) c2 <- readWord8Buf iraw (ir+2) if not (validate4 c0 c1 c2 0x80) then invalid else done ir ow _ -> do c1 <- readWord8Buf iraw (ir+1) c2 <- readWord8Buf iraw (ir+2) c3 <- readWord8Buf iraw (ir+3) if not (validate4 c0 c1 c2 c3) then invalid else do ow' <- writeCharBuf oraw ow (chr4 c0 c1 c2 c3) loop (ir+4) ow' | otherwise -> invalid where invalid = if ir > ir0 then done ir ow else ioe_decodingError -- lambda-lifted, to avoid thunks being built in the inner-loop: done !ir !ow = return (if ir == iw then input{ bufL=0, bufR=0 } else input{ bufL=ir }, output{ bufR=ow }) in loop ir0 ow0 ioe_decodingError :: IO a ioe_decodingError = ioException (IOError Nothing InvalidArgument "utf8_decode" "invalid UTF-8 byte sequence" Nothing Nothing) utf8_encode :: EncodeBuffer utf8_encode input@Buffer{ bufRaw=iraw, bufL=ir0, bufR=iw, bufSize=_ } output@Buffer{ bufRaw=oraw, bufL=_, bufR=ow0, bufSize=os } = let done !ir !ow = return (if ir == iw then input{ bufL=0, bufR=0 } else input{ bufL=ir }, output{ bufR=ow }) loop !ir !ow | ow >= os || ir >= iw = done ir ow | otherwise = do (c,ir') <- readCharBuf iraw ir case ord c of x | x <= 0x7F -> do writeWord8Buf oraw ow (fromIntegral x) loop ir' (ow+1) | x <= 0x07FF -> if os - ow < 2 then done ir ow else do let (c1,c2) = ord2 c writeWord8Buf oraw ow c1 writeWord8Buf oraw (ow+1) c2 loop ir' (ow+2) | x <= 0xFFFF -> do if os - ow < 3 then done ir ow else do let (c1,c2,c3) = ord3 c writeWord8Buf oraw ow c1 writeWord8Buf oraw (ow+1) c2 writeWord8Buf oraw (ow+2) c3 loop ir' (ow+3) | otherwise -> do if os - ow < 4 then done ir ow else do let (c1,c2,c3,c4) = ord4 c writeWord8Buf oraw ow c1 writeWord8Buf oraw (ow+1) c2 writeWord8Buf oraw (ow+2) c3 writeWord8Buf oraw (ow+3) c4 loop ir' (ow+4) in loop ir0 ow0 -- ----------------------------------------------------------------------------- -- UTF-8 primitives, lifted from Data.Text.Fusion.Utf8 ord2 :: Char -> (Word8,Word8) ord2 c = assert (n >= 0x80 && n <= 0x07ff) (x1,x2) where n = ord c x1 = fromIntegral $ (n `shiftR` 6) + 0xC0 x2 = fromIntegral $ (n .&. 0x3F) + 0x80 ord3 :: Char -> (Word8,Word8,Word8) ord3 c = assert (n >= 0x0800 && n <= 0xffff) (x1,x2,x3) where n = ord c x1 = fromIntegral $ (n `shiftR` 12) + 0xE0 x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x3 = fromIntegral $ (n .&. 0x3F) + 0x80 ord4 :: Char -> (Word8,Word8,Word8,Word8) ord4 c = assert (n >= 0x10000) (x1,x2,x3,x4) where n = ord c x1 = fromIntegral $ (n `shiftR` 18) + 0xF0 x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80 x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80 x4 = fromIntegral $ (n .&. 0x3F) + 0x80 chr2 :: Word8 -> Word8 -> Char chr2 (W8# x1#) (W8# x2#) = C# (chr# (z1# +# z2#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6# !z2# = y2# -# 0x80# {-# INLINE chr2 #-} chr3 :: Word8 -> Word8 -> Word8 -> Char chr3 (W8# x1#) (W8# x2#) (W8# x3#) = C# (chr# (z1# +# z2# +# z3#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 6# !z3# = y3# -# 0x80# {-# INLINE chr3 #-} chr4 :: Word8 -> Word8 -> Word8 -> Word8 -> Char chr4 (W8# x1#) (W8# x2#) (W8# x3#) (W8# x4#) = C# (chr# (z1# +# z2# +# z3# +# z4#)) where !y1# = word2Int# x1# !y2# = word2Int# x2# !y3# = word2Int# x3# !y4# = word2Int# x4# !z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18# !z2# = uncheckedIShiftL# (y2# -# 0x80#) 12# !z3# = uncheckedIShiftL# (y3# -# 0x80#) 6# !z4# = y4# -# 0x80# {-# INLINE chr4 #-} between :: Word8 -- ^ byte to check -> Word8 -- ^ lower bound -> Word8 -- ^ upper bound -> Bool between x y z = x >= y && x <= z {-# INLINE between #-} validate3 :: Word8 -> Word8 -> Word8 -> Bool {-# INLINE validate3 #-} validate3 x1 x2 x3 = validate3_1 || validate3_2 || validate3_3 || validate3_4 where validate3_1 = (x1 == 0xE0) && between x2 0xA0 0xBF && between x3 0x80 0xBF validate3_2 = between x1 0xE1 0xEC && between x2 0x80 0xBF && between x3 0x80 0xBF validate3_3 = x1 == 0xED && between x2 0x80 0x9F && between x3 0x80 0xBF validate3_4 = between x1 0xEE 0xEF && between x2 0x80 0xBF && between x3 0x80 0xBF validate4 :: Word8 -> Word8 -> Word8 -> Word8 -> Bool {-# INLINE validate4 #-} validate4 x1 x2 x3 x4 = validate4_1 || validate4_2 || validate4_3 where validate4_1 = x1 == 0xF0 && between x2 0x90 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_2 = between x1 0xF1 0xF3 && between x2 0x80 0xBF && between x3 0x80 0xBF && between x4 0x80 0xBF validate4_3 = x1 == 0xF4 && between x2 0x80 0x8F && between x3 0x80 0xBF && between x4 0x80 0xBF
__label__pos
0.979233
Spotting Internet Scams in India 0 0 0 Guidebook Trust Security With internet usage so widespread, it's essential to ensure online safety. Scammers are becoming more sophisticated in their methods, including the misuse of AI. This guide aims to provide you with the knowledge to recognise and avoid common online scams such as phishing emails, deceptive ads, and untrustworthy websites. Phishing Emails Phishing emails are designed to look like they're from a legitimate company, but they're actually from scammers trying to trick you into giving them your personal information. Here's how to spot them: • Check the Email Address: If the email address doesn't match the company's official email or looks suspicious, it's likely a scam. • Spelling and Grammar Mistakes: Legitimate companies usually have professional editors to ensure their emails are error-free. If an email is full of mistakes, be wary. • Urgent Action Requests: Phishing emails often create a sense of urgency, like "Your account will be closed if you don't respond immediately." Legitimate companies usually don't pressure you like this. Deceptive Ads Online advertisements can sometimes be misleading. Here’s how to recognise potentially deceptive ones: • Unbelievable Offers: If an advertisement promises something that seems too good to be true, like an expensive gadget at a very low price, it’s likely not genuine. • Urgency Tactics: Watch out for advertisements that urge you to act immediately, such as "Limited time offer!" • Verify the URL: Move your cursor over the advertisement to preview the URL. If it doesn’t look like the official site of the advertised product or service, think twice before clicking. Suspicious Websites The internet is full of various websites, and not all are trustworthy. Here’s how to identify less reliable ones: • Secure Connection: Trustworthy websites often have a secure connection, shown by ‘https’ in the URL. If a website starts with ‘http,’ it might not be secure. • Contact Information: Reliable websites typically provide clear ways to contact the business. A lack of contact information is a warning sign. • Website Quality: Genuine businesses usually have well-designed websites. If you encounter a site with poor design or numerous errors, proceed with caution. Scamming with AI Thankfully, there are signs you can look for to spot AI-powered scams: Text and Audio • Unnatural language: Pay attention to unnatural phrasing, repetitive sentences, or awkward grammar. These are common signs of AI-generated text. • Lack of emotion: AI voices may sound realistic, but they often lack subtle emotional nuances present in human speech. Be wary of voices that sound flat or monotone. • Inconsistent information: Listen for contradictions or information that doesn't quite make sense, especially if the same AI voice appears in multiple places. Images and Videos • Unrealistic details: Look for inconsistencies in images, like blurry backgrounds, strange shadows, or unnatural skin textures. Deepfakes, which manipulate real videos, might flicker or have inconsistent lighting. • Lip-syncing issues: Watch for mismatched lip movements or delays between the audio and visuals. This can be a sign of a manipulated video. • Reverse image search: If you're unsure about an image or video, use a reverse image search to see if it appears elsewhere online. General Tips • Urgency: Scammers often use urgency to create pressure and cloud your judgement. Don't rush into decisions based on urgent messages or threats. • Verify Identities: Don't trust unknown senders, always be cautious with messages claiming to be from official sources. Verify contact information independently. • Unrealistic Offers: If something seems too good to be true, it probably is. Be sceptical of unrealistic investment opportunities or prizes. • Suspicious Links: Never click on links or open attachments from unknown senders. • Strong Passwords with 2FA: Protect your accounts with strong passwords and enable multi-factor authentication whenever possible. Being hacked can have serious consequences. For instance, scammers can steal your identity, empty your bank accounts, or even take over your social media accounts and send misleading messages to your friends and family. Remember, even humans can be fooled by sophisticated AI scams. Stay vigilant, think critically, and don't hesitate to research before engaging with anything suspicious.  Remember, when it comes to online safety, it's better to be safe than sorry. If something feels off, trust your gut and always keep your antivirus software and apps updated to add an extra layer of protection.  Staying safe online in the age of scams: Watch out for phishing emails, dodgy ads, and sketchy websites. Protect yourself with easy rules and some common sense. Sponsored Article More Security Articles Trust / Security / Choosing a Secure and Memorable Password Trust / Security / Guide to Securing Your Online Accounts
__label__pos
0.668864
cdstoolbox.cube.sum cdstoolbox.cube.sum(data: data object, dim: Union[Sequence[str], str] = None, keep_attrs: bool = True, **kwargs) → data object[source] Reduce input data by applying sum along the specified dimension(s). Attributes are preserved by default. Parameters • data (data object) – Data to be summed along the given dim. • dim (str or sequence of str, optional) – Dimension(s) over which to apply sum(). If None (default), then ‘sum’ is calculated over all dimensions. • keep_attrs (bool, optional) – If True (default), the attributes are copied from the original object to the new one. If False, the new object is returned without attributes. • **kwargs (dict) – Additional keyword argument passed to sum() xarray.DataArray.sum. Returns Sum of data along the specified dimensions and with the indicated dimension(s) removed. Return type data object Examples Calculate ‘sum’ along all dimensions: >>> sum = ct.cube.sum(data) Calculate ‘sum’ along specified dimension, e.g. ‘time’: >>> sum = ct.cube.sum(data, dim='time')
__label__pos
0.98338
Tamas Mission Specialist Mission Specialist • 12.4K Views AD user not known for client via one way trust (via IdM) Jump to solution Hello. I set up an AD & IdM test environment. The AD called winad.lab.infra; I have a one way trust between ipa.it.lab.infra & winad.lab.infra.. I have a test001 user on AD. I have a client machine called client7.it.lab.infra & a user in IdM called ipauser001. I can kinit on the client7 for [email protected] BUT I cannot do ssh to client7.it.lab.infra with the [email protected].. This is what I get from secure log: May 21 16:20:33 client7 sshd[3560]: Invalid user [email protected] from 192.168.122.1 port 33862 May 21 16:20:33 client7 sshd[3560]: input_userauth_request: invalid user [email protected] [preauth] May 21 16:20:33 client7 sshd[3560]: Postponed keyboard-interactive for invalid user [email protected] from 192.168.122.1 port 33862 ssh2 [preauth] May 21 16:20:45 client7 sshd[3562]: pam_unix(sshd:auth): check pass; user unknown May 21 16:20:45 client7 sshd[3562]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=gateway This is how my krb5.conf looks like on krb5.conf includedir /etc/krb5.conf.d/ includedir /var/lib/sss/pubconf/krb5.include.d/ [libdefaults] default_realm = LAB.INFRA dns_lookup_realm = false dns_lookup_kdc = false rdns = false dns_canonicalize_hostname = false ticket_lifetime = 24h forwardable = true udp_preference_limit = 0 default_ccache_name = KEYRING:persistent:%{uid} [realms] IT.LAB.INFRA = { pkinit_anchors = FILE:/var/lib/ipa-client/pki/kdc-ca-bundle.pem pkinit_pool = FILE:/var/lib/ipa-client/pki/ca-bundle.pem kdc = ipa.it.lab.infra admin_server = ipa.it.lab.infra } LAB.INFRA = { kdc = winad.lab.infra admin_server = winad.lab.infra default_domain = lab.infra } [domain_realm] client7.it.lab.infra = IPA.IT.LAB.INFRA it.lab.infra = IT.LAB.INFRA .it.lab.infra = IT.LAB.INFRA lab.infra = LAB.INFRA .lab.infra = LAB.INFRA I also enabled Kerberos authentication via authconfig-tui, kdc & admin server is pointing to the IdM server, the REALM is IT.LAB.INFRA.. The reason I set this because IPA shows that the trust exist between the two entity. Could you please pin-point me what did I do brutally wrong & why my AD user is an unknown user for the IdM client machine? Thanks in advance. Tamas 0 Kudos 1 Solution Accepted Solutions Tamas Mission Specialist Mission Specialist • 12.3K Views The issue was that in AD there were no uid, gid possix accounts assigned manually. I can't even add to the external users without having UID/GID in AD user properties.. Weird. Is this something expected? I try also make it work in Windows Server 2019 where the IDM extension is deprecated & in advanced view I had to edit attribute for the test user.. This is me building stuff from scratch (and learn the hard way)... View solution in original post 0 Kudos 3 Replies PeterTselios Starfighter Starfighter Starfighter • 12.4K Views Why are you manually change the configuration files?  Don't you use ipa-client? If so, ipa-client configures everything for you.  In any case, the reason could be anything. From timeouts to misconfigured SSSD. What I would recommend is to check the following:  1. Check if the id <username>@ad works 2. Check the getent password <username>@ad If those two are not working:  1. Clear SSSD cache and check again 2. If again is not working , enable debug logs in SSSD and check for the authentication attempt 3. Uninstall ipa-client and install it again.    0 Kudos Tamas Mission Specialist Mission Specialist • 12.4K Views hello, thanks for your answer. I tried what you said & still doens't work. Nothing in SSSD logs even after turning debug mode on but I saw in secure logs: error: PAM: User not known to the underlying authentication module for illegal user [email protected] from gateway Do I need to tune manually the pam config files? My LDAP does work with the IPA users but not the Kerberos cross-realm / AD part.. [root@client7 ~]# getent passwd ipauser001 ipauser001:*:866000004:866000004:Ipa User:/home/ipauser001:/bin/sh [root@client7 ~]# id ipauser001 uid=866000004(ipauser001) gid=866000004(ipauser001) groups=866000004(ipauser001) Thanks for your reply. 0 Kudos Tamas Mission Specialist Mission Specialist • 12.3K Views The issue was that in AD there were no uid, gid possix accounts assigned manually. I can't even add to the external users without having UID/GID in AD user properties.. Weird. Is this something expected? I try also make it work in Windows Server 2019 where the IDM extension is deprecated & in advanced view I had to edit attribute for the test user.. This is me building stuff from scratch (and learn the hard way)... 0 Kudos Join the discussion You must log in to join this conversation.
__label__pos
0.644715
USB Flash Drive - format to FAT, FAT32 or NTFS? Discussion in 'Accessories' started by anteis24, Nov 5, 2007. Thread Status: Not open for further replies. 1. anteis24 anteis24 Notebook Enthusiast Reputations: 21 Messages: 36 Likes Received: 0 Trophy Points: 15 Which format is recommended? Are there any advantages to one over another? I just purchased a Sandisk cruzer micro 2GB USB 2.0 flash drive.   2. scooberdoober scooberdoober Penguins FTW! Reputations: 1,716 Messages: 2,211 Likes Received: 0 Trophy Points: 55 I recommend FAT16 for a 2GB drive. This should give the best overall performance and most efficient usage of available space.   3. yuio yuio NBR Assistive Tec. Tec. Reputations: 634 Messages: 3,637 Likes Received: 0 Trophy Points: 105 I recommend just FAT, do not use NTFS, heard bad things...   4. swarmer swarmer beep beep Reputations: 2,071 Messages: 5,234 Likes Received: 0 Trophy Points: 205 It depends on your needs. If compatibility between different OSes is important, use FAT32. Pretty much everything can read and write to it: Windows, Linux, Mac OS X. If it's just Windows XP and/or Vista, you may want to use NTFS. It's more sophisticated and keeps track of owner and group, and file permissions, etc. (Other OSes can often read NTFS volumes, but usually can't write to them.) But if it's just a bunch of media files or something and you don't care about permissions, then I'd use FAT32. Here's a decent summary of the advantages of NTFS: http://www.theeldergeek.com/ntfs_or_fat32_file_system.htm Other than compatibility, and advantage of FAT32 is simplicity. Without any file permissions, there's no chance that you could inadvertently deny yourself permission to access a file. The ownership/permissions thing could maybe complicate things when connecting the drive to a different computer (with a different user account) -- although I don't really know how that works in any detail.   5. lokster lokster Notebook Deity Reputations: 63 Messages: 1,046 Likes Received: 0 Trophy Points: 55 No no no. ONLY USE FAT. fat32 and ntfs MAKES your USB drive much smaller. once you format into fat32 or ntfs whichever higher you cannot format down. ONLY USE FAT!   6. Metamorphical Metamorphical The Random Mod Super Moderator Reputations: 2,613 Messages: 2,190 Likes Received: 2 Trophy Points: 56 Always use Fat23. You will never see the full size on a flashdrive no matter what because even they have firmware which takes up a tiny portion of the drive.   7. scooberdoober scooberdoober Penguins FTW! Reputations: 1,716 Messages: 2,211 Likes Received: 0 Trophy Points: 55 Fat 23 huh? Must be some new tech I've never heard of before! :p   8. times times Notebook Evangelist Reputations: 0 Messages: 316 Likes Received: 0 Trophy Points: 30 ive been using ntfs.owell lol   9. scooberdoober scooberdoober Penguins FTW! Reputations: 1,716 Messages: 2,211 Likes Received: 0 Trophy Points: 55 Just transfer your files to your HD, reformat your flash drive, and then return the files, no big deal.   10. KnightUnit KnightUnit Notebook Evangelist Reputations: 42 Messages: 497 Likes Received: 0 Trophy Points: 30 Really, not with all that reading :p   Similar Threads: Flash Drive Forum Title Date Accessories Only 49 MB of 16GB USB 3.0 Flash Drive Being Detected May 25, 2014 Accessories Super Fast, Metal USB 3.0 Flash Drive Mar 27, 2014 Accessories USB 3.0 Flashdrive Feb 25, 2014 Accessories High quality USB 3.0 flash drive? Nov 24, 2013 Accessories Kingston HyperX Predator 1TB Flash Drive Sep 8, 2013 Thread Status: Not open for further replies. Share This Page
__label__pos
0.977361
Malicious Race Conditions and Data Races Contents[Show] This post is about malicious race conditions and data races. Malicious race conditions are race conditions that cause the breaking of invariants, blocking issues of threads, or lifetime issues of variables.  At first, let me remind you, what a race condition is.  • Race condition: A race condition is a situation, in which the result of an operation depends on the interleaving of certain individual operations. That's fine as starting point. A race condition can break the invariant of a program. Breaking of invariants In the last post Race Conditions and Data Races, I use the transfer of money between two accounts to show a data race. There was a benign race condition involved. To be honest, there was also a malicious race condition. The malicious race condition breaks an invariant of the program. The invariant is, that the sum of all balances should always have the same amount. Which is in our case is 200 because each account starts with 100 (1). For simplicity reason, the unit should be euro. Neither I want to create money by transferring it nor I want to destroy it. // breakingInvariant.cpp #include <atomic> #include <functional> #include <iostream> #include <thread> struct Account{ std::atomic<int> balance{100}; // 1 }; void transferMoney(int amount, Account& from, Account& to){ using namespace std::chrono_literals; if (from.balance >= amount){ from.balance -= amount; std::this_thread::sleep_for(1ns); // 2 to.balance += amount; } } void printSum(Account& a1, Account& a2){ std::cout << (a1.balance + a2.balance) << std::endl; // 3 } int main(){ std::cout << std::endl; Account acc1; Account acc2; std::cout << "Initial sum: "; printSum(acc1, acc2); // 4 std::thread thr1(transferMoney, 5, std::ref(acc1), std::ref(acc2)); std::thread thr2(transferMoney, 13, std::ref(acc2), std::ref(acc1)); std::cout << "Intermediate sum: "; std::thread thr3(printSum, std::ref(acc1), std::ref(acc2)); // 5 thr1.join(); thr2.join(); thr3.join(); // 6 std::cout << " acc1.balance: " << acc1.balance << std::endl; std::cout << " acc2.balance: " << acc2.balance << std::endl; std::cout << "Final sum: "; printSum(acc1, acc2); // 8 std::cout << std::endl; }   At the begin, the sum of the accounts is 200 euro. (4) display the sum by using the function printSum (3). Line (5) makes the invariant visible. Because there is a short sleep of 1ns in line (2), the intermediate sum is 182 euro. At the end, all is fine. Each account has the right balance (6) and the sum is 200 euro (8). Here is the output of the program. breakingInvariant The malicious story goes on. Let's create a deadlock by using conditions variables without a predicate. Blocking issues with race conditions Only to make my point clear. You have to use a condition variable in combination with a predicate. For the details read my post Condition Variables. If not, your program may become the victim of a spurious wakeup or lost wakeup. If you use a condition variable without a predicate, it may happen that the notifying thread sends it notification before the waiting thread is in the waiting state. Therefore, the waiting thread waits forever. That phenomenon is called a lost wakeup. Here is the program. // conditionVariableBlock.cpp #include <iostream> #include <condition_variable> #include <mutex> #include <thread> std::mutex mutex_; std::condition_variable condVar; bool dataReady; void waitingForWork(){ std::cout << "Worker: Waiting for work." << std::endl; std::unique_lock<std::mutex> lck(mutex_); condVar.wait(lck); // 3 // do the work std::cout << "Work done." << std::endl; } void setDataReady(){ std::cout << "Sender: Data is ready." << std::endl; condVar.notify_one(); // 1 } int main(){ std::cout << std::endl; std::thread t1(setDataReady); std::thread t2(waitingForWork); // 2 t1.join(); t2.join(); std::cout << std::endl; }   The first invocations of the program work fine. The second invocation locks because the notify call (1) happens before the thread t2 (2) is in the waiting state (3).   conditionVariableBlock Of course, deadlocks and livelocks are other effects of race conditions. A deadlock depends in general on the interleaving of the threads and my sometimes happen or not. A livelock is similar to a deadlock. While a deadlock blocks, I livelock seems to make progress. The emphasis lies on seems. Think about a transaction in a transactional memory use case. Each time the transaction should be committed, a conflict happens. Therefore a rollback takes place. Here is my post about Transactional Memory. Showing lifetime issues of variables is not so challenging. Lifetime issues of variables The recipe of a lifetime issue is quite simple. Let the created thread run in the background and you are half done. That means the creator thread will not wait until its child is done. In this case, you have to be extremely careful that the child is not using something belonging to the creator.   // lifetimeIssues.cpp #include <iostream> #include <string> #include <thread> int main(){ std::cout << "Begin:" << std::endl; // 2 std::string mess{"Child thread"}; std::thread t([&mess]{ std::cout << mess << std::endl;}); t.detach(); // 1 std::cout << "End:" << std::endl; // 3 }   This is too simple. The thread t is using std::cout and the variable mess. Both belong to the main thread. The effect is that we don't see the output of the child thread in the second run. Only "Begin:" (2) and "End:" (3) are displayed.  lifetimeIssues2 I want to emphasise it very explicitly. All the programs in this post are up to this point without a data race. You know is was my idea to write about race conditions and data races. They are a related, but different concept. I can even create a data race without a race condition. A data race without a race condition But first, let me remind you, what a data race is. • Data race: A data race is a situation, in which at least two threads access a shared variable at the same time. At least on thread tries to modify the variable.   // addMoney.cpp #include <functional> #include <iostream> #include <thread> #include <vector> struct Account{ int balance{100}; // 1 }; void addMoney(Account& to, int amount){ to.balance += amount; // 2 } int main(){ std::cout << std::endl; Account account; std::vector<std::thread> vecThreads(100); // 3 for (auto& thr: vecThreads) thr = std::thread( addMoney, std::ref(account), 50); for (auto& thr: vecThreads) thr.join(); // 4 std::cout << "account.balance: " << account.balance << std::endl; std::cout << std::endl; }   100 threads are adding 50 euro (3) to the same account (1). They use the function addMoney. The key observation is, that the writing to the account is done without synchronisation. Therefore we have a data race and no valid result. That is undefined behaviour and the final balance (4) differs between 5000 and 5100 euro.   addMoney What's next? I often hear at concurrency conference discussions about the terms non-blocking, lock-free, and wait-free. So let me write about these terms in my next post. Add comment Subscribe to the newsletter (+ pdf bundle) Blog archive Source Code Visitors Today 2703 All 1509304 Currently are 187 guests and no members online Kubik-Rubik Joomla! Extensions Latest comments
__label__pos
0.613095
How to loop through a map in golang? Member by emely , in category: Golang , 2 years ago How to loop through a map in golang? Facebook Twitter LinkedIn Telegram Whatsapp 2 answers by dmitrypro77 , 2 years ago @emely you can use for loop to iterate over any map in Golang, the code would be something like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 package main import ( "fmt" ) func main() { mapExample := map[int]string{0: "john", 1: "steven"} // Output: map: map[0:john 1:steven] fmt.Println("map:", mapExample) for key, value := range mapExample { fmt.Println("key:", key, "value:", value) } // Output: //key: 0 value: john //key: 1 value: steven } Member by anthony , a year ago @emely  To loop through a map in Golang, you can use a for loop with the range keyword. Here's an example: 1 2 3 4 5 m := map[string]int{"apple": 1, "banana": 2, "orange": 3} for key, value := range m { fmt.Println(key, value) } This code will output: 1 2 3 apple 1 banana 2 orange 3 The range keyword returns both the key and the value of each pair in the map. You can use these variables in your loop to perform any calculations necessary.
__label__pos
0.999663
The DirectoryIterator class (PHP 5, PHP 7, PHP 8) Introduction The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories. Class synopsis class DirectoryIterator extends SplFileInfo implements SeekableIterator { /* Methods */ public __construct(string $directory) public current(): mixed public getATime(): int public getBasename(string $suffix = ""): string public getCTime(): int public getExtension(): string public getFilename(): string public getGroup(): int public getInode(): int public getMTime(): int public getOwner(): int public getPath(): string public getPathname(): string public getPerms(): int public getSize(): int public getType(): string public isDir(): bool public isDot(): bool public isExecutable(): bool public isFile(): bool public isLink(): bool public isReadable(): bool public isWritable(): bool public key(): mixed public next(): void public rewind(): void public seek(int $offset): void public __toString(): string public valid(): bool /* Inherited methods */ public SplFileInfo::getATime(): int|false public SplFileInfo::getBasename(string $suffix = ""): string public SplFileInfo::getCTime(): int|false public SplFileInfo::getExtension(): string public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo public SplFileInfo::getFilename(): string public SplFileInfo::getGroup(): int|false public SplFileInfo::getInode(): int|false public SplFileInfo::getLinkTarget(): string|false public SplFileInfo::getMTime(): int|false public SplFileInfo::getOwner(): int|false public SplFileInfo::getPath(): string public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo public SplFileInfo::getPathname(): string public SplFileInfo::getPerms(): int|false public SplFileInfo::getRealPath(): string|false public SplFileInfo::getSize(): int|false public SplFileInfo::getType(): string|false public SplFileInfo::isDir(): bool public SplFileInfo::isFile(): bool public SplFileInfo::isLink(): bool public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject public SplFileInfo::setFileClass(string $class = SplFileObject::class): void public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void public SplFileInfo::__toString(): string } Table of Contents add a note User Contributed Notes 8 notes up 56 krystianmularczyk at gmail dot com 14 years ago Shows us all files and catalogues in directory except "." and "..". <?php foreach (new DirectoryIterator('../moodle') as $fileInfo) {     if( $fileInfo->isDot()) continue;     echo $fileInfo->getFilename() . "<br>\n"; } ?> up 3 alvaro at demogracia dot com 5 years ago DirectoryIterator is just an lightweight SplFileInfo iterator and its methods operate on whatever item the internal cursor points to. In other words: <?php $iterator = new DirectoryIterator('C:\\'); echo $iterator->getPathname(); ?> ... will NOT print "C:\" but the path of the first file or subdirectory retrieved, e.g. "C:\$Recycle.Bin". up 10 rogier at dsone dot nl 10 years ago Beware of the behavior when using FilesystemIterator::UNIX_PATHS, it's not applied as you might expect. I guess this flag is added especially for use on windows. However, the path you construct the RecursiveDirectoryIterator or FilesystemIterator with will not be available as a unix path. I can't say this is a bug, since most methods are just purely inherited from DirectoryIterator. In my test, I'd expected a complete unix path. Unfortunately... not quite as expected: <?php          // say $folder = C:\projects\lang         $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;         $d_iterator = new RecursiveDirectoryIterator($folder, $flags);         echo $d_iterator->getPath(); ?> expected result: /projects/lang (or C:/projects/lang) actual result: C:\projects\lang up 5 David Lanstein 14 years ago DirectoryIterator::getBasename() has been also been available since 5.2.2, according to the changelog (not documented yet).  It takes a parameter $suffix, and is useful if, for instance, you use a naming convention for your files (e.g. ClassName.php).  The following code uses this to add recursively All*Tests.php in any subdirectory off of tests/, basically, suites of suites. <?php // PHPUnit boilerplate code goes here class AllTests {     public static function main() {         $parameters = array('verbose' => true);         PHPUnit_TextUI_TestRunner::run(self::suite(), $parameters);     }     public static function suite() {         $suite = new PHPUnit_Framework_TestSuite('AllMyTests'); // this must be something different than the class name, per PHPUnit         $it = new AllTestsFilterIterator(                   new RecursiveIteratorIterator(                       new RecursiveDirectoryIterator(dirname(__FILE__) . '/tests')));         for ( $it->rewind(); $it->valid(); $it->next()) {             require_once( $it->current());             $className = $it->current()->getBasename('.php');             $suite->addTest($className::suite());         }         return $suite;     } } ?> Also, the AllTestsFilterIterator above extends FilterIterator, and contains one method, accept(): <?php class AllTestsFilterIterator extends FilterIterator {     public function accept() {         if ( preg_match('/All.*Tests\.php/', $this->current())) {             return true;         } else {             return false;         }     } } ?> up -6 Mark van Straten 14 years ago Implements Iterator so you can foreach() over the content of the given directory up -5 Kunal Bhatia->kmasterzone@gmail dot com 11 years ago Deleting all files in a directory except the one which is last modified. <?php     $directory = dirname(__FILE__)."/demo";     $filenames = array();     $iterator = new DirectoryIterator($directory);     foreach ( $iterator as $fileinfo) {         if ( $fileinfo->isFile()) {             $filenames[$fileinfo->getMTime()] = $fileinfo->getFilename();         }     }     ksort($filenames);     print_r($filenames);     echo "\n";     $i=0;     if( sizeof($filenames)>1){         foreach ( $filenames as $file){             if( $i>0){                 echo $file."\n";                 unlink($directory."/".$file);             }             $i++;         }     } ?> up -7 abdel at elghafoud dot com 8 years ago Shows us recursively all files and catalogues in directory except "." and "..". <?php /** * @param string $directory * @param array $files * @return array */ public function recursiveDirectoryIterator ($directory = null, $files = array()) {     $iterator = new \DirectoryIterator ( $directory );     foreach ( $iterator as $info ) {         if ( $info->isFile ()) {             $files [$info->__toString ()] = $info;         } elseif (! $info->isDot ()) {             $list = array($info->__toString () => $this->recursiveDirectoryIterator(                         $directory.DIRECTORY_SEPARATOR.$info->__toString ()             ));             if(!empty( $files))                 $files = array_merge_recursive($files, $filest);             else {                 $files = $list;             }         }     }     return $files; } ?> up -11 incredimike 4 years ago For some reason, the `isDot()` method doesn't return positive for the `.DS_Store` file generated by Mac OS's Finder. In practice, I've had to write code to explicitly check for this file: <?php foreach (new DirectoryIterator('../moodle') as $fileInfo) {     if( $fileInfo->isDot() || $fileInfo->getBasename() === '.DS_Store') continue;     echo $fileInfo->getFilename() . "<br>\n"; } ?> To Top
__label__pos
0.539024
Advanced Poker Math: GTO Strategy and Game Theory Mastering GTO Poker Strategy Advanced Poker Math: GTO Strategy and Game Theory is a comprehensive guide that delves into the intricacies of poker mathematics, specifically focusing on the concept of Game Theory Optimal (GTO) strategy. This book provides an in-depth exploration of the mathematical principles and strategies that underpin successful poker play, offering valuable insights for both aspiring and experienced players. By understanding the fundamental concepts of GTO strategy and game theory, players can enhance their decision-making abilities, optimize their play, and ultimately improve their overall performance at the poker table. The Basics of Game Theory Optimal Strategy in Advanced Poker Math Game Theory Optimal (GTO) strategy is a concept that has gained significant popularity in the world of advanced poker math. It is a mathematical approach to decision-making that aims to find the most optimal strategy in a given situation. In this article, we will explore the basics of GTO strategy and its application in advanced poker math. To understand GTO strategy, it is essential to have a basic understanding of game theory. Game theory is a branch of mathematics that deals with the study of strategic decision-making. It provides a framework for analyzing and predicting the outcomes of competitive situations, such as poker games. In poker, GTO strategy refers to a strategy that cannot be exploited by an opponent, regardless of their actions. It is a strategy that ensures a player’s long-term profitability, even against skilled opponents. The goal of GTO strategy is to find a balanced range of actions that maximizes expected value while minimizing the opponent’s ability to exploit weaknesses. To implement GTO strategy, players need to consider various factors, such as their hand strength, position at the table, stack sizes, and the actions of their opponents. They must also take into account the concept of range balancing, which involves choosing actions that make it difficult for opponents to determine the strength of their hand. One of the key principles of GTO strategy is the concept of frequency-based decision-making. Instead of always choosing the same action with a particular hand, players should vary their actions based on a predetermined frequency. For example, if a player decides to bet with a certain hand 60% of the time, they should also check or fold with that hand the remaining 40% of the time. This frequency-based approach makes it difficult for opponents to exploit predictable patterns in a player’s strategy. Another important aspect of GTO strategy is the concept of mixed strategies. A mixed strategy involves randomly choosing between different actions with a certain frequency. By using mixed strategies, players can introduce uncertainty into their decision-making process, making it even more challenging for opponents to exploit their strategy. Implementing GTO strategy requires a deep understanding of advanced poker math. Players need to be able to calculate the expected value of different actions and determine the optimal frequencies for each action. This involves complex mathematical calculations and simulations, which can be time-consuming and require advanced software tools. While GTO strategy is considered the gold standard in advanced poker math, it is important to note that it is not always the most profitable strategy in every situation. GTO strategy assumes that opponents are also playing optimally, which is often not the case in real-world poker games. In some situations, players may find it more profitable to deviate from GTO strategy and exploit specific weaknesses in their opponents’ strategies. In conclusion, GTO strategy is a powerful concept in advanced poker math that aims to find the most optimal strategy in a given situation. It is based on the principles of game theory and involves frequency-based decision-making and mixed strategies. While GTO strategy is not always the most profitable approach, it provides a solid foundation for players looking to improve their decision-making skills and maximize their long-term profitability in poker games. How to Apply GTO Strategy in Advanced Poker Math Advanced Poker Math: GTO Strategy and Game Theory Poker is a game of skill, strategy, and mathematics. While many players rely on their instincts and experience, advanced players understand the importance of incorporating game theory optimal (GTO) strategy into their gameplay. GTO strategy is a mathematical approach that aims to find the most balanced and unexploitable strategy in any given situation. In this article, we will explore how to apply GTO strategy in advanced poker math. To understand GTO strategy, it is crucial to have a solid foundation in poker mathematics. This includes understanding concepts such as pot odds, expected value, and equity. These mathematical principles help players make informed decisions based on the probability of winning a hand and the potential payoff. Once you have a good grasp of poker mathematics, you can start incorporating GTO strategy into your gameplay. The first step is to analyze the range of hands your opponents could have in a given situation. This requires observing their betting patterns, tendencies, and previous actions. By understanding their range, you can make more accurate decisions based on the likelihood of their hand strength. Next, you need to determine your own range of hands and how it interacts with your opponents’ ranges. This involves considering your position at the table, the strength of your hand, and the potential for future betting rounds. By analyzing these factors, you can make more informed decisions about whether to bet, raise, or fold. One of the key principles of GTO strategy is to maintain a balanced range of hands. This means that your betting and raising frequencies should be proportionate across different hand strengths. By doing so, you make it difficult for your opponents to exploit your strategy. For example, if you only bet when you have a strong hand, observant opponents will quickly catch on and adjust their play accordingly. Another important aspect of GTO strategy is understanding the concept of bluffing. Bluffing is a crucial tool in poker, but it must be used strategically and sparingly. GTO strategy suggests bluffing with a balanced range of hands to prevent opponents from easily identifying your bluffs. By incorporating bluffs into your gameplay, you can keep your opponents guessing and increase your profitability. In addition to analyzing hand ranges and maintaining balance, GTO strategy also involves considering the concept of game theory. Game theory is a mathematical framework that analyzes the interactions between players and their decision-making processes. By applying game theory principles, you can make decisions that maximize your expected value while minimizing your opponents’ potential gains. One of the fundamental concepts in game theory is the Nash equilibrium. The Nash equilibrium is a state in which no player can improve their expected value by unilaterally changing their strategy. By striving to play in a Nash equilibrium, you can ensure that your decisions are optimal and unexploitable. To apply GTO strategy effectively, it is essential to constantly analyze and adjust your gameplay. This requires reviewing hand histories, studying your opponents’ tendencies, and staying up to date with the latest poker strategies. By continuously refining your skills and incorporating GTO strategy, you can elevate your poker game to the next level. In conclusion, GTO strategy and game theory are essential components of advanced poker math. By understanding the principles of GTO strategy, analyzing hand ranges, maintaining balance, and applying game theory principles, you can make more informed and profitable decisions at the poker table. While GTO strategy may seem complex at first, with practice and dedication, you can become a formidable player who consistently makes optimal decisions. So, embrace the power of GTO strategy and take your poker game to new heights. Analyzing Game Theory Optimal Strategy in Advanced Poker Math Advanced Poker Math: GTO Strategy and Game Theory Analyzing Game Theory Optimal Strategy in Advanced Poker Math In the world of poker, understanding the underlying mathematics and strategies is crucial for success. One concept that has gained significant attention in recent years is Game Theory Optimal (GTO) strategy. GTO strategy is a mathematical approach to poker that aims to find the most balanced and unexploitable strategy in any given situation. By analyzing the game through the lens of game theory, players can make more informed decisions and maximize their long-term profitability. To understand GTO strategy, it is essential to grasp the basics of game theory. Game theory is a branch of mathematics that studies the strategic interactions between players in a game. It provides a framework for analyzing decision-making and predicting outcomes based on the actions of all players involved. In poker, game theory can be used to determine the optimal strategy in various situations, taking into account the range of possible actions and the potential responses of opponents. GTO strategy, as the name suggests, aims to find the optimal strategy that cannot be exploited by opponents. It seeks to strike a balance between aggression and passivity, ensuring that the player’s actions are not predictable or exploitable. By playing a GTO strategy, players can make it difficult for opponents to gain an edge and force them to make mistakes. To implement GTO strategy, players must first understand the concept of ranges. A range is a set of hands that a player can have in a particular situation. By assigning a range to each player, it becomes possible to calculate the expected value (EV) of each action. The EV represents the average outcome of a decision over the long run. By comparing the EVs of different actions, players can determine the most profitable move. One of the key principles of GTO strategy is the concept of balanced ranges. A balanced range is one that contains a mix of strong and weak hands, making it difficult for opponents to determine the player’s holdings. By balancing their ranges, players can prevent opponents from exploiting their tendencies and gain an edge in the game. Another important aspect of GTO strategy is the concept of frequency-based play. Instead of always using the same actions with the same hands, players should vary their decisions based on a predetermined frequency. For example, if a player decides to bluff 30% of the time in a particular situation, they should follow through with a bluff roughly 30% of the time. This frequency-based approach makes it difficult for opponents to exploit the player’s tendencies and keeps them guessing. While GTO strategy provides a solid foundation for decision-making, it is important to note that it is not the only approach to poker. In fact, many successful players deviate from GTO strategy in certain situations to exploit their opponents’ weaknesses. This is known as an exploitative strategy, where players adjust their play based on the specific tendencies and behaviors of their opponents. In conclusion, GTO strategy and game theory are essential components of advanced poker math. By analyzing the game through the lens of game theory, players can develop a balanced and unexploitable strategy that maximizes their long-term profitability. Understanding the concepts of ranges, expected value, balanced ranges, and frequency-based play is crucial for implementing GTO strategy effectively. However, it is important to remember that GTO strategy is not the only approach to poker, and players should also consider exploitative strategies to gain an edge over their opponents. Advanced Poker Math: Exploring the Relationship Between Game Theory and Optimal Strategy Advanced Poker Math: GTO Strategy and Game Theory Poker is a game of skill, strategy, and mathematics. While many players rely on their instincts and experience to make decisions at the table, understanding the underlying math can give you a significant edge. In this article, we will explore the relationship between game theory and optimal strategy in poker, specifically focusing on the concept of GTO (Game Theory Optimal) strategy. To understand GTO strategy, we must first delve into the world of game theory. Game theory is a branch of mathematics that studies strategic decision-making in competitive situations. It provides a framework for analyzing and predicting the outcomes of games, including poker. By applying game theory principles to poker, players can develop strategies that are theoretically unbeatable. GTO strategy is based on the idea of playing a balanced range of hands in every situation. It involves making decisions that are indifferent to the actions of your opponents. In other words, regardless of what your opponents do, you will always have a profitable response. This approach ensures that you are not exploitable and maximizes your long-term expected value. One of the key concepts in GTO strategy is the concept of range balancing. A range is the set of hands that a player can have in a particular situation. Balancing your range means having a mix of strong and weak hands in your betting and checking ranges. By doing so, you make it difficult for your opponents to determine the strength of your hand, making it harder for them to exploit you. Another important aspect of GTO strategy is understanding and exploiting imbalances in your opponents’ ranges. If you can accurately assess the range of hands your opponents are likely to have, you can adjust your strategy to exploit their weaknesses. For example, if you know that a player is too aggressive with their bluffs, you can call them down more often with marginal hands, knowing that they are likely to be bluffing. Implementing GTO strategy requires a deep understanding of poker math. This includes concepts such as pot odds, implied odds, and expected value. Pot odds refer to the ratio of the current size of the pot to the cost of a contemplated call. Implied odds take into account the potential future bets that can be won if a particular hand improves. Expected value is a measure of the average amount of money you can expect to win or lose in a particular situation. By combining these mathematical concepts with game theory principles, you can make more informed decisions at the poker table. However, it is important to note that GTO strategy is not always the most profitable strategy in every situation. In certain scenarios, exploiting your opponents’ weaknesses may be more profitable than playing a balanced range. This is where the concept of exploitative play comes into play. Exploitative play involves deviating from GTO strategy to take advantage of specific weaknesses in your opponents’ games. For example, if you notice that a player is folding too often to continuation bets, you can increase the frequency of your bluffs. Exploitative play requires a keen observation of your opponents’ tendencies and the ability to adjust your strategy accordingly. In conclusion, advanced poker math, specifically GTO strategy, is a powerful tool that can give you an edge at the poker table. By understanding the principles of game theory and implementing a balanced range of hands, you can make theoretically unbeatable decisions. However, it is important to remember that GTO strategy is not always the most profitable approach. Exploitative play, based on exploiting your opponents’ weaknesses, can be more profitable in certain situations. Ultimately, a combination of both GTO strategy and exploitative play is the key to success in poker.In conclusion, advanced poker math, GTO strategy, and game theory are essential components for players looking to improve their poker skills. By understanding the mathematical concepts behind the game and applying game theory principles, players can make more informed decisions and increase their chances of success at the poker table. These strategies help players analyze different scenarios, calculate probabilities, and optimize their overall gameplay. Incorporating advanced poker math and GTO strategy can give players a competitive edge and enhance their overall poker performance.
__label__pos
0.999562
About Version: WCAG 2.1+ Number: 2.2.6 Level: AAA Applicability: • Forms • Interactive Content Requirement: Users are warned of the duration of any user inactivity that could cause data loss, unless the data is preserved for more than 20 hours when the user does not take any actions. Guidance: Purpose The purpose of this success criterion is to ensure that users are aware how much time there is before a timeout will occur (i.e., their data is lost), as readers with cognitive disabilities, for example, may require additional time to read, understand and interact with the content. How to Meet The use of timeouts in digital publications is not common, as timeouts are usually included on the web as a security measure (i.e., to close a user's session in case they forgot to log out when they quit). If authors do include a timeout (e.g., in an embedded game or application), they need to ensure that users are aware before they begin interacting with the content how long they have before the timeout occurs. The length of time before a timeout could be provided in the instructions for a game, for example. In general, however, it is best to avoid timeouts unless there is a specific security concern. Additional Information The following knowledge base pages provide more information about how to address this success criterion for publishing content:
__label__pos
0.634022
Migration from Angular 2 Betas to RC On May 2nd Angular 2 moved from the beta stage to the release candidate stage and is currently on RC 1. The move from beta to RC was a bit more involved than the moves between beta. This post is going to cover the changes I went through to get my SPA sample application migrated to RC 1. Update package.json With this release Angular 2 was split from a single dependency in to multiple. The other big change is a rename of from angular2  to @angular. The following is my updated dependencies section. "dependencies": { "@angular/common": "2.0.0-rc.1", "@angular/compiler": "2.0.0-rc.1", "@angular/core": "2.0.0-rc.1", "@angular/http": "2.0.0-rc.1", "@angular/platform-browser": "2.0.0-rc.1", "@angular/platform-browser-dynamic": "2.0.0-rc.1", "@angular/router": "2.0.0-rc.1", "@angular/router-deprecated": "2.0.0-rc.1", "@angular/upgrade": "2.0.0-rc.1", "systemjs": "0.19.27", "es6-shim": "^0.35.0", "reflect-metadata": "^0.1.3", "rxjs": "5.0.0-beta.6", "zone.js": "^0.6.12" } After the above change make sure to run npm install in the root of the project from a command prompt. Not sure if it was just me, but the dependency auto restore in Visual Studio wouldn’t work for the @angular dependencies. Update gulpfile.js Due to the changes in the dependency structure my gulpfile had to be updated to copy the new files to the proper locations. I took the opportunity to move all of my dependency to a lib folder. gulp.task("angular2:moveLibs", function () { return gulp.src([ "node_modules/@angular/common/**/*", "node_modules/@angular/compiler/**/*", "node_modules/@angular/core/**/*", "node_modules/@angular/http/**/*", "node_modules/@angular/platform-browser/**/*", "node_modules/@angular/platform-browser-dynamic/**/*", "node_modules/@angular/router/**/*", "node_modules/@angular/router-deprecated/**/*", "node_modules/@angular/upgrade/**/*", "node_modules/systemjs/dist/system.src.js", "node_modules/systemjs/dist/system-polyfills.js", "node_modules/rxjs/**/*", "node_modules/es6-shim/es6-shim.min.js", "node_modules/zone.js/dist/zone.js", "node_modules/reflect-metadata/Reflect.js" ], { base: "node_modules" }) .pipe(gulp.dest(paths.webroot + "Angular/lib")); }); If you were using the previous version of my gulp take make sure to remove the old dependencies from the wwwroot/Angular/ folder. Update Entry Point View Again because of the dependency changes the entry point view for the Angular 2 application needed changes which is Angular2.cshtml in my project. A systemjs.config.js was added to handle the bulk of the configuration. The following is the full source for my entry point view. <html> <head> <title>Angular 2 QuickStart</title> <script src="~/Angular/lib/es6-shim/es6-shim.min.js"></script> <script src="~/Angular/lib/zone.js/dist/zone.js"></script> <script src="~/Angular/lib/reflect-metadata/Reflect.js"></script> <script src="~/Angular/lib/systemjs/dist/system.src.js"></script> <script src="~/Angular/app/systemjs.config.js"></script> <script> System.import('app').catch(function(err){ console.error(err); }); </script> </head> <body> <my-app>Loading...</my-app> </body> </html> Add system.config.js This new file is where the configuration of systemjs happens. I found this setup in Dan Wahlin’s Angular2-JumpStart project which can be found here. The only real changes I made from Dan’s file was to adjust the map section to match my folder layout. (function (global) { // map tells the System loader where to look for things var map = { 'app': '../Angular/app', 'rxjs': '../Angular/lib/rxjs', '@angular': '../Angular/lib/@angular' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'boot.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' } }; var packageNames = [ '@angular/common', '@angular/compiler', '@angular/core', '@angular/http', '@angular/platform-browser', '@angular/platform-browser-dynamic', '@angular/router', '@angular/router-deprecated', '@angular/testing', '@angular/upgrade' ]; // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } packageNames.forEach(function (pkgName) { packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; }); var config = { map: map, packages: packages } // filterSystemConfig - index.html's chance to modify config before we register it. if (global.filterSystemConfig) { global.filterSystemConfig(config); } System.config(config); })(this); Update Component Imports With the change in package names all imports that were using angular2 need to be changed to @angular. The following is an example of this from my app.component.ts file. Before: import {Component} from 'angular2/core'; import {OnInit} from 'angular2/core'; import {HTTP_PROVIDERS} from 'angular2/http'; After: import {Component} from '@angular/core'; import {OnInit} from '@angular/core'; import {HTTP_PROVIDERS} from '@angular/http'; NgFor Change There was also a slight syntax change around ngFor that changes the name declaration of the current item in the iteration of a loop. The following shows the before and after. Before: *ngFor="#contact of contacts" After: *ngFor="let contact of contacts" Complete With the above changes my application was run able again. The hardest part of the upgrade for me was getting systemjs configured properly. Hope your upgrade goes smooth and if not leave a comment with what issues you had. 4 Replies to “Migration from Angular 2 Betas to RC” 1. hiii, i am working in old angular2 rc1. my task is to convert it to new latest rc6. i am doing it manual. its so complicated to convert each component syntax to rc6 syntax.. is there any migration technique that convert all component together. if possible plzz suggest Leave a Reply Your email address will not be published. Required fields are marked * This site uses Akismet to reduce spam. Learn how your comment data is processed.
__label__pos
0.520376
Class InsertAllRequest.RowToInsert (2.13.4) public static class InsertAllRequest.RowToInsert implements Serializable A Google Big Query row to be inserted into a table. Each RowToInsert has an associated id used by BigQuery to detect duplicate insertion requests on a best-effort basis. To ensure proper serialization of numeric data, it is recommended to supply values using a string-typed representation. Additionally, data for fields of LegacySQLTypeName#BYTES must be provided as a base64 encoded string. Example usage of creating a row to insert: List<Long> repeatedFieldValue = Arrays.asList(1L, 2L); Map<String, Object> recordContent = new HashMap<String, Object>(); recordContent.put("subfieldName1", "value"); recordContent.put("subfieldName2", repeatedFieldValue); Map<String, Object> rowContent = new HashMap<String, Object>(); rowContent.put("booleanFieldName", true); rowContent.put("bytesFieldName", "DQ4KDQ=="); rowContent.put("recordFieldName", recordContent); rowContent.put("numericFieldName", "1298930929292.129593272"); RowToInsert row = new RowToInsert("rowId", rowContent); See Also: Data Consistency Inheritance Object > InsertAllRequest.RowToInsert Implements Serializable Static Methods of(String id, Map<String,?> content) public static InsertAllRequest.RowToInsert of(String id, Map<String,?> content) Creates a row to be inserted with associated id. To ensure proper serialization of numeric data, supply values using a string-typed representation. Additionally, data for fields of LegacySQLTypeName#BYTES must be provided as a base64 encoded string. Parameters NameDescription idString id of the row, used to identify duplicates contentMap<String,?> the actual content of the row Returns TypeDescription InsertAllRequest.RowToInsert of(Map<String,?> content) public static InsertAllRequest.RowToInsert of(Map<String,?> content) Creates a row to be inserted without associated id. To ensure proper serialization of numeric data, supply values using a string-typed representation. Additionally, data for fields of type LegacySQLTypeName#BYTES must be provided as a base64 encoded string. Parameter NameDescription contentMap<String,?> the actual content of the row Returns TypeDescription InsertAllRequest.RowToInsert Methods equals(Object obj) public boolean equals(Object obj) Parameter NameDescription objObject Returns TypeDescription boolean Overrides getContent() public Map<String,Object> getContent() Returns the actual content of the row, as a map. The returned map is always immutable. Its iteration order is unspecified. Returns TypeDescription Map<String,Object> getId() public String getId() Returns the id associated with the row. Returns null if not set. Returns TypeDescription String hashCode() public int hashCode() Returns TypeDescription int Overrides toString() public String toString() Returns TypeDescription String Overrides
__label__pos
0.879811
0 Hallo, I get stuck when installing SQL Server 2012 : Services Account Name Password SQL Server Agent SQL Server Database Enginee SQL Server Analysis Services SQL Server Browser This Sharepoint Server connected to DCSHARE1 (Domain Controller) The problem is I do not know what to fill for Account Name & Password Can anyone help me? Thanks before. 2 Contributors 3 Replies 20 Views 3 Years Discussion Span Last Post by davy_yg 0 First a little background...when the SQL Server services get installed, they have to have a security context that has sufficient permissions on the local server to do what it needs to do. Usually the person doing the installation has local administrator permissions on the server, but it is usually NOT recommended to use that login as the services account name...the permissions are too elevated and if the password gets out it could compromise the security of your data. In some cases, you can simply use the system-generated security context. This doesn't require a password to be entered, and is never actually used by a person to log in...it is only used by the SQL Server service. Some installations use a separately created "user" account on the local machine so they have the ability to elevate permissions depending on what the SQL Server is for. It also allows the administrator to rotate the password on a periodic basis. Some installations use a domain account so that multiple servers can use the same account for all their SQL Servers. It allows for simpler central management and administration of the entire SQL Server landscape. So, long story short, if you are asked for an Account Name and Password, you should either use the Local System Account setting, or you should set up a new account either on the local server or in the domain (named whatever you want to name it...hopefully something meaningful) and use that. Hope that helps you some! Good luck! 0 How to use the Local System Account setting, or you should set up a new account? 0 I finally figure this things out. I just have to connect to the DC by join domain. Then, use the username & password from the domain that I have set. This question has already been answered. Start a new discussion instead. Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.
__label__pos
0.672994
SCHOOL CLOSED? We have new content EVERY WEEKDAY. Check out our homepage. Computer Coding Computer Coding for kids Computer coding for kids in Primary School. Homework help with computers and computer coding languages in Key Stage 1 and Key Stage 2. Learn algorithms, simple programming and coding. What is a computer? A computer is a machine. A computer doesn't have a brain and can't think for it's self. Instead it has a set of instructions it follows so that it is able to do clever things.  Computers are everywhere. They help us do many useful things. Computers are used in schools for learning, at the doctors to keep track of appointments and at home too. But did you know that your microwave has a computer? When you press the buttons to cook your food a tiny computer built inside knows how to cook the food by the order you press the buttons. Clever right? It's the same with your washing machine, dishwasher and your camera. Scrapyard Challenge GameScrapyard Challenge Game Identify computer at the scrapyard. Can you pick them all out? What is computer coding? Computer coding is a list of instructions a computer follows to get a job done. This is also called an algorithm, the steps it need to take to complete a task. Bee Bot gameBee Bot Game Program the Bee Bot to get to the flower. Complete all 6 levels. Bitesize logoBitesize KS1 - Computing Computing resources for Key Stage 1. The internet The internet is loads of computers all connected together around the world. The computer that has this website on is in the the United Kingdom. In a split second you can click on other website and look at a website on a computer in China. Cool! You can use computers, tables, mobile phones and even your TV to see the internet.  Staying safe on the internet It is really important to stay safe on the internet. This means not sharing your personal information like your phone number, address and full name with anyone that you may meet on the internet. Check out our Internet Safety page for more information. Follow Super Brainy Beans's board Computer Coding on Pinterest. Input and output devices An input device is something that sends information to a computer, this could be a webcam, microphone or a keyboard. An output device is something that computer sends out. A computer could send an image to be printed to a printer, or it could produce a sound that would come out of its speakers. primary-computingBBC Schools - Primary Computing Everything you need to know about computing. KS1 & KS2. Create your own code People who create computer code are called coders. There are many programming languages you can learn to use. For example, C, Java, Ruby, JavaScript and Python. If you have never done any programming before then it's best to start with Scratch. It's an easy way to learn how code works without having to know all the code words. Fancy having a go at being a coder? Select a link below and start coding. Scratch websiteScratch Create stories, games and animations and share with others around the world. Shaun the Sheep Game Academy LogoShaun the Sheep Game Academy Learn how to build an awesome game using Scratch. swiftSwift Playgrounds Solve interactive puzzles in the guided “Learn to Code” lessons tynkerTynker Join for Free to try up to 20 activities blockyBlockly Invent your own programs by using Blockly to control Dash & Dot. scratch-appScratch Jr Ages 5-7 program your own interactive stories and games. hopstotchHopscotch Make games and learn to code cargobotCargo-Bot A puzzle game where you teach a robot how to move crates. Bitesize logoBitesize KS2 - Computing Computing resources for Key Stage 2. Khan Academy LogoKhan Academy What more of a challenge? Learn JavaScript or HTML to create webpages. How to create an algorithm that works We already know that an algorithm is a list of instructions that a computer follows. So let us look at how we would write these instructions. Imagine you are writing instructions to tell an alien how to walk from your bedroom to your bathroom. What would this look like? 1. Walk forward out of the bedroom. 2. Turn left. 3. Walk forward 4. Turn right. 5. Walk forward into the kitchen. That's a start but what happens if the bathroom door is shut? How would the alien know what to do? Okay, let us try again... 1. Walk forward out of the bedroom. 2. Turn left. 3. Walk forward 4. Turn right. 5. Check bathroom door 1. If it is closed, open it. 2. If it is open, do nothing. 6. Walk forward into the bathroom. That's better, but what if the cat gets in the way, or someone is in the bathroom? When you write code you have to think of everything that could happen and test your code. If you get an error you need to debug the code and fix the error. The Basics of Coding websiteBasics of Coding Answer the questions of computer questions and get a certificate for completion. Learn to type Want to learn to type fast? Then learn to touch type. Being able to touch type means that you don't have to look at the keyboard while you are typing. It will make you faster as you will then be able to keep your eyes on the text you are copying and not keep having to look at the keyboard. It may be slow to start with, but trust me it's worth learning. BBC Guides websiteDance Mat Typing Learn how to type the keys and row at a time with the help of Gary the Goat. Typing.com websiteTyping.com Work through the lessons to learn to type. Create a login if you want to save your progress. Big Brown Bear websiteBig Brown Bear The exercises gradually build up from using a few keys until you have total keyboard mastery.
__label__pos
0.927517
Permiso denegado: creación de archivos en Java Después de compilar el siguiente código en Eclipse usando una Mac: import java.io.*; public class Filer{ public static void main(String[] args) throws IOException{ File f1; f1 = new File("/System/file.txt"); if(!f1.exists()){ f1.createNewFile(); } } } Me sale un error: Exception in thread "main" java.io.IOException: Permission denied at java.io.UnixFileSystem.createFileExclusively(Native Method) at java.io.File.createNewFile(File.java:883) at Filer.main(Filer.java:11) ¿Alguien puede decirme por qué es eso? ¿Hay alguna forma de cambiar los permisos? Y si tuviera que compilar esto como un archivo .jar y enviárselo a alguien, ¿esa persona tendría los permisos correctos? Respuesta 1 ¿Alguien puede decirme por qué es eso? Su usuario no tiene permiso para crear un archivo en ese directorio. ¿Hay alguna forma de cambiar los permisos? De la misma manera que cambiaría los permisos de cualquier directorio. En Java 7+ Files.setPosixFilePermisions(f1.toPath(), EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_EXECUTE)); Y si tuviera que compilar esto como un archivo .jar y enviárselo a alguien, ¿esa persona tendría los permisos correctos? Sospecho que los permisos correctos para un directorio llamado /Systemes que NO tiene acceso de escritura. ¿Hay alguna razón para no usar el directorio de inicio o el directorio de trabajo actual? Respuesta: 2 Estoy buscando una buena herramienta para escribir pruebas de regresión para nuestra GUI Java Swing. Encontré jemmy2 y estoy realmente satisfecho con él. Sin embargo, hay un pequeño inconveniente: como muestran los ejemplos jemmy, yo ... Gracias por su atención. He creado un programa que estoy usando un formulario de inicio de sesión y un formulario de registro. Una vez que los usuarios registren su correo electrónico y su contraseña se guardará en submit.txt. Entonces ellos ... Necesito su ayuda sobre JAVA RMI, desarrollé un programa de muestra utilizado para ordenar la tabla. pero obtuve esta excepción: Erreur RemoteException ocurrió en el hilo del servidor; La excepción anidada es: java.rmi .... Tengo una aplicación web que usa hibernate 3.6.4 y spring 3.2.4 (mvc, tx y seguridad) y se ejecuta en tomcat 7. Cada vez que implemento una versión más nueva de mi aplicación sin reiniciar tomcat, entonces ...
__label__pos
0.911669
How to translate the theme in the Loco Translate plugin Translating a plugin 1) Select the DateBook plugin in Loco Translate Go to WordPress -> Loco Translate -> Plugins. Click DateBook. 2) Create a new language If you want to add/create a new language (for example: your own English language or another language: Greek, Irish, Japanese or other), then you should click “New language”, as you see below. If you want to edit the translation, then, find your language and click the Edit button next to that language. See a screenshot in step 6 below. 3) Choose a new language Select a language you would like to create, and click “Start translating”. See below how to do that: 4) Start translating words and phrases Now, you can search for words of the theme and translate them. After the translated done, remember to save all your changes. See below how to do that: Translating a theme 5) Select the DateBook theme in Loco Translate Go to WordPress -> Loco Translate -> Themes. Click DateBook. 6) Select a language and edit it You can create your English or other language or edit an existing language. 1) To create a new language, click “New language” button. 2) To edit an existing language, click the Edit button under the language title, as you see below: 7) Start translating and save After you completed translating, remember to save the changes. Done! Now the theme and plugin are translated.
__label__pos
0.998911
Frame drops by calling webgl render sub function I made panorama cube with mesh. Panorama cube’s 6 each face is textured by loaded image and mesh is added inside of panorama cube. When I rotate camera, sometimes frame goes smooth but sometimes frame goes little bit down. Which ways I can approach this problems? It seems you screenshots just show the initial texture upload overhead. This is a single-time issue and does not appear again if you just render your scene.
__label__pos
0.896322
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. I'm trying to add a few more icons to elements of a standard System.Windows.Forms.TreeView control. My plan was to only change the label area of the treeview control, but it shows a strange behaviour. If I click a node to select it, when the mouse button is depressed the background is draw correctly with the highlight color. However, the text is the wrong unselected color until I release the mouse button. It's as if e.State contains the wrong state between when the mouse button is pressed and released. Here is what I'm doing: I init with this.DrawMode = TreeViewDrawMode.OwnerDrawText and then register my event handler with this.DrawNode += LayoutTreeView_DrawNode. Here is the handler: void LayoutTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e) { Color color = (e.State & TreeNodeStates.Selected) != 0 ? SystemColors.HighlightText : SystemColors.WindowText; TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis; TextRenderer.DrawText(e.Graphics, e.Node.Text, Font, e.Bounds, color, flags); } If I set the handler to its default case... void LayoutTreeView_DrawNode(object sender, DrawTreeNodeEventArgs e) { e.DefaultDraw = true; } ...the same thing happens, which is weird since windows is actually drawing it now. This behaviour is in Windows XP with .Net 3.5. Is there any way to work around this strange behaviour? share|improve this question   FYI, it's always useful to include the .Net version you're dealing with. I'll give your sample a try to see if I fully comprehend what you're seeing. If I think I do I'll tell you what I think is going on. –  Jason D Mar 10 '10 at 21:07   Also, I'm never a fan of doing drawing in the consumer of a control. I always push to have it done in a derived class, that way if the same behavior is needed on another form or application it's easier to do. –  Jason D Mar 10 '10 at 21:08   I am unable to reproduce the described behavior with the draw default, but can with the custom code. I am running Vista x64; VS 2008. .Net 3.5. Could you add the OS, Visual Studio and .Net version that you're using to the question. (I've heard rumors that Vista and Windows 7 have some differences vs XP for how TreeViews work within the OS.) –  Jason D Mar 10 '10 at 21:13   Well, actually it is a derived control consuming its own events. The behaviour is in Windows XP with .Net 3.5 –  Coincoin Mar 11 '10 at 16:38 add comment 1 Answer up vote 3 down vote accepted Change Color color = (e.State & TreeNodeStates.Selected) != 0 ? SystemColors.HighlightText : SystemColors.WindowText; to Color color = (e.State & TreeNodeStates.Focused) != 0 ? SystemColors.HighlightText : SystemColors.WindowText; This worked on Vista x64 and VS 2008 with .Net 3.5. Let me know if it works for you. What I observed when watching the default windows behavior was that the text and highlight weren't drawn until the node was selected and had focus. So I checked for the focused condition in order to change the text color. However this doesn't precisely mimic the Widows behavior where the new colors aren't used until the mouse is released. It appears the point when it chooses to draw the blue highlight status changes when in ownerdrawn mode versus windows drawing it... Which admittedly is confusing. EDIT However, when you create your own derived treeview you have full control over when everything is drawn. public class MyTreeView : TreeView { bool isLeftMouseDown = false; bool isRightMouseDown = false; public MyTreeView() { DrawMode = TreeViewDrawMode.OwnerDrawText; } protected override void OnMouseDown(MouseEventArgs e) { TrackMouseButtons(e); base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { TrackMouseButtons(e); base.OnMouseUp(e); } protected override void OnMouseMove(MouseEventArgs e) { TrackMouseButtons(e); base.OnMouseMove(e); } private void TrackMouseButtons(MouseEventArgs e) { isLeftMouseDown = e.Button == MouseButtons.Left; isRightMouseDown = e.Button == MouseButtons.Right; } protected override void OnDrawNode(DrawTreeNodeEventArgs e) { // don't call the base or it will goof up your display! // capture the selected/focused states bool isFocused = (e.State & TreeNodeStates.Focused) != 0; bool isSelected = (e.State & TreeNodeStates.Selected) != 0; // set up default colors. Color color = SystemColors.WindowText; Color backColor = BackColor; if (isFocused && isRightMouseDown) { // right clicking on a color = SystemColors.HighlightText; backColor = SystemColors.Highlight; } else if (isSelected && !isRightMouseDown) { // if the node is selected and we're not right clicking on another node. color = SystemColors.HighlightText; backColor = SystemColors.Highlight; } using (Brush sb = new SolidBrush(backColor)) e.Graphics.FillRectangle(sb,e.Bounds); TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis; TextRenderer.DrawText(e.Graphics, e.Node.Text, Font, e.Bounds, color, backColor, flags); } } share|improve this answer   Also, capturing mouse buttons with mouseup and down doesn't work. This might be XP specific but the control is already processing selection and redrawing BEFORE the mosue events are raised in the control. –  Coincoin Mar 11 '10 at 16:42   I tried something similar and it works fine.... until you scroll and drag and drop. I resigned myself to drawing the whole item myself and now at least the text is synchronised with the back ground color even though the behaviour is a little strange. I will accept your answer as it is, I guess, the nearest we can get to the original XP behaviour without glitch. –  Coincoin Mar 11 '10 at 16:44   OOf. I guess I didn't bother with scroll and drag and drop. I've done the whole draw it yourself bit. It's a lot of code, but worthwhile if needed. (I believe my code was ~1000 LOC as I needed to draw check boxes, plus minus and the lines... ) –  Jason D Mar 12 '10 at 0:14 add comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.860739
Recipe 1.3 Enhancing the Output of a Tabular Display       1.3.1 Problem You need to display data from a database in a way that lets you organize and enhance the output beyond the confines of the DataGrid control's default tabular display. Selecting and editing the data are not important, nor is navigating through the data. 1.3.2 Solution Use a Repeater control with templates and then bind the data to the control. In the .aspx file, add a Repeater control and the associated templates for displaying the data. In the code-behind class for the page, use the .NET language of your choice to: 1. Open a connection to the database. 2. Build a query string, and read the desired data from the database using an OleDbCommand and OleDbDataReader . 3. Assign the data source to the Repeater control and bind it. Figure 1-2 shows the appearance of a typical Repeater in a browser. Example 1-4 through Example 1-6 show the .aspx and code-behind files for an application that produces this result. Figure 1-2. Using templates with Repeater control display output figs/ancb_0102.gif 1.3.3 Discussion When your primary aim is to organize and enhance the output beyond the confines of the DataGrid control's default tabular display, the Repeater control is a good choice because, unlike a DataGrid , it has associated templates that allow you to use virtually any HTML to format the displayed data. It also has the advantage of being relatively lightweight and easy to use. When using Repeater , however, there are a handful of nuances you should know about that can make life easier and, in one instance, enhance performance. Example 1-4 shows one of the most common approaches to using the Repeater control, which is to place the asp:Repeater element in a table and use its HeaderTemplate , ItemTemplate , and AlternatingItemTemplate attributes to format the displayed data as rows in the table. A HeaderTemplate is used to define the header row of the table. In this example, the header is straight HTML with a single table row and three columns . An ItemTemplate formats the even-numbered rows of data, while an AlternatingItemTemplate formats the odd-numbered rows. For both templates, a single row in the table is defined with the same three columns defined in the header template. In each of the three columns, data-binding statements (described later) define the data to be placed in each of the columns. The only differences between ItemTemplate and AlternatingItemTemplate are the color schemes and stylesheet classes used to output the rows. If you do not need to output the data using alternating styles, then omit the AlternatingItemTemplate attribute. The data from the database is bound to the cells in the templates using the DataBinder.Eval method. The Title field is placed in the first column, the ISBN field is placed in the second column, and the Publisher field is placed in the third column: DataBinder.Eval(Container.DataItem, "Title") DataBinder.Eval(Container.DataItem, "ISBN") DataBinder.Eval(Container.DataItem, "Publisher") If the header is pure HTML with no data binding required, it is more efficient to remove the HeaderTemplate attribute and place the header HTML before the asp:Repeater tag. By moving the header outside of the asp:Repeater tag, the creation of several server-side controls is eliminated, which reduces the time required to render the page and improves performance. <table width="100%" border="2" bordercolor="#000080" bgcolor="#FFFFE0" style="border-style:solid; border-collapse:collapse;"> <thead bgcolor="#000080" class="TableHeader"> <tr> <th align="center">Title</th> <th align="center">ISBN</th> <th align="center">Publisher</th> </tr> </thead> <asp:Repeater id=repBooks runat="server"> ... </asp:Repeater> </table> The Page_Load method in the code-behind, shown in Example 1-5 (VB) and Example 1-6 (C#), opens a connection to the database, reads the data from the database using an OleDbCommand and an OleDbDataReader object, binds the data reader to the Repeater control, and then performs the necessary cleanup. 1.3.4 See Also Recipe 1.6 for another example of using a template with a tabular control More About the DataBinder.Eval Method Recipe 1.3 uses the DataBinder.Eval method to bind data from the database to cells in the templates, as in: <%# DataBinder.Eval(Container.DataItem, "Title") %> The advantage of this approach is its relatively simple syntax. However, because the DataBinder.Eval method uses late-bound reflection to parse and evaluate a data-binding expression (in this case it's a simple string), there's a performance penalty associated with it. If performance is your prime concern, you could use the following syntax instead: <%# ((DbDataRecord)Container.DataItem)["Title"] %> In order for this syntax to work, explicit casting is required. Also, when casting to DbDataRecord , make sure to add the following page-level directive to the beginning of your .aspx file: <%@ Import namespace="System.Data.Common" %> Example 1-4. Templates with Repeater control (.aspx) <%@ Page Language="vb" AutoEventWireup="false" Codebehind="CH01TemplatesWithRepeaterVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH01TemplatesWithRepeaterVB" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Templates with Repeater</title> <link rel="stylesheet" href="css/ASPNetCookbook.css"> </head> <body leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> <form id="frmData" method="post" runat="server"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td align="center"> <img src="images/ASPNETCookbookHeading_blue.gif"> </td> </tr> <tr> <td class="dividerLine"> <img src="images/spacer.gif" height="6" border="0"></td> </tr> </table> <table width="90%" align="center" border="0"> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center" class="PageHeading"> Templates With Repeater (VB)</td> </tr> <tr> <td><img src="images/spacer.gif" height="10" border="0"></td> </tr> <tr> <td align="center"> <!-- Create a table within the cell to provide localized customization for the book list --> <table width="100%" border="2" bordercolor="#000080" bgcolor="#FFFFE0" style="border-style:solid;border-collapse:collapse;"> <asp:Repeater id=repBooks runat="server"> <HeaderTemplate> <thead bgcolor="#000080" class="TableHeader"> <tr> <th align="center">Title</th> <th align="center">ISBN</th> <th align="center">Publisher</th> </tr> </thead> </HeaderTemplate> <ItemTemplate> <tr bordercolor="#000080" class="TableCellNormal"> <td><%# DataBinder.Eval(Container.DataItem, "Title") %> </td> <td align="center"> <%# DataBinder.Eval(Container.DataItem, "ISBN") %> </td> <td align="center"> <%# DataBinder.Eval(Container.DataItem, "Publisher") %> </td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr bordercolor="#000080" bgcolor="#FFFFFF" class="TableCellAlternating"> <td><%# DataBinder.Eval(Container.DataItem, "Title") %> </td> <td align="center"> <%# DataBinder.Eval(Container.DataItem, "ISBN") %> </td> <td align="center"> <%# DataBinder.Eval(Container.DataItem, "Publisher") %> </td> </tr> </AlternatingItemTemplate> </asp:Repeater> </table> </td> </tr> </table> </form> </body> </html> Example 1-5. Templates with Repeater control code-behind (.vb) Option Explicit On Option Strict On '----------------------------------------------------------------------------- ' ' Module Name: CH01TemplatesWithRepeaterVB.aspx.vb ' ' Description: This class provides the code behind for ' CH01TemplatesWithRepeaterVB.aspx ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System.Configuration Imports System.Data Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples Public Class CH01TemplatesWithRepeaterVB Inherits System.Web.UI.Page 'controls on form Protected repBooks As System.Web.UI.WebControls.Repeater '************************************************************************* ' ' ROUTINE: Page_Load ' ' DESCRIPTION: This routine provides the event handler for the page load ' event. It is responsible for initializing the controls ' on the page. ' '------------------------------------------------------------------------- Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Dim dbConn As OleDbConnection Dim dCmd As OleDbCommand Dim dReader As OleDbDataReader Dim strConnection As String Dim strSQL As String If (Not Page.IsPostBack) Then Try 'get the connection string from web.config and open a connection 'to the database strConnection = _ ConfigurationSettings.AppSettings("dbConnectionString") dbConn = New OleDbConnection(strConnection) dbConn.Open( ) 'build the query string and get the data from the database strSQL = "SELECT Title, ISBN, Publisher " & _ "FROM Book " & _ "ORDER BY Title" dCmd = New OleDbCommand(strSQL, dbConn) dReader = dCmd.ExecuteReader( ) 'set the source of the data for the repeater control and bind it repBooks.DataSource = dReader repBooks.DataBind( ) Finally 'cleanup If (Not IsNothing(dReader)) Then dReader.Close( ) End If If (Not IsNothing(dbConn)) Then dbConn.Close( ) End If End Try End If End Sub 'Page_Load End Class 'CH01TemplatesWithRepeaterVB End Namespace Example 1-6. Templates with Repeater control code-behind (.cs) //---------------------------------------------------------------------------- // // Module Name: CH01TemplatesWithRepeaterCS.aspx.cs // // Description: This class provides the code behind for // CH01TemplatesWithRepeaterCS.aspx // //**************************************************************************** using System; using System.Configuration; using System.Data; using System.Data.OleDb; namespace ASPNetCookbook.CSExamples { public class CH01TemplatesWithRepeaterCS : System.Web.UI.Page { // controls on form protected System.Web.UI.WebControls.Repeater repBooks; //************************************************************************ // // ROUTINE: Page_Load // // DESCRIPTION: This routine provides the event handler for the page // load event. It is responsible for initializing the // controls on the page. // //------------------------------------------------------------------------ private void Page_Load(object sender, System.EventArgs e) { OleDbConnection dbConn = null; OleDbCommand dCmd = null; OleDbDataReader dReader = null; String strConnection = null; String strSQL = null; if (!Page.IsPostBack) { try { // get the connection string from web.config and open a connection // to the database strConnection = ConfigurationSettings.AppSettings["dbConnectionString"]; dbConn = new OleDbConnection(strConnection); dbConn.Open( ); // build the query string and get the data from the database strSQL = "SELECT Title, ISBN, Publisher " + "FROM Book " + "ORDER BY Title"; dCmd = new OleDbCommand(strSQL, dbConn); dReader = dCmd.ExecuteReader( ); // set the source of the data for the repeater control and bind it repBooks.DataSource = dReader; repBooks.DataBind( ); } finally { // cleanup if (dReader != null) { dReader.Close( ); } if (dbConn != null) { dbConn.Close( ); } } // finally } } // Page_Load } // CH01TemplatesWithRepeaterCS } ASP. NET Cookbook ASP.Net 2.0 Cookbook (Cookbooks (OReilly)) ISBN: 0596100647 EAN: 2147483647 Year: 2006 Pages: 179 flylib.com © 2008-2017. If you may any questions please contact us: [email protected]
__label__pos
0.685172
Skip to main content V6 License changes and text capabilities? carlbeech Hi I've been a long-time user of V5, and while its great to see a new version coming out, its not so great to see that you can't import STL files any more (I can't afford the monthly license fee) - however, given that this is a new and improved version, can I ask how come there isn't a simple 'add text' button - similar to tinkercad?    Thanks Carl. Share this post DesignSpark Electrical Logolinkedin
__label__pos
0.99838
1. Log in to pos.tableneeds.net and go to "Floor Plan" in the navigation 2. Turn your computer screen into a a preview of an ipad in a Chrome browser (Learn how here). This will ensure your tables fit into the KDS screen 3. Move the tables around in the layout of your tables of your floor plan. You can click on the table and rotate or resize the tables 4. To add additional tables, press the "Add" button 5. When you have a layout you'd like, press the "Save" button Did this answer your question?
__label__pos
0.964949
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. Could someone please help me understand the concept of memory leaking and how specific data structures promote/prevent it (e.g. linked lists, arrays etc). I've been taught it twice by 2 different people a while ago - which has confused me slightly because of the differences in teaching methods. share|improve this question 1   So now you're asking for a third explanation, using yet another method? –  Matti Virkkunen Feb 2 '11 at 14:41   I'm hoping someone will follow a similar methodology to one of the different explanations to make it concrete. Happy? –  user559142 Feb 3 '11 at 23:03 add comment 5 Answers up vote 7 down vote accepted Wikipedia has a good description on memory leaks. The defintion given there is: A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system. For example, the following C function leaks memory: void leaky(int n) { char* a = malloc(n); char* b = malloc(n); // Do something with a // Do something with b free(a); } The above function leaks n bytes of memory as the programmer forgot to call free(b). What that means is that the operating system has n bytes less memory to satisfy further calls to malloc. If the program calls leaky many times, the OS may eventually run out of memory that it could allocate for other tasks. As for the second part of your question, there is nothing intrinsic to data structures that makes them leak memory, but a careless implementation of a data structure could leak memory. As an example, consider the following function that deletes an element from a linked list: // I guess you could figure out where memory is leaking and fix it. void delete_element(ListNode* node, int key) { if (node != NULL) { if (node->key == key) { if (node->prev != NULL) { // Unlink the node from the list. node->prev->next = node->next; } } else { delete_element(node->next, key); } } } share|improve this answer add comment Basically, a memory leak occurs when a program allocates memory and does not release it even though it is not anymore needed. • In languages with manual memory management like C, this happens when the program fails to explicitly free heap memory, i.e. the programmer always has to do something to avoid memory leaks. • In garbage collection base languages like Java, it happens when the program inadvertedly keeps references to objects that aren't needed anymore. Very often, this happens when such objects are added to a "global" collection and then "forgotten" (especially when the adding happend implicitly). As you see from the second point, collections in general tend to be a focus of memory leaks because it's not obvious what they contain, doubly so when they are maintained internally by a long-lived object. The prototypical memory leak is a cache (i.e. a collection that is maintained implicitly) kept in a static variable (i.e. maximally long-lived). share|improve this answer add comment I agree with Vijay's answer for the most part, but it is important to note that leaks occur when references to heap blocks (pointers) are lost. The two common causes are: 1 - Losing scope of the pointer void foo(void) { char *s; s = strdup("U N I C O R N S ! ! !"); return; } In the above, we've lost scope of the pointer s, so we have absolutely no way to free it. That memory is now lost in (address) space until the program exits and the virtual memory subsystem reclaims everything the process had. However, if we just changed the function to return strdup("U N I C O R N S ! ! !");, we'd still have reference to the block that strdup() allocated. 2 - Re-assigning pointers without saving the original void foo(void) { unsigned int i; char *s; for (i=0; i<100; i++) s = strdup("U N I C O R N S ! ! !"); free(s); } In this example, we've lost 99 references to blocks that s once pointed to, so we're only actually freeing one block at the end. Again, this memory is now lost until the OS reclaims it after the program exits. Another typical misconception is that memory that is still reachable at program exit is leaked if the program does not free it prior to exiting. This has not been true for a very long time. A leak only happens when there is no way to dereference a previously allocated block in order to free it. It should also be noted that dealing with the static storage type is a little different, as discussed in this answer. share|improve this answer add comment The answer provided by Vijay shows you how to produce a memory leak. But finding a leak can be a quite difficult task once your program grows beyond a few lines of code. If you're on Linux, valgrind can help you to find leaks. On Windows you could use the CRT Debug Heap, which displays what leaked out, but not where it was allocated. To display where the leaking memory was allocated, you could use the Memory Validator which is quite painless to use: either run your program under the hood of Memory Validator or attach to a running process. No changes in sources are required. They provide a 30 day trial which is fully functional. share|improve this answer add comment I can't really add to what the others have said in terms of defining memory leaks, but I can give you a few notes on when memory leaks might happen. The first case that comes to mind is that of a function that does an allocation: int* somefunction(size_t sz) { int* mem; mem = malloc(sz*sizeof(int)); return mem; } There is nothing inheritently wrong with writing a function this way. It's a very similar concept to malloc. The problem is, you now start doing: int* x = somefunction(5); And its easy to forget, now that isn't a malloc, to free x. Again, there is nothing about this that means you will forget, but my experience tells me this is the sort of thing I and others overlook. A good strategy to get around this is to indicate in the function naming that allocation happens. So, call the function somefunction_alloc. The second case that comes to mind is threads, especially fork(), because the code is all in one place as it were. If you code neatly with functions, multiple files etc you'll almost always avoid errors, but remember that everything must be free'd within some scope, including that which was allocated both post fork() and pre fork. Consider this: int main() { char* buffer = malloc(100*sizeof(char)); int fork_result = fork(); if ( fork_result < 0 ) { printf("Error\n"); return 1; } elseif ( fork_result == 0 ) { /* do child stuff */ return 0; } else { /* do parent stuff */ } free(buffer); return 0; } There is a subtle error here. The parent will not leak any memory, but the child does, because it is an exact copy of the parent, heap included, but it exits before freeing anything. Free must happen on both code paths. Likewise, if the fork fails, you still haven't freed. It is easy to miss things when you're writing code like this. A better method is to create an exit code variable like int status = 0; and modify it where errors occur, and do not use return in any structure but allow child and parent code paths to continue on to the end of the program as they should. That said, threading and forking always make debugging more difficult due to their nature. share|improve this answer add comment Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.975454
Documentation Home »User Guide: Commerce »Pricing »Price Lists Management »Filtering Expression Syntax 1.6 version Filtering Expression Syntax The filtering expression for the product assignment rule and the price calculation condition follow the Symfony2 expression language syntax and may contain the following elements: • Entity properties stored as table columns, including: • Product properties: product.id, product.sku, product.status, product.createdAt, product.updatedAt, product.inventory_status, etc. • Properties of product’s children entities, like: • Category properties: product.category.id, product.category.left, product.category.right, product.category.level, product.category.root, product.category.createdAt, and product.category.updatedAt • Any custom properties added to the product entity (e.g. product.awesomeness), or to the product children entity (e.g. product.category.priority and product.price.season) • Price properties: pricelist[N].prices.currency, pricelist[N].prices.productSku, pricelist[N].prices.quantity, and pricelist[N].prices.value, where N is the ID of the pricelist that the product belongs to. • Relations (for example, product.owner, product.organization, product.primaryUnitPrecision, product.category, and any virtual relations created in OroCommerce for entities of product and its children. Note • To keep the filter behavior predictable, OroCommerce enforces the following limitation in regards to using relations in the filtering criteria: you can only use parameters residing on the “one” side of the “one-to-many” relation (including the custom ones). • When using relation, the id is assumed and may be omitted (e.g. “product.category == 1” expression means the same as “product.category.id == 1”). • Any product, price and category entity attribute is accessible by field name. • Operators: +, -, , / , %, * , ==, ===, !=, !==, <, >, <=, >=, matches (string) (e.g. matches ‘t-shirt’; you can also use the following wildcards in the string: % — replaces any number of symbols, _ — any single symbol, e.g., matches ‘ t_shirt’ returns both ‘t-shirt’ and ‘t shirt’) and, or, not, ~ (concatenation), in, not in, and .. (range). • Literals: You can use strings (e.g. ‘hello’), numbers (e.g. 345), arrays (e.g. [7, 8, 9] ), hashes (e.g. { property_name: ‘property_value’ }), true, false and null. Browse maintained versions: current1.6 You will be redirected to [title]. Would you like to continue? Yes No ssossossosso
__label__pos
0.666971
Changes between Version 39 and Version 40 of BluePrintVITA Ignore: Timestamp: 03/27/10 00:24:11 (12 years ago) Author: Dominic König Comment: -- Legend: Unmodified Added Removed Modified • BluePrintVITA v39 v40   1212  - a set of interfaces to request and manipulate person entity data 1313  - an XML-based data format to communicate person entity data  14  15== Ontology ==  16  17Ontology draft for "Personal Data for Disaster Management" (suggested for implementation in the data model):  18  19  * [http://ontology.nursix.org/sahana-person.owl "OWL Source"]  20  * [http://ontology.nursix.org/sahana-person.png "Class Tree Diagram"]  21  22''(still under development, see the OWL source for version information)''  23  24This ontology defines four axes for the construction of "Personal Data" relations:  25  26  * '''Appearance''' - forms of appearance (of persons)  27  * '''Distinction''' - classes for operational distinction (assigned features)  28  * '''Evidence''' - classes of data sources  29  * '''Finding''' - classes of findings (observed or derived features)  30  31Every data set implements at least one class (aspect) from each axis (at least implicitly, e.g. in case of the appearance aspect). 1432 1533== The Data Model ==
__label__pos
0.721966
/node-js/ Node.js, Express, Jade and simple CRUD 2014-08-11 18:58:39 I use in this example: Before start you have to install nodejs and npm sudo apt-get update sudo apt-get install nodejs sudo apt-get install npm node_modules: npm install express npm install jade npm install body-parser Project structure server.js var express = require('express'); var bodyParser = require('body-parser') var path = require('path'); var methodOverride = require('method-override') var post = require('./module/post'); var app = express(); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.static(path.join(__dirname, 'public'))); app.use(bodyParser.urlencoded({ extended: false })) app.get('/', post.index); app.get('/post/create', post.form); app.post('/post/create', post.save); app.get('/post/details/:id', post.details); app.get('/post/edit/:id', post.edit); app.post('/post/update', post.update); app.get('/post/delete/:id', post.remove); app.listen(3000); post.js var util = require('util'); var db = require('./postMemoryDb'); exports.index = function (req, res) { res.render('post/index', { posts: db.list()}); }; exports.form = function (req, res) { res.render('post/form'); }; exports.details = function (req, res) { var post = db.getById(req.params.id); res.render('post/details', {post: post}); }; exports.edit = function (req, res) { var post = db.getById(req.params.id); res.render('post/edit', {post: post}) } exports.save = function (req, res) { db.add({name: req.body.name, desc: req.body.desc}); res.redirect('/'); }; exports.update = function (req, res) { db.update({id: req.body.id, name: req.body.name, desc: req.body.desc}); res.redirect('/'); }; exports.remove = function (req, res) { db.remove(req.params.id); res.redirect('/'); }; postMemoryDb.js var memoryDb = {}; var id = 0; var list = function () { return memoryDb; }; var add = function (item) { id = id + 1; item.id = id; memoryDb[item.id] = item; }; var getById = function (id) { return memoryDb[id]; }; var update = function (item) { console.log(item.id); memoryDb[item.id] = item; }; var remove = function (id) { delete memoryDb[id]; }; exports.list = list; exports.add = add; exports.getById = getById; exports.memoryDb = memoryDb; exports.remove = remove; exports.update = update; index.jade doctype html head title body h1 Posts ul each item in posts li Item #{item.name} - #{item.desc} - a(href='/post/details/#{item.id}') Details - a(href='/post/edit/#{item.id}') Edit - a(href='/post/delete/#{item.id}') Delete div p a(href='post/create') Add new form.jade doctype html head title body h1 New post form(id='form', action='/post/create', method='POST') input(id='name', name='name', placeholder='Name') input(id='desc', name='desc', placeholder='Desc') input(type='submit', value='Add post') edit.jade doctype html head title body h1 New post form(id='form', action='/post/update', method='POST') input(id='id', name='id', type='hidden', value='#{post.id}') input(id='name', name='name', value='#{post.name}') input(id='desc', name='desc', value='#{post.desc}') input(type='submit', value='Update post') details.jade doctype html head title body p Name: #{post.name} p Desc: #{post.desc}
__label__pos
0.9448
Você está na página 1de 5 ATIVIDADE DE MATEMÁTICA 1) Faça o agrupamento dos monônimos abaixo: a) 3ax + 5bx – 12 ax – 15 bx + 4x =. c) 24aw + 6x – 12aw – 6x = b) 15y – 4z + 3x + 12y – 20z = 2) Resolva as adições de monômios abaixo: a) 15ax + 6ax = c) 32cz3 + 24cz3 = 6 2 b) 1by + 15by = Digite a equação aqui . b) 32cz - (- 24cz) = 3) Utilizando o agrupamento, resolva as expressões numéricas abaixo: a) 2x2 + 20y3 – 15y3 – 36x2 =. b) 6x2 - 7 x2 + 28 x2 = 10 4) Análise a figura a seguir: Suponha que o terreno comprado por um proprietário tenha a forma da figura acima e suas medidas sejam representadas, em unidades de comprimento, pelas variáveis X, Y e Z. A expressão algébrica que representa o perímetro desse terreno é: a) 2x + 3y + z b) 3x + 4y + 2z c) 3x + 3y + z d) 3x + 2y + 3z e) 4x + 3y + 2z 05) Reduzindo-se os termos semelhantes da expressão b(a - b) + (b + a) (b - a) - a(b - a) + (b - a)2, obtém- se: a) (a – b)2 b) (a + b)2 c) b2 – a2 d) a2 – b2 e) a2 + b2 6) Resolva: a) (y2 + 4y – 5) + (– 3y2 + 12y – 1)=. b) x2 + 12x – 9 – (– 8x2 + 7x – 1)= 7) As redes de fast food têm nas suas caixas registradoras teclas associadas a alguns produtos que são muito pedidos. Basta apertar uma tecla e indicar a quantidade daquele produto que o preço já sai calculado. Produto X - Bolão Oba Cola Sorvetão Preço (R$) 5 1,5 3 a) Qual o gasto da turma se, ao todo, foram pedidos 15 sanduíches X-Bolão. 11 refrigerantes Oba Cola e 10 sorvetes? b) Escreva uma expressão algébrica que indica o valor gasto ao serem pedidos x sanduíches, y refrigerantes e z sorvetes. 08) Jorge quer construir um galinheiro aproveitando um muro de seu quintal e alguns metros de tela que possui. a) Se Jorge tivesse 9m de tela, qual seria a área do quintal ocupada pelo galinheiro? b) Supondo que o comprimento da tela seja desconhecido e indicado por c, c  6m, escreva uma expressão algébrica para o cálculo da área do galinheiro dependendo do comprimento c da tela. 09) Sendo o perímetro da figura igual a 48cm, determine: a) o valor de x. b) o polinômio( a expressão )que representa a área em função de x 10) Naquele bimestre, o professor de inglês de Fabíola iria avaliar os alunos baseado em participação em classe e na média das provas. Para calcular a média das provas, ele atribuiu peso 1 à P 1+ P 2 M= primeira e peso 2 à segunda. A média, então, era dada por: 3 , em que P1 e P2 são as notas das duas primeiras provas. Fabíola obteve 3 na primeira prova. a) Qual seria a média de provas de Fabíola se a nota da segunda prova fosse igual a 6? b) Considerando como satisfatórias para aprovação as médias de provas com valores maiores ou iguais a 6, qual deveria ser a nota mínima de Fabílola na segunda prova para não ser reprovada? 11) O número S do sapato que uma pessoa calça está relacionado com o comprimento p, em 5 P+28 S= centímetros, de seu pé pela fórmula: 4 . Qual é o comprimento do pé de uma pessoa que calça sapatos de número 41? Agora meça o comprimento do seu pé e confira o número do seu sapato. 12) Uma estrada está marcada em cinco partes iguais conforme a figura abaixo. Se o carro X está na posição 170,3 e o Y está na posição 231,8 , qual será a localização do carro Z? 13) Considere um retângulo de base (x + 5) e altura ( 2x ). a) Escreva uma expressão algébrica que represente o seu perímetro. b) Escreva uma expressão algébrica que represente a sua área. 14) Observe as formas planas: a) Escreva seus perímetros na forma de polinômios ( um, dois, três ou mais termos) b) Se o perímetro da forma retangular é de 24 cm, qual é o valor de x? c) Se a outra tem perímetro de 84 cm e a + 7cm, qual é o valor de b? 15) Se A = x² +1 e B = – 2x² + x + 2, determine o valor de: a) A + B b) A – B c) B – A d) 3 . A e) – 5.B f) – 2.A + 3.B 16) Calcule os seguintes produtos: a) – 2 a.(x + 4 ) b) 2x.(3x + 4y – 2) c) (x + 5 ). ( x² + 2x – 10 ) d) (x + 1 ) . ( x² + 2x – 1 ) e) ( x + 7 ) . ( x + 3 ) Você também pode gostar
__label__pos
0.987916
Threaded select reactor The threadedselectreactor is a specialized reactor for integrating with arbitrary foreign event loop, such as those you find in GUI toolkits. There are three things you'll need to do to use this reactor. Install the reactor at the beginning of your program, before importing the rest of Twisted: | from twisted.internet import _threadedselect | _threadedselect.install() Interleave this reactor with your foreign event loop, at some point after your event loop is initialized: | from twisted.internet import reactor | reactor.interleave(foreignEventLoopWakerFunction) | self.addSystemEventTrigger('after', 'shutdown', foreignEventLoopStop) Instead of shutting down the foreign event loop directly, shut down the reactor: | from twisted.internet import reactor | reactor.stop() In order for Twisted to do its work in the main thread (the thread that interleave is called from), a waker function is necessary. The waker function will be called from a "background" thread with one argument: func. The waker function's purpose is to call func() from the main thread. Many GUI toolkits ship with appropriate waker functions. Some examples of this are wxPython's wx.callAfter (may be wxCallAfter in older versions of wxPython) or PyObjC's PyObjCTools.AppHelper.callAfter. These would be used in place of "foreignEventLoopWakerFunction" in the above example. The other integration point at which the foreign event loop and this reactor must integrate is shutdown. In order to ensure clean shutdown of Twisted, you must allow for Twisted to come to a complete stop before quitting the application. Typically, you will do this by setting up an after shutdown trigger to stop your foreign event loop, and call reactor.stop() where you would normally have initiated the shutdown procedure for the foreign event loop. Shutdown functions that could be used in place of "foreignEventloopStop" would be the ExitMainLoop method of the wxApp instance with wxPython, or the PyObjCTools.AppHelper.stopEventLoop function. Function dictRemove Undocumented Function raiseException Undocumented Class ThreadedSelectReactor A threaded select() based reactor - runs on all POSIX platforms and on Win32. Function install Configure the twisted mainloop to be run using the select() reactor. def dictRemove(dct, value): (source) Undocumented def raiseException(e): (source) Undocumented def install(): (source) Configure the twisted mainloop to be run using the select() reactor. API Documentation for Twisted, generated by pydoctor at 2015-11-29 11:40:45.
__label__pos
0.604544
answersLogoWhite 0 Best Answer Supplement of 65 = 180-65 = 115 degrees. User Avatar Wiki User 14y ago This answer is: User Avatar Add your answer: Earn +20 pts Q: What is the measure of the supplement of 65? Write your answer... Submit Still have questions? magnify glass imp Related questions The supplement of a 65 angle has a measure of? 115 degrees What is the supplement of a 65 degree angle? A pair of supplementary angles total 180 degrees. In this instance, the supplement to a 65 degree angle would be 180 - 65 = 115 degrees. What is the supplement to 152 degrees? 28 degrees An angle is 30 more than its supplement what is the measure of the angle and its supplement? The angle is 105, its supplement is 75. Three times the measure of the supplement of an angle is equal to eight times the measure of its complement Find the angle its complement and its supplement? The angle= 36, the supplement= 144, the compliment=54 An angle measure 17 more than 3 times a number.its supplement is three more than 7 times the number.what is the measure of each angle in degrees? The angles are: 65 degrees and 115 degrees = 180 degrees What does albumin measure? Dietary supplement The measure of the supplement of an angle is 40 less than 3 times its complement Find the measure of the angle its supplement and its complement? 25 What is the measure of an angle if its measure is 40 degrees more than the measure of its supplement? supplement + angle = 180180 - angle = supplementangle = supplement + 40 = 180 - angle +40 = 220-angle2 x angle = 220angle = 110 degrees An angel measure is 5 degrees less than 3 times the measure of its supplement Find the measure of the angle and its supplement? The angles are: 43.75 degrees and 136.25 degrees What a 45 degree angle in supplement measure? The supplement of 45 degrees is 135 degrees. What is the supplement of an angle with measure 23? What_is_the_supplement_of_an_angle_with_measure_23
__label__pos
1
Skip to content Formatting Testing Formatting tests are data-driven instead of being specified explicitly. This document explains how to add a new formatting test. Adding a formatting test 1. Create a new file with the extension .sdsdev in the tests/resources/formatting directory or any subdirectory. Give the file a descriptive name, since the file name becomes part of the test name. Skipping a test If you want to skip a test, add the prefix skip- to the file name. 2. Add the original unformatted Safe-DS code to the top of the file. The code must be syntactically valid. 3. Add the following separator to the file: // ----------------------------------------------------------------------------- 4. Add the expected formatted Safe-DS code to the file below the separator. 5. Run the tests. The test runner will automatically pick up the new test.
__label__pos
0.93232
how to use a ti89 calculator to graph linear equations math wonderhowto equations graphing calculator to get systems solution piecewise functions in the graphing calculator a solution of system two equations in variables is an how to graph a system of linear equations on a ti83 or ti84 math wonderhowto graphing linear equations 2 variables calculator tessshlo solving quadratic equations using graphing calculator worksheet traveling with linear equations graphing equations calculator jennarocca example 1 solve a linear quadratic system by graphing solve the system using a graphing how to solve a quadratic equation with a graphing calculator math wonderhowto 1 solve systems graphically with calculator extended learning use the e tutor graphing calculator to solve image titled use a graphing calculator to solve a systems of equations step 7 standard form of equation calculator talkchannels how to solve equations by graphing on the clep scientific calculator lesson transcript study com graphing a system of equations calculator image gallery linear graph equation solver graph linear equations by plotting points calculator jennarocca graphing linear equations official tutor com blog incorporate technology into your math classroom and help kids make sense of systems of linear description of lesson using the ti 83 graphing calculator solving and graphing linear equations graphing to get solutions for systems solving algebraic equations calculator tessshlo guided practice example 2 solve the system below table and graph worksheet 4 18 graphing systems of linear equations answer key graphing calculator art equations jennarocca solving and graphing systems of equations calculator tessshlo y intercept 1 graphing graphing linear equations calculator jennarocca voary linear equations 1 what you will learn voary how to plot a point in 3 before graphing check your calculator settings image titled use a graphing calculator to solve a systems of equations step 1 solving systems of equations using matrices graphing calculator math algebra graphing systems of equations matrices a rei 8 showme solving two step linear equations calculator jennarocca using linear combinations to solve systems of equations graphing equation solver talkchannels
__label__pos
0.999967
Blog Detail Home / hartford escort / And therefore means can you swipe towards the tinder? And therefore means can you swipe towards the tinder? And therefore means can you swipe towards the tinder? It doesn’t really matter perhaps the person you swiped leftover happen to, swiped your right or remaining, or haven’t swiped you yet, as you can’t matches together. Needless to say, they are able to simply be removed right back if you have entry to Tinder Silver or And additionally. All you have to would should be to faucet on yellow arrow at the end kept of display. Cancel an excellent Tinder correct swipe The challenge is a little bit other which have Tinder correct swipes. The reason hookupdates.net/escort/hartford behind this is when a profile has recently swiped your right and you also accidentally swipe the woman correct, it becomes a simple matches. In cases like this, your definitely cannot make proper swipe right back as it’s a complement currently. If this happens then you may go to the man or woman’s reputation and only just unmatch the lady. For folks who correct swipe anyone and it is maybe not a quick fits you might terminate the proper swipe in the same way just like the a left swipe. Taking back good Tinder Swipe right up Tinder Swipe Ups a great.k.good. Tinder Extremely Loves work in the same way given that Tinder best swipes when you have access to Tinder Rewind. For many who instant fits for the kids your swiped upwards your usually do not get back the fresh swipe right up. Frequently asked questions If you discover people glamorous and want to features a discussion with her, you should swipe the woman correct. If she as well as look for you attractive she will swipe your correct, you can aquire good Tinder fits and start a conversation with the woman. If you don’t need to match having anyone merely swipe their kept, you will never find the lady ever again. Exactly how many swipes might you log in to Tinder? While Tinder Remaining swipes try unlimited, approximately you have made 50-100 best swipes in the good several time several months which have a free of charge account. When you have entry to Tinder subscriptions you will also have endless likes. Does Tinder show the same person double? For those who have currently swiped remaining or best people, the guy should not pop-up on your swiping deck ever again. You will find step three exceptions when this can invariably occurs: it is both good Tinder bug, it is a phony otherwise bot character, or perhaps the individual deleted following reset her profile. Commonly Tinder guide you a person who your already swiped left? No, they will not arrive again on the development screen reputation the person you enjoys swiped leftover. Really the only different occurs when they or if you reset the Tinder pages. How do you determine if some body swiped close to Tinder? As well as meets with them, the only way to understand is the Come across Whom Loves you display screen where you can select most of the users that have swiped your proper nevertheless have not swiped her or him but really. You will get accessibility that it display screen when you have Tinder Gold or by using the greatest blur cheat. Really does Tinder assist you pages you currently swiped correct? Even though you removed the match otherwise she unmatched your, she won’t appear in your finding display ever again. The only exception is that you or she’s got removed and reset Tinder. How does Tinder matching really works? When several Tinder pages swipe directly on one another regarding Discovery monitor, they’ll score an excellent Tinder Meets and they can start chatting each other. This isn’t enough to possess a complement if only certainly her or him swiped right additionally the almost every other one to swiped remaining or have maybe not swiped yet. Why you ought to not at all times swipe correct Eventually swiped left towards the Tinder? Don’t worry, Tinder left swipes can be drawn back into any possible circumstance that have Tinder Rewind.
__label__pos
0.834592
41. The 50th percentile would yield a z score of a. -1 b. +500 c. above +1 d. 0 45 42. Over 50% of a     41. The 50th percentile would yield a z score of a. -1 b. +500 c. above +1 d. 0 45 42. Over 50% of all the scores would fall above a raw score of a. 568 b. 534 c. 501 d. 499 43. When a given point under the normal curve is 1.54 standard deviation units above the mean, then a. its percentile is 15.4 b. its percentile is 1.54 c. its z score is +1.54 d. both a and c, but not b 44. All percentiles of less than 50 must necessarily a. fall below the raw score mean b. yield negative z scores c. fall to the left of the z score mean d. all of these 45. A positive z score must always yield a percentile which is a. above 50 b. below 50 c. between 40 and 60 d. above 100 46. Percentiles always indicate a. the percentage of cases falling below a given point b. the percentage of cases falling above a given point c. the percentage of cases falling between a given z score and the mean d. the percentage of cases falling above a given z score 47. A z score of +3 corresponds with a a. percentile of 3 b. percentile of 53 c. percentile of 103 d. raw score which is 3 standard deviation units above the mean 48. For a z score of 1.35 the z score table indicates a percentage value of 41.15. This means that a. 41.15% of the cases fell below a z score of +1.35 b. 41.15% of the cases fell above a z score of +1.35 c. 41.15% of the cases fell between z scores of +1.35 d. 41.15% of the cases fell between a z score of +1.35 and the mean 46 49. The z score table always gives, as a direct read-out, the percentage of cases falling a. between a given z score and the mean b. below a negative z score c. above a positive z score d. none of these 50. The percentage values on the z score table are only valid when a. the z scores are positive b. the raw score mean equals 50 c. the raw score mean is greater than 50 d. the distribution is normal   Expert's Answer Submit Your Questions Here ! Copy and paste your question here... Attach Files 187 Wolf Road, Albany New York, 12205, USA Level 6/140 Creek Street, Brisbane, QLD 4000, Australia [email protected] Reach us on: © 2007-2022 Transweb Global Inc. All rights reserved.
__label__pos
0.96319
Take the 2-minute tour × Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required. 1. Where and how are Linux processes and threads configured? 2. What is the name of the underlying Linux resource that manages processes and threads and determines their total number? 3. Is there a limit on, and if so, what is the total number of threads & processes that can be created in a Linux system? share|improve this question 1   1) Memory. 2) That depends on the memory available. Related: stackoverflow.com/questions/344203/…. –  Frédéric Hamidi Jun 8 '12 at 10:17 1 Answer 1 up vote 1 down vote accepted There is a bunch of sysctls and ulimits that relate to this. Threads and processes on linux are both created with the clone syscall under the hood, and are all in fact the same thing, just with different parameters. So when you see "process" related settings on linux, they are also thread related settings most of the time. $ ulimit -u ...will get/set the max user processes You also need to look at: /etc/security/limits.conf and of course: /proc/sys/kernel/threads-max I've had upwards of 10000 threads running no problem at all on a 64-bit system. If you need more than that you are better off doing cooperative multitasking, and handle the "task scheduling" yourself. share|improve this answer Your Answer   discard By posting your answer, you agree to the privacy policy and terms of service. Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.985542
Is it me, or have some forums *Disappeared*? Discussion in 'Site Suggestions, Help and Announcements' started by RickAgresta, Jan 3, 2018. 1. Charles P. Jefferies Charles P. Jefferies Administrator Super Moderator Messages: 85 Likes Received: 135 Trophy Points: 33 We'll open permissions to the News forum, sure. Charles   Chronos, scjjtt, Mi An and 6 others like this. 2. scjjtt scjjtt A Former Palm User Messages: 2,316 Likes Received: 4,053 Trophy Points: 288 Here is what I'm getting trying to post to it.., [​IMG] Sent from my LG G4 using Tapatalk   3. RickAgresta RickAgresta Peanut, leader of the Peanutty Forces Messages: 20,431 Likes Received: 14,822 Trophy Points: 288 Via the web, I see the same message Scott. hopefully, soon…<RA holds off on asking if Scott would like to buy a bridge in one of the NYC boros…>   Hook, scjjtt and jigwashere like this. 4. Charles P. Jefferies Charles P. Jefferies Administrator Super Moderator Messages: 85 Likes Received: 135 Trophy Points: 33 Our developers say they've opened the permissions, Log in/out and try again. Best, Charles   scjjtt, jigwashere, Hook and 2 others like this. 5. Hook Hook Professional Daydreamer Messages: 19,193 Likes Received: 9,015 Trophy Points: 288 Yup. works now! :thumbsup: Thanks!   Chronos, scjjtt, jigwashere and 2 others like this. 6. EdmundDantes EdmundDantes Mobile Deity Messages: 2,207 Likes Received: 1,909 Trophy Points: 288 Frankly, it seems nicely cleaned up besides the already solved glitches, but I do have one suggestion/question: there's no Apple forum under device manufactures. Shouldn't there be? I'm not a big Apple user, although I've recently considered going back, but it seems like it would make sense.   Charles P. Jefferies and scjjtt like this. 7. headcronie headcronie Greyscale. Nuff Said. Super Moderator Messages: 13,843 Likes Received: 3,277 Trophy Points: 113 The results you see, are from collapsing forums and sub forums. This forum has never been a leading forum for Apple posts, and as such, never a forum in that area for Apple hardware. The hardware options are for lack of better words, limited by Apple's own nature. You're more likely to have OS / software questions, than you are to have a specific model question due to this. If this forum should ever gain such popularity as to necessitate a forum just for Apple hardware, I'd think a sub forum could be added at that time.   8. lelisa13p lelisa13p Your Super Moderator Super Moderator Messages: 22,981 Likes Received: 6,266 Trophy Points: 288 I like the iOS/iPhone relocation just fine. It makes sense. :vbsmile:   9. EdmundDantes EdmundDantes Mobile Deity Messages: 2,207 Likes Received: 1,909 Trophy Points: 288 Yes, but it's really the only one where the software/OS is combined with the hardware and there are differences. Even Palm has these separated and those are not really all that active (said as a Palm diehard).   scjjtt likes this. 10. headcronie headcronie Greyscale. Nuff Said. Super Moderator Messages: 13,843 Likes Received: 3,277 Trophy Points: 113 Palm has countless forums and sub forums, as Brighthand used to be the place to go for everything Palm. Representatives from Palm used to have discussions with the owner and staff of Brighthand, and took information directly back to Palm, on a monthly basis if I remember correctly. This was before exploits shook the industry, before using a device a few years old, meant that it was just old, and not a security vulnerability. The times have radically changed since the days of Palm. For iOS, if you are not using a device that is capable of using version 11.2.2 as of 1/15/18, I wouldn't even bother to offer support, beyond that of go get a new device and transfer your data. Anyone that begs to differ, can queue up in my support line, that I'll never get to. I don't see hardware forums for iOS to be of much benefit. The question needs to be, what OS version. If OS version =/= supported version, get updated or upgraded. Once up to date, then proceed with question.   Share This Page
__label__pos
0.643301
Lesson Plan : Using Equations and Inequalities Teacher Name:  Ben Middleton Grade:  Grade 7-8 Subject:  Math Topic:  Using equations and Inequalities to solve problems. Content:  Define a variable, write an equation or inequality, and then solve. Sum= addition product= multiplication quotient= division is=equals (=) at most= less than or equal to (<) at least= greater than or equal to (>) more than= greater than (>) difference= subtraction increased= addition decreased= subtraction Goals:  Students will be able to solve verbal problems by translating them into equations and inequalities. Objectives:  a.Solve verbal problems by translating them into ineqalities. b.Solve verbal problems by translating them into equations. Introduction:  We have gone over how to solve equations and inequalities in the past. You know how to do those. Now we are going to see how to take a word problem where we don't have anything to solve and turn it into an equation or inequality so that we can then solve it. These word problems have been put into codes and so you need to know how to break the codes to find out how to work the problems. Development:  Steps: 1. Explore-Look at the problem to get the main idea of what it is asking you to do.Find all the important information that you will need to solve the problem. 2. Plan- Translate the words that are used into an equation or inequality using the variable. 3. Solve- Solve the problem. 4. Examine- Check the answer and see if it makes sense. Examples: 1.A number increased by 4 is 16. x+4=16;x=12 2.The product of 21 and a number is at most -84. 21x<-84; x=-4. 3.The result of dividing a number by 7 is 49. x/7=49;x=343 4.The quotient of a number and 8 is greater than 72. x/8>72;x>576 5. Four times a number is greater than 76.4x>76;x>19 Practice:  Work through problems with class until they are able to reach level of three consecutive solved problems. 1.Five times some number equals -85. 5x=-85;x=-17 2.Seven dollars less than the cost of the compact disc is $12. x-$7=$12;x=$19 3.The quotient when dividing a number by -7 is less than 112. x/-7<112;x<-784 4.Maria bought 3 pairs of jeans for $75. If each pair costs the same amount, how much did each pair cost? 3x=75;$25. 5.Three friends went to dinner together to celebrate one of them getting a job promotion. The total of the check was less than $36. If the cost was shared evenly, how much did each person pay for dinner? 3x<36;x<12 Checking For Understanding:  When correcting worksheets look for correct answer as well as comprehension of what different terms mean and how to organize the information into equations or inequalities. Teacher Reflections:  I was unable to give this lesson due to sickness from food poisoning. Create New Lesson Plan Lesson Plan Center Popular Areas: Bloom's Taxonomy Verbs | Lesson Planning Blocks | Lesson Forms Pack | Lesson Writing | Teacher Forum Chat
__label__pos
0.999267
Beefy Boxes and Bandwidth Generously Provided by pair Networks Syntactic Confectionery Delight   PerlMonks   Re^2: Breaking The Rules II by tsee (Curate) on Jul 05, 2007 at 09:55 UTC ( #625027=note: print w/ replies, xml ) Need Help?? in reply to Re: Breaking The Rules II in thread Breaking The Rules II I forgot to mention how you'd actually use that specific "wheel" to evaluate expressions. I know it's not the point of this meditation to just use the existing tools, but comparison might still be sensible. #!/usr/bin/perl use strict; use warnings; use Math::Symbolic; my $parser = Math::Symbolic::Parser->new(); while (1) { print "\n> "; my $line = <STDIN>; my $tree = $parser->parse($line); print("Parse error.\n"), next if not defined $tree; print "Entered: $tree\n"; my $result = $tree->value(); print("Evaluation error.\n"), next if not defined $result; print "Result: $result\n"; } The output would look like this: > 3*4.2e3+5^(3.1+2) Entered: (3 * 4.2e3) + (5 ^ (3.1 + 2)) Result: 16270.6841971501 > a*b+c Entered: (a * b) + c Evaluation error. That last bit shows that the parser is actually intended to be used with variables, too. So it's not a parse error but an evaluation error. Switching to using the YAPP based parser is rather straightforward, too. Just add "implementation => 'Yapp'" to the call to the constructor. Cheers, Steffen Comment on Re^2: Breaking The Rules II Select or Download Code Log In? Username: Password: What's my password? Create A New User Node Status? node history Node Type: note [id://625027] help Chatterbox? and the web crawler heard nothing... How do I use this? | Other CB clients Other Users? Others pondering the Monastery: (8) As of 2015-07-08 00:16 GMT Sections? Information? Find Nodes? Leftovers? Voting Booth? The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ... Results (93 votes), past polls
__label__pos
0.759422
JS deobfuscator: Your Key to Understanding Cryptic Code JS deobfuscator In the ever-evolving landscape of web development and cybersecurity, JavaScript (JS) remains a pivotal tool for creating dynamic and interactive web experiences. However, with the rise of sophisticated cyber threats, protecting sensitive code from prying eyes has become paramount. This is where JavaScript obfuscation steps in, serving as a shield against reverse engineering and unauthorized access. But what if you need to understand and modify obfuscated code for legitimate reasons? Enter the JS deobfuscator, a powerful tool that unveils the mysteries hidden within obfuscated JavaScript. Understanding JavaScript Obfuscation Before delving into the realm of deobfuscation, it’s crucial to grasp the concept of JavaScript obfuscation. At its core, obfuscation is the process of deliberately making code more difficult to understand, often to deter reverse engineering or unauthorized modification. Obfuscated JavaScript typically involves techniques such as minification, mangling, and code transformation, which obscure the original logic and structure of the code while preserving its functionality. The Role of JS Deobfuscator While JavaScript obfuscation enhances security by making code unintelligible to casual observers, it can also pose challenges for developers who need to analyze or modify the code. This is where the JS deobfuscator comes into play. By reversing the obfuscation process, deobfuscation tools help developers regain visibility into the underlying logic of obfuscated JavaScript, enabling them to understand, debug, and modify the code more effectively. Unleashing the Power of JS Deobfuscator 1. Analyzing Obfuscated Code One of the primary functions of a JS deobfuscator is to analyze obfuscated JavaScript code and reconstruct its original structure. By unraveling the obfuscation layers, deobfuscation tools reveal the true nature of the code, making it easier for developers to comprehend and work with. 2. Identifying Patterns and Logic Beyond mere reconstruction, a high-quality JS deobfuscator excels at identifying patterns, logic flows, and critical components within obfuscated code. This capability is invaluable for developers seeking to gain insights into the behavior of complex JavaScript applications and pinpoint potential vulnerabilities or optimizations. 3. Debugging and Testing Another advantage of using a JS deobfuscator is its utility in debugging and testing obfuscated JavaScript code. By deobfuscating the code, developers can more effectively trace execution paths, identify errors, and validate the correctness of their implementations, ultimately enhancing the robustness and reliability of their applications. Choosing the Right JS Deobfuscator With a plethora of deobfuscation tools available in the market, selecting the right one can be daunting. Here are some key considerations to keep in mind: • Accuracy and Reliability: Look for a deobfuscator that consistently produces accurate results and can handle a wide range of obfuscation techniques. • Performance: Choose a tool that offers fast and efficient deobfuscation without compromising on quality. • Compatibility: Ensure that the deobfuscator supports the JavaScript frameworks and environments relevant to your projects. • Ease of Use: Opt for a deobfuscation tool with an intuitive user interface and comprehensive documentation to streamline the deobfuscation process. Conclusion In conclusion, JS deobfuscator plays a vital role in the toolkit of modern web developers, empowering them to unravel the complexities of obfuscated JavaScript code with ease and precision. By leveraging the power of deobfuscation, developers can gain deeper insights into their code, streamline the debugging process, and enhance the overall security and reliability of their web applications. Whether you’re a seasoned developer tackling a legacy codebase or a newcomer grappling with obfuscated scripts, investing in a reliable JS deobfuscator can make all the difference in your development workflow. Unlock the secrets hidden within your JavaScript code and embark on a journey of discovery and innovation with confidence. Leave a Reply Your email address will not be published. Required fields are marked *
__label__pos
0.976277
OtaconEvil [MAP] Easy grounds in 'SF' By OTACON Oct 19th, 2013 226 Never Not a member of Pastebin yet? Sign Up, it unlocks many cool features! 1.     /* 2.         * ## LEASE ATENTAMENTE PARA NO CONVERTIRSE EN LAMMER!!.: :D ## 3.         * 4.         * Estè Simple MAPA esta hecho especialmente para www.forum.sa-mp.com 5.         * NO Publicar estè MAPA en Otros foros de SA-MP y hacerse pasar por el creador del CODE. 6.         * 7.         * Codigo Creado Por OTACON 8.         * 9.         * CREDITOS: 10.         *     OTACON: Realizacion y Idea de creacion del code. 11.         *     TÙ: Modificacion libremente respetando lo mencionado ;). 12.         * 13.         *    NOTA: Menos Creditos para los que me los critican.. JO'PUTAS! :D xD ;) 14.         * 15.         *            Prohibido TOTALMENTE el Robo de Créditos o la 16.         *              Publicación de este MAPA sin Mi Permiso. 17.     */  18.     /* 19.         * ## READ CAREFULLY TO AVOID BECOMING LAMMER!.: :D ## 20.         * 21.         * This simple MAP is made especially for www.forum.sa-mp.com 22.         * DO NOT Post the map in Other SAMP forums and impersonating the creator of the CODE. 23.         * 24.         * Code Created By OTACON 25.         * 26.         * CREDITS: 27.         *     OTACON: Idea Making and code creation. 28.         *     YOUR: Modification freely respecting the above ;). 29.         * 30.         *    NOTE: Less Credits for those who criticize me.. JO'PUTAS! :D xD ;) 31.         * 32.         *                    FULLY spaces Theft Credit or 33.         *             Publication of this MAP without my permission. 34.     */ 35. #include <a_samp> 36. new objetosparque[6]; 37.   38. public OnFilterScriptInit() { 39.     AddPlayerClass(286,-2876.6987,467.7014,4.8745,262.0000,0,0,0,0,0,0); // 40.     objetosparque[0]=CreateObject(9829, -2920.57031, 461.79688, -61.39063,   0.00000, 0.00000, 0.00000); 41.     SetObjectMaterial(objetosparque[0], 4, 10638, "groundbit_sfs", "desgreengrass", -1); 42.     objetosparque[1]=CreateObject(18981, -2900.88843, 464.36179, 3.46780,   0.00000, 90.00000, 0.00000); 43.     SetObjectMaterial(objetosparque[1], 0, 9829, "hrbr_sfw", "fancy_slab128", -1); 44.     objetosparque[2]=CreateObject(18980, -2900.88843, 452.36069, 4.27880,   0.00000, 90.00000, 0.00000); 45.     objetosparque[3]=CreateObject(18980, -2900.88843, 476.36349, 4.27880,   0.00000, 90.00000, 0.00000); 46.     objetosparque[4]=CreateObject(18980, -2888.86426, 464.34180, 4.27680,   0.00000, 90.00000, 90.00000); 47.     objetosparque[5]=CreateObject(18980, -2912.89233, 464.36179, 4.27680,   0.00000, 90.00000, 90.00000); 48.     SetObjectMaterial(objetosparque[2], 0, 9829, "hrbr_sfw", "fancy_slab128", -1); 49.     SetObjectMaterial(objetosparque[3], 0, 9829, "hrbr_sfw", "fancy_slab128", -1); 50.     SetObjectMaterial(objetosparque[4], 0, 9829, "hrbr_sfw", "fancy_slab128", -1); 51.     SetObjectMaterial(objetosparque[5], 0, 9829, "hrbr_sfw", "fancy_slab128", -1); 52.     CreateObject(669, -2914.08789, 433.02759, 4.22530,   0.00000, 0.00000, 0.00000); 53.     CreateObject(669, -2894.44849, 433.04126, 4.22530,   0.00000, 0.00000, 0.00000); 54.     CreateObject(669, -2874.54834, 433.02759, 4.22530,   0.00000, 0.00000, 0.00000); 55.     CreateObject(669, -2874.54834, 493.13760, 4.22530,   0.00000, 0.00000, 0.00000); 56.     CreateObject(669, -2894.44849, 493.13760, 4.22530,   0.00000, 0.00000, 0.00000); 57.     CreateObject(669, -2914.08789, 493.13760, 4.22530,   0.00000, 0.00000, 0.00000); 58.     CreateObject(669, -2884.12891, 452.80161, 4.22530,   0.00000, 0.00000, 0.00000); 59.     CreateObject(669, -2884.12891, 473.02139, 4.22530,   0.00000, 0.00000, 0.00000); 60.     CreateObject(669, -2914.08789, 473.02139, 4.22530,   0.00000, 0.00000, 0.00000); 61.     CreateObject(669, -2914.08789, 452.80161, 4.22530,   0.00000, 0.00000, 0.00000); 62.     CreateObject(672, -2933.71216, 462.96579, 4.84930,   0.00000, 0.00000, 0.00000); 63.     CreateObject(672, -2953.61450, 462.96628, 4.84930,   0.00000, 0.00000, 0.00000); 64.     CreateObject(672, -2973.80420, 462.96579, 4.84930,   0.00000, 0.00000, 0.00000); 65.     CreateObject(672, -2993.89453, 462.96579, 4.84930,   0.00000, 0.00000, 0.00000); 66.     CreateObject(672, -2933.71216, 479.45251, 4.84930,   0.00000, 0.00000, 0.00000); 67.     CreateObject(672, -2953.61450, 479.45251, 4.84930,   0.00000, 0.00000, 0.00000); 68.     CreateObject(672, -2993.87451, 479.45251, 4.84930,   0.00000, 0.00000, 0.00000); 69.     CreateObject(672, -2973.80420, 479.45251, 4.84930,   0.00000, 0.00000, 0.00000); 70.     CreateObject(16061, -2894.35303, 423.27982, 4.00480,   0.00000, 0.00000, 89.00000); 71.     CreateObject(16061, -2894.35303, 503.27161, 4.00480,   0.00000, 0.00000, 89.00000); 72.     CreateObject(647, -2904.70264, 427.36710, 5.29860,   0.00000, 0.00000, 0.00000); 73.     CreateObject(647, -2883.79517, 427.58459, 5.29860,   0.00000, 0.00000, 0.00000); 74.     CreateObject(647, -2869.27930, 422.00034, 5.29860,   0.00000, 0.00000, 0.00000); 75.     CreateObject(647, -2919.36523, 422.01083, 5.29860,   0.00000, 0.00000, 0.00000); 76.     CreateObject(647, -2883.55713, 497.29144, 5.29860,   0.00000, 0.00000, 0.00000); 77.     CreateObject(647, -2904.71045, 499.78302, 5.29860,   0.00000, 0.00000, 0.00000); 78.     CreateObject(647, -2920.90454, 504.99023, 5.29860,   0.00000, 0.00000, 0.00000); 79.     CreateObject(647, -2869.41211, 504.94308, 5.29860,   0.00000, 0.00000, 0.00000); 80.     CreateObject(647, -2923.32861, 442.56207, 5.29860,   0.00000, 0.00000, 0.00000); 81.     CreateObject(647, -2924.03418, 464.15158, 5.29860,   0.00000, 0.00000, 0.00000); 82.     CreateObject(647, -2923.92847, 484.53485, 5.29860,   0.00000, 0.00000, 0.00000); 83.     CreateObject(878, -2984.29956, 459.91611, 5.62400,   0.00000, 0.00000, 90.00000); 84.     CreateObject(878, -2964.55713, 460.40015, 5.62400,   0.00000, 0.00000, 90.00000); 85.     CreateObject(878, -2944.14404, 461.01160, 5.62400,   0.00000, 0.00000, 90.00000); 86.     CreateObject(878, -2963.82837, 481.14417, 5.62400,   0.00000, 0.00000, 90.00000); 87.     CreateObject(878, -2985.42627, 481.27136, 5.62400,   0.00000, 0.00000, 90.00000); 88.     CreateObject(878, -2944.41284, 479.64651, 5.62400,   0.00000, 0.00000, 90.00000); 89.     CreateObject(878, -2916.43750, 433.25436, 5.62400,   0.00000, 0.00000, 90.00000); 90.     CreateObject(878, -2894.03442, 423.42810, 5.62400,   0.00000, 0.00000, 90.00000); 91.     CreateObject(878, -2873.35303, 445.89578, 5.62400,   0.00000, 0.00000, 90.00000); 92.     CreateObject(878, -2870.30493, 480.74231, 5.62400,   0.00000, 0.00000, 90.00000); 93.     CreateObject(878, -2894.36597, 503.86301, 5.62400,   0.00000, 0.00000, 90.00000); 94.     CreateObject(878, -2921.64502, 496.18497, 5.62400,   0.00000, 0.00000, 90.00000); 95.     CreateObject(877, -2903.92773, 482.82761, 5.62400,   0.00000, 0.00000, 90.00000); 96.     CreateObject(877, -2902.57788, 442.48459, 5.62400,   0.00000, 0.00000, 90.00000); 97.     CreateObject(647, -2881.44360, 483.85092, 5.29860,   0.00000, 0.00000, 0.00000); 98.     CreateObject(647, -2885.32471, 442.21909, 5.29860,   0.00000, 0.00000, 0.00000); 99.     CreateObject(705, -2872.77515, 463.49719, 3.78366,   0.00000, 0.00000, 0.00000); 100.     CreateObject(1231, -2993.87451, 471.41321, 6.60600,   0.00000, 0.00000, 90.00000); 101.     CreateObject(1231, -2973.80420, 471.41321, 6.60600,   0.00000, 0.00000, 90.00000); 102.     CreateObject(1231, -2953.61450, 471.41321, 6.60600,   0.00000, 0.00000, 90.00000); 103.     CreateObject(1231, -2933.71216, 471.41321, 6.60600,   0.00000, 0.00000, 90.00000); 104.     CreateObject(1231, -2879.94556, 437.42169, 6.85200,   0.00000, 0.00000, 90.00000); 105.     CreateObject(1231, -2916.91431, 483.75058, 6.60600,   0.00000, 0.00000, 90.00000); 106.     CreateObject(1231, -2916.62964, 443.09692, 6.60600,   0.00000, 0.00000, 90.00000); 107.     CreateObject(1231, -2869.41821, 455.05664, 6.85200,   0.00000, 0.00000, 90.00000); 108.     CreateObject(1231, -2869.34741, 472.39960, 6.85200,   0.00000, 0.00000, 90.00000); 109.     CreateObject(1231, -2880.61157, 490.54260, 6.85200,   0.00000, 0.00000, 90.00000); 110.     return true; 111. } 112. public OnPlayerConnect(playerid) { 113.     RemoveBuildingForPlayer(playerid, 9842, -2920.5703, 461.7969, -61.3906, 0.25); 114.     RemoveBuildingForPlayer(playerid, 9829, -2920.5703, 461.7969, -61.3906, 0.25); 115.     RemoveBuildingForPlayer(playerid, 1232, -2916.6172, 419.7344, 6.5000, 0.25); 116.     RemoveBuildingForPlayer(playerid, 1232, -2880.3828, 419.7344, 6.5000, 0.25); 117.     RemoveBuildingForPlayer(playerid, 1232, -2993.8125, 457.8672, 6.5000, 0.25); 118.     RemoveBuildingForPlayer(playerid, 1232, -2938.4531, 457.5313, 6.5000, 0.25); 119.     RemoveBuildingForPlayer(playerid, 1232, -2961.8906, 484.0156, 6.5000, 0.25); 120.     RemoveBuildingForPlayer(playerid, 1232, -2916.8984, 506.8203, 6.5000, 0.25); 121.     RemoveBuildingForPlayer(playerid, 1232, -2863.3438, 506.8203, 6.5000, 0.25); 122.     RemoveBuildingForPlayer(playerid, 1280, -2911.4219, 422.3516, 4.2891, 0.25); 123.     RemoveBuildingForPlayer(playerid, 1280, -2886.5859, 422.3516, 4.2891, 0.25); 124.     return true; 125. } 126.     /* 127.         * ## LEASE ATENTAMENTE PARA NO CONVERTIRSE EN LAMMER!!.: :D ## 128.         * 129.         * Estè Simple MAPA esta hecho especialmente para www.forum.sa-mp.com 130.         * NO Publicar estè MAPA en Otros foros de SA-MP y hacerse pasar por el creador del CODE. 131.         * 132.         * Codigo Creado Por OTACON 133.         * 134.         * CREDITOS: 135.         *     OTACON: Realizacion y Idea de creacion del code. 136.         *     TÙ: Modificacion libremente respetando lo mencionado ;). 137.         * 138.         *    NOTA: Menos Creditos para los que me los critican.. JO'PUTAS! :D xD ;) 139.         * 140.         *            Prohibido TOTALMENTE el Robo de Créditos o la 141.         *              Publicación de este MAPA sin Mi Permiso. 142.     */  143.     /* 144.         * ## READ CAREFULLY TO AVOID BECOMING LAMMER!.: :D ## 145.         * 146.         * This simple MAP is made especially for www.forum.sa-mp.com 147.         * DO NOT Post the map in Other SAMP forums and impersonating the creator of the CODE. 148.         * 149.         * Code Created By OTACON 150.         * 151.         * CREDITS: 152.         *     OTACON: Idea Making and code creation. 153.         *     YOUR: Modification freely respecting the above ;). 154.         * 155.         *    NOTE: Less Credits for those who criticize me.. JO'PUTAS! :D xD ;) 156.         * 157.         *                    FULLY spaces Theft Credit or 158.         *             Publication of this MAP without my permission. 159.     */ RAW Paste Data
__label__pos
0.610674
blob: b3e854f53d67552e754f8cd9b378ed6e257962a3 [file] [log] [blame] // SPDX-License-Identifier: (GPL-2.0 OR MIT) /* * Driver for Microsemi VSC85xx PHYs * * Author: Bjarni Jonasson <[email protected]> * License: Dual MIT/GPL * Copyright (c) 2021 Microsemi Corporation */ #include <linux/phy.h> #include "mscc_serdes.h" #include "mscc.h" static int pll5g_detune(struct phy_device *phydev) { u32 rd_dat; int ret; rd_dat = vsc85xx_csr_read(phydev, MACRO_CTRL, PHY_S6G_PLL5G_CFG2); rd_dat &= ~PHY_S6G_PLL5G_CFG2_GAIN_MASK; rd_dat |= PHY_S6G_PLL5G_CFG2_ENA_GAIN; ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_PLL5G_CFG2, rd_dat); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int pll5g_tune(struct phy_device *phydev) { u32 rd_dat; int ret; rd_dat = vsc85xx_csr_read(phydev, MACRO_CTRL, PHY_S6G_PLL5G_CFG2); rd_dat &= ~PHY_S6G_PLL5G_CFG2_ENA_GAIN; ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_PLL5G_CFG2, rd_dat); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_pll_cfg_wr(struct phy_device *phydev, const u32 pll_ena_offs, const u32 pll_fsm_ctrl_data, const u32 pll_fsm_ena) { int ret; ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_PLL_CFG, (pll_fsm_ena << PHY_S6G_PLL_ENA_OFFS_POS) | (pll_fsm_ctrl_data << PHY_S6G_PLL_FSM_CTRL_DATA_POS) | (pll_ena_offs << PHY_S6G_PLL_FSM_ENA_POS)); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_common_cfg_wr(struct phy_device *phydev, const u32 sys_rst, const u32 ena_lane, const u32 ena_loop, const u32 qrate, const u32 if_mode, const u32 pwd_tx) { /* ena_loop = 8 for eloop */ /* = 4 for floop */ /* = 2 for iloop */ /* = 1 for ploop */ /* qrate = 1 for SGMII, 0 for QSGMII */ /* if_mode = 1 for SGMII, 3 for QSGMII */ int ret; ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_COMMON_CFG, (sys_rst << PHY_S6G_SYS_RST_POS) | (ena_lane << PHY_S6G_ENA_LANE_POS) | (ena_loop << PHY_S6G_ENA_LOOP_POS) | (qrate << PHY_S6G_QRATE_POS) | (if_mode << PHY_S6G_IF_MODE_POS)); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_des_cfg_wr(struct phy_device *phydev, const u32 des_phy_ctrl, const u32 des_mbtr_ctrl, const u32 des_bw_hyst, const u32 des_bw_ana, const u32 des_cpmd_sel) { u32 reg_val; int ret; /* configurable terms */ reg_val = (des_phy_ctrl << PHY_S6G_DES_PHY_CTRL_POS) | (des_mbtr_ctrl << PHY_S6G_DES_MBTR_CTRL_POS) | (des_cpmd_sel << PHY_S6G_DES_CPMD_SEL_POS) | (des_bw_hyst << PHY_S6G_DES_BW_HYST_POS) | (des_bw_ana << PHY_S6G_DES_BW_ANA_POS); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_DES_CFG, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_ib_cfg0_wr(struct phy_device *phydev, const u32 ib_rtrm_adj, const u32 ib_sig_det_clk_sel, const u32 ib_reg_pat_sel_offset, const u32 ib_cal_ena) { u32 base_val; u32 reg_val; int ret; /* constant terms */ base_val = 0x60a85837; /* configurable terms */ reg_val = base_val | (ib_rtrm_adj << 25) | (ib_sig_det_clk_sel << 16) | (ib_reg_pat_sel_offset << 8) | (ib_cal_ena << 3); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_IB_CFG0, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_ib_cfg1_wr(struct phy_device *phydev, const u32 ib_tjtag, const u32 ib_tsdet, const u32 ib_scaly, const u32 ib_frc_offset, const u32 ib_filt_offset) { u32 ib_filt_val; u32 reg_val = 0; int ret; /* constant terms */ ib_filt_val = 0xe0; /* configurable terms */ reg_val = (ib_tjtag << 17) + (ib_tsdet << 12) + (ib_scaly << 8) + ib_filt_val + (ib_filt_offset << 4) + (ib_frc_offset << 0); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_IB_CFG1, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_ib_cfg2_wr(struct phy_device *phydev, const u32 ib_tinfv, const u32 ib_tcalv, const u32 ib_ureg) { u32 ib_cfg2_val; u32 base_val; int ret; /* constant terms */ base_val = 0x0f878010; /* configurable terms */ ib_cfg2_val = base_val | ((ib_tinfv) << 28) | ((ib_tcalv) << 5) | (ib_ureg << 0); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_IB_CFG2, ib_cfg2_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_ib_cfg3_wr(struct phy_device *phydev, const u32 ib_ini_hp, const u32 ib_ini_mid, const u32 ib_ini_lp, const u32 ib_ini_offset) { u32 reg_val; int ret; reg_val = (ib_ini_hp << 24) + (ib_ini_mid << 16) + (ib_ini_lp << 8) + (ib_ini_offset << 0); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_IB_CFG3, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_ib_cfg4_wr(struct phy_device *phydev, const u32 ib_max_hp, const u32 ib_max_mid, const u32 ib_max_lp, const u32 ib_max_offset) { u32 reg_val; int ret; reg_val = (ib_max_hp << 24) + (ib_max_mid << 16) + (ib_max_lp << 8) + (ib_max_offset << 0); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_IB_CFG4, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_misc_cfg_wr(struct phy_device *phydev, const u32 lane_rst) { int ret; ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_MISC_CFG, lane_rst); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_gp_cfg_wr(struct phy_device *phydev, const u32 gp_cfg_val) { int ret; ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_GP_CFG, gp_cfg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_dft_cfg2_wr(struct phy_device *phydev, const u32 rx_ji_ampl, const u32 rx_step_freq, const u32 rx_ji_ena, const u32 rx_waveform_sel, const u32 rx_freqoff_dir, const u32 rx_freqoff_ena) { u32 reg_val; int ret; /* configurable terms */ reg_val = (rx_ji_ampl << 8) | (rx_step_freq << 4) | (rx_ji_ena << 3) | (rx_waveform_sel << 2) | (rx_freqoff_dir << 1) | rx_freqoff_ena; ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_IB_DFT_CFG2, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } static int vsc85xx_sd6g_dft_cfg0_wr(struct phy_device *phydev, const u32 prbs_sel, const u32 test_mode, const u32 rx_dft_ena) { u32 reg_val; int ret; /* configurable terms */ reg_val = (prbs_sel << 20) | (test_mode << 16) | (rx_dft_ena << 2); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_DFT_CFG0, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } /* Access LCPLL Cfg_0 */ static int vsc85xx_pll5g_cfg0_wr(struct phy_device *phydev, const u32 selbgv820) { u32 base_val; u32 reg_val; int ret; /* constant terms */ base_val = 0x7036f145; /* configurable terms */ reg_val = base_val | (selbgv820 << 23); ret = vsc85xx_csr_write(phydev, MACRO_CTRL, PHY_S6G_PLL5G_CFG0, reg_val); if (ret) dev_err(&phydev->mdio.dev, "%s: write error\n", __func__); return ret; } int vsc85xx_sd6g_config_v2(struct phy_device *phydev) { u32 ib_sig_det_clk_sel_cal = 0; u32 ib_sig_det_clk_sel_mm = 7; u32 pll_fsm_ctrl_data = 60; unsigned long deadline; u32 des_bw_ana_val = 3; u32 ib_tsdet_cal = 16; u32 ib_tsdet_mm = 5; u32 ib_rtrm_adj; u32 if_mode = 1; u32 gp_iter = 5; u32 val32 = 0; u32 qrate = 1; u32 iter; int val = 0; int ret; phy_base_write(phydev, MSCC_EXT_PAGE_ACCESS, MSCC_PHY_PAGE_STANDARD); /* Detune/Unlock LCPLL */ ret = pll5g_detune(phydev); if (ret) return ret; /* 0. Reset RCPLL */ ret = vsc85xx_sd6g_pll_cfg_wr(phydev, 3, pll_fsm_ctrl_data, 0); if (ret) return ret; ret = vsc85xx_sd6g_common_cfg_wr(phydev, 0, 0, 0, qrate, if_mode, 0); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; ret = vsc85xx_sd6g_des_cfg_wr(phydev, 6, 2, 5, des_bw_ana_val, 0); if (ret) return ret; /* 1. Configure sd6g for SGMII prior to sd6g_IB_CAL */ ib_rtrm_adj = 13; ret = vsc85xx_sd6g_ib_cfg0_wr(phydev, ib_rtrm_adj, ib_sig_det_clk_sel_mm, 0, 0); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg1_wr(phydev, 8, ib_tsdet_mm, 15, 0, 1); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg2_wr(phydev, 3, 13, 5); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg3_wr(phydev, 0, 31, 1, 31); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg4_wr(phydev, 63, 63, 2, 63); if (ret) return ret; ret = vsc85xx_sd6g_common_cfg_wr(phydev, 1, 1, 0, qrate, if_mode, 0); if (ret) return ret; ret = vsc85xx_sd6g_misc_cfg_wr(phydev, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 2. Start rcpll_fsm */ ret = vsc85xx_sd6g_pll_cfg_wr(phydev, 3, pll_fsm_ctrl_data, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; deadline = jiffies + msecs_to_jiffies(PROC_CMD_NCOMPLETED_TIMEOUT_MS); do { usleep_range(500, 1000); ret = phy_update_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; val32 = vsc85xx_csr_read(phydev, MACRO_CTRL, PHY_S6G_PLL_STATUS); /* wait for bit 12 to clear */ } while (time_before(jiffies, deadline) && (val32 & BIT(12))); if (val32 & BIT(12)) return -ETIMEDOUT; /* 4. Release digital reset and disable transmitter */ ret = vsc85xx_sd6g_misc_cfg_wr(phydev, 0); if (ret) return ret; ret = vsc85xx_sd6g_common_cfg_wr(phydev, 1, 1, 0, qrate, if_mode, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 5. Apply a frequency offset on RX-side (using internal FoJi logic) */ ret = vsc85xx_sd6g_gp_cfg_wr(phydev, 768); if (ret) return ret; ret = vsc85xx_sd6g_dft_cfg2_wr(phydev, 0, 2, 0, 0, 0, 1); if (ret) return ret; ret = vsc85xx_sd6g_dft_cfg0_wr(phydev, 0, 0, 1); if (ret) return ret; ret = vsc85xx_sd6g_des_cfg_wr(phydev, 6, 2, 5, des_bw_ana_val, 2); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 6. Prepare required settings for IBCAL */ ret = vsc85xx_sd6g_ib_cfg1_wr(phydev, 8, ib_tsdet_cal, 15, 1, 0); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg0_wr(phydev, ib_rtrm_adj, ib_sig_det_clk_sel_cal, 0, 0); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 7. Start IB_CAL */ ret = vsc85xx_sd6g_ib_cfg0_wr(phydev, ib_rtrm_adj, ib_sig_det_clk_sel_cal, 0, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 11 cycles (for ViperA) or 5 cycles (for ViperB & Elise) w/ SW clock */ for (iter = 0; iter < gp_iter; iter++) { /* set gp(0) */ ret = vsc85xx_sd6g_gp_cfg_wr(phydev, 769); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* clear gp(0) */ ret = vsc85xx_sd6g_gp_cfg_wr(phydev, 768); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; } ret = vsc85xx_sd6g_ib_cfg1_wr(phydev, 8, ib_tsdet_cal, 15, 1, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg1_wr(phydev, 8, ib_tsdet_cal, 15, 0, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 8. Wait for IB cal to complete */ deadline = jiffies + msecs_to_jiffies(PROC_CMD_NCOMPLETED_TIMEOUT_MS); do { usleep_range(500, 1000); ret = phy_update_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; val32 = vsc85xx_csr_read(phydev, MACRO_CTRL, PHY_S6G_IB_STATUS0); /* wait for bit 8 to set */ } while (time_before(jiffies, deadline) && (~val32 & BIT(8))); if (~val32 & BIT(8)) return -ETIMEDOUT; /* 9. Restore cfg values for mission mode */ ret = vsc85xx_sd6g_ib_cfg0_wr(phydev, ib_rtrm_adj, ib_sig_det_clk_sel_mm, 0, 1); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg1_wr(phydev, 8, ib_tsdet_mm, 15, 0, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 10. Re-enable transmitter */ ret = vsc85xx_sd6g_common_cfg_wr(phydev, 1, 1, 0, qrate, if_mode, 0); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 11. Disable frequency offset generation (using internal FoJi logic) */ ret = vsc85xx_sd6g_dft_cfg2_wr(phydev, 0, 0, 0, 0, 0, 0); if (ret) return ret; ret = vsc85xx_sd6g_dft_cfg0_wr(phydev, 0, 0, 0); if (ret) return ret; ret = vsc85xx_sd6g_des_cfg_wr(phydev, 6, 2, 5, des_bw_ana_val, 0); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* Tune/Re-lock LCPLL */ ret = pll5g_tune(phydev); if (ret) return ret; /* 12. Configure for Final Configuration and Settings */ /* a. Reset RCPLL */ ret = vsc85xx_sd6g_pll_cfg_wr(phydev, 3, pll_fsm_ctrl_data, 0); if (ret) return ret; ret = vsc85xx_sd6g_common_cfg_wr(phydev, 0, 1, 0, qrate, if_mode, 0); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* b. Configure sd6g for desired operating mode */ phy_base_write(phydev, MSCC_EXT_PAGE_ACCESS, MSCC_PHY_PAGE_EXTENDED_GPIO); ret = phy_base_read(phydev, MSCC_PHY_MAC_CFG_FASTLINK); if ((ret & MAC_CFG_MASK) == MAC_CFG_QSGMII) { /* QSGMII */ pll_fsm_ctrl_data = 120; qrate = 0; if_mode = 3; des_bw_ana_val = 5; val = PROC_CMD_MCB_ACCESS_MAC_CONF | PROC_CMD_RST_CONF_PORT | PROC_CMD_READ_MOD_WRITE_PORT | PROC_CMD_QSGMII_MAC; ret = vsc8584_cmd(phydev, val); if (ret) { dev_err(&phydev->mdio.dev, "%s: QSGMII error: %d\n", __func__, ret); return ret; } phy_base_write(phydev, MSCC_EXT_PAGE_ACCESS, MSCC_PHY_PAGE_STANDARD); } else if ((ret & MAC_CFG_MASK) == MAC_CFG_SGMII) { /* SGMII */ pll_fsm_ctrl_data = 60; qrate = 1; if_mode = 1; des_bw_ana_val = 3; val = PROC_CMD_MCB_ACCESS_MAC_CONF | PROC_CMD_RST_CONF_PORT | PROC_CMD_READ_MOD_WRITE_PORT | PROC_CMD_SGMII_MAC; ret = vsc8584_cmd(phydev, val); if (ret) { dev_err(&phydev->mdio.dev, "%s: SGMII error: %d\n", __func__, ret); return ret; } phy_base_write(phydev, MSCC_EXT_PAGE_ACCESS, MSCC_PHY_PAGE_STANDARD); } else { dev_err(&phydev->mdio.dev, "%s: invalid mac_if: %x\n", __func__, ret); } ret = phy_update_mcb_s6g(phydev, PHY_S6G_LCPLL_CFG, 0); if (ret) return ret; ret = phy_update_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; ret = vsc85xx_pll5g_cfg0_wr(phydev, 4); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_S6G_LCPLL_CFG, 0); if (ret) return ret; ret = vsc85xx_sd6g_des_cfg_wr(phydev, 6, 2, 5, des_bw_ana_val, 0); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg0_wr(phydev, ib_rtrm_adj, ib_sig_det_clk_sel_mm, 0, 1); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg1_wr(phydev, 8, ib_tsdet_mm, 15, 0, 1); if (ret) return ret; ret = vsc85xx_sd6g_common_cfg_wr(phydev, 1, 1, 0, qrate, if_mode, 0); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg2_wr(phydev, 3, 13, 5); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg3_wr(phydev, 0, 31, 1, 31); if (ret) return ret; ret = vsc85xx_sd6g_ib_cfg4_wr(phydev, 63, 63, 2, 63); if (ret) return ret; ret = vsc85xx_sd6g_misc_cfg_wr(phydev, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 13. Start rcpll_fsm */ ret = vsc85xx_sd6g_pll_cfg_wr(phydev, 3, pll_fsm_ctrl_data, 1); if (ret) return ret; ret = phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; /* 14. Wait for PLL cal to complete */ deadline = jiffies + msecs_to_jiffies(PROC_CMD_NCOMPLETED_TIMEOUT_MS); do { usleep_range(500, 1000); ret = phy_update_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); if (ret) return ret; val32 = vsc85xx_csr_read(phydev, MACRO_CTRL, PHY_S6G_PLL_STATUS); /* wait for bit 12 to clear */ } while (time_before(jiffies, deadline) && (val32 & BIT(12))); if (val32 & BIT(12)) return -ETIMEDOUT; /* release lane reset */ ret = vsc85xx_sd6g_misc_cfg_wr(phydev, 0); if (ret) return ret; return phy_commit_mcb_s6g(phydev, PHY_MCB_S6G_CFG, 0); }
__label__pos
0.949534
Loading a dataset by passing a class of trasnforamtions Hi all, I am trying to load STL10 dataset, by passing a class of transformation. My aim is to obtain two agumeneted versions of each image. But when I pass the class as a transformation argument, I got the message that the class is not iterable. I tried to make the class simpler. But I got the same message. Does it mean that we can not pass a class as transformations in loading datasets? Here is a sample of code: color_jitter = transforms.ColorJitter(0.8 , 0.8 , 0.8 , 0.2 ) data_transforms = transforms.Compose([transforms.RandomResizedCrop(size=96), transforms.RandomHorizontalFlip(), transforms.RandomApply([color_jitter],p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor()]) class Trans(object): def __init__(self,transform): self.transform = transform def __cal__(self,sample): xi = self.transform(sample) xj = self.transform(sample) return(xi, xj) dataset =datasets.STL10(’./data’,split = ‘train+unlabeled’, download = True, transform =Trans(data_transforms) ) Any help is appreciated. Best Could you post the complete error message with the stack trace, please? Also, you have a typo in self.__call__ :wink: . Thank you for your answer. The problem was solved. It was just due to the typo in the self.__call__ definition.:slight_smile:
__label__pos
0.977733
MRPT  1.9.9 CPoseRandomSampler.cpp Go to the documentation of this file. 1 /* +------------------------------------------------------------------------+ 2  | Mobile Robot Programming Toolkit (MRPT) | 3  | https://www.mrpt.org/ | 4  | | 5  | Copyright (c) 2005-2019, Individual contributors, see AUTHORS file | 6  | See: https://www.mrpt.org/Authors - All rights reserved. | 7  | Released under BSD License. See: https://www.mrpt.org/License | 8  +------------------------------------------------------------------------+ */ 9  10 #include "poses-precomp.h" // Precompiled headers 11  17 #include <mrpt/poses/CPosePDFSOG.h> 19 #include <mrpt/random.h> 20 #include <Eigen/Dense> 21  22 using namespace mrpt; 23 using namespace mrpt::math; 24 using namespace mrpt::poses; 25  26 using namespace mrpt::random; 27  28 /*--------------------------------------------------------------- 29  Constructor 30  ---------------------------------------------------------------*/ 31 CPoseRandomSampler::CPoseRandomSampler() = default; 32 CPoseRandomSampler::CPoseRandomSampler(const CPoseRandomSampler& o) 33 { 34  *this = o; 35 } 36  37 CPoseRandomSampler& CPoseRandomSampler::operator=(const CPoseRandomSampler& o) 38 { 39  if (&o == this) return *this; 40  m_pdf2D.reset(); 41  m_pdf3D.reset(); 42  if (o.m_pdf2D) m_pdf2D.reset(dynamic_cast<CPosePDF*>(o.m_pdf2D->clone())); 43  if (o.m_pdf3D) m_pdf3D.reset(dynamic_cast<CPose3DPDF*>(o.m_pdf3D->clone())); 44  m_fastdraw_gauss_Z3 = o.m_fastdraw_gauss_Z3; 45  m_fastdraw_gauss_Z6 = o.m_fastdraw_gauss_Z6; 46  m_fastdraw_gauss_M_2D = o.m_fastdraw_gauss_M_2D; 47  m_fastdraw_gauss_M_3D = o.m_fastdraw_gauss_M_3D; 48  return *this; 49 } 50  51 CPoseRandomSampler::CPoseRandomSampler(CPoseRandomSampler&& o) 52  : m_pdf2D(nullptr), m_pdf3D(nullptr) 53 { 54  if (o.m_pdf2D) 55  { 56  m_pdf2D = std::move(o.m_pdf2D); 57  o.m_pdf2D = nullptr; 58  } 59  if (o.m_pdf3D) 60  { 61  m_pdf3D = std::move(o.m_pdf3D); 62  o.m_pdf3D = nullptr; 63  } 64  m_fastdraw_gauss_Z3 = std::move(o.m_fastdraw_gauss_Z3); 65  m_fastdraw_gauss_Z6 = std::move(o.m_fastdraw_gauss_Z6); 66  m_fastdraw_gauss_M_2D = std::move(o.m_fastdraw_gauss_M_2D); 67  m_fastdraw_gauss_M_3D = std::move(o.m_fastdraw_gauss_M_3D); 68 } 70 { 71  if (this == &o) return *this; 72  this->clear(); 73  if (o.m_pdf2D) 74  { 75  m_pdf2D = std::move(o.m_pdf2D); 76  o.m_pdf2D = nullptr; 77  } 78  if (o.m_pdf3D) 79  { 80  m_pdf3D = std::move(o.m_pdf3D); 81  o.m_pdf3D = nullptr; 82  } 83  m_fastdraw_gauss_Z3 = std::move(o.m_fastdraw_gauss_Z3); 84  m_fastdraw_gauss_Z6 = std::move(o.m_fastdraw_gauss_Z6); 85  m_fastdraw_gauss_M_2D = std::move(o.m_fastdraw_gauss_M_2D); 86  m_fastdraw_gauss_M_3D = std::move(o.m_fastdraw_gauss_M_3D); 87  return *this; 88 } 89  90 /*--------------------------------------------------------------- 91  clear 92  ---------------------------------------------------------------*/ 94 { 95  m_pdf2D.reset(); 96  m_pdf3D.reset(); 97 } 98  99 /*--------------------------------------------------------------- 100  setPosePDF 101  ---------------------------------------------------------------*/ 103 { 104  MRPT_START 105  106  clear(); 107  m_pdf2D.reset(dynamic_cast<CPosePDF*>(pdf.clone())); 108  109  // According to the PDF type: 110  if (IS_CLASS(pdf, CPosePDFGaussian)) 111  { 112  const auto& gPdf = dynamic_cast<const CPosePDFGaussian&>(pdf); 113  const CMatrixDouble33& cov = gPdf.cov; 114  115  m_fastdraw_gauss_M_2D = gPdf.mean; 116  117  std::vector<double> eigVals; 119  120  // Scale eigenvectors with eigenvalues: 122  D.setDiagonal(eigVals); 123  D = D.asEigen().array().sqrt().matrix(); 125  } 126  else if (IS_CLASS(pdf, CPosePDFParticles)) 127  { 128  return; // Nothing to prepare. 129  } 130  else 131  { 133  "Unsupported class: %s", m_pdf2D->GetRuntimeClass()->className); 134  } 135  136  MRPT_END 137 } 138  139 /*--------------------------------------------------------------- 140  setPosePDF 141  ---------------------------------------------------------------*/ 143 { 144  MRPT_START 145  146  clear(); 147  m_pdf3D.reset(dynamic_cast<CPose3DPDF*>(pdf.clone())); 148  149  // According to the PDF type: 150  if (IS_CLASS(pdf, CPose3DPDFGaussian)) 151  { 152  const auto& gPdf = dynamic_cast<const CPose3DPDFGaussian&>(pdf); 153  const CMatrixDouble66& cov = gPdf.cov; 154  155  m_fastdraw_gauss_M_3D = gPdf.mean; 156  157  std::vector<double> eigVals; 159  160  // Scale eigenvectors with eigenvalues: 162  D.setDiagonal(eigVals); 163  164  // Scale eigenvectors with eigenvalues: 165  D = D.asEigen().array().sqrt().matrix(); 167  } 168  else if (IS_CLASS(pdf, CPose3DPDFParticles)) 169  { 170  return; // Nothing to prepare. 171  } 172  else 173  { 175  "Unsoported class: %s", m_pdf3D->GetRuntimeClass()->className); 176  } 177  178  MRPT_END 179 } 180  181 /*--------------------------------------------------------------- 182  drawSample 183  ---------------------------------------------------------------*/ 185 { 186  MRPT_START 187  188  if (m_pdf2D) 189  { 190  do_sample_2D(p); 191  } 192  else if (m_pdf3D) 193  { 194  CPose3D q; 195  do_sample_3D(q); 196  p.x(q.x()); 197  p.y(q.y()); 198  p.phi(q.yaw()); 199  } 200  else 201  THROW_EXCEPTION("No associated pdf: setPosePDF must be called first."); 202  203  return p; 204  MRPT_END 205 } 206  207 /*--------------------------------------------------------------- 208  drawSample 209  ---------------------------------------------------------------*/ 211 { 212  MRPT_START 213  214  if (m_pdf2D) 215  { 216  CPose2D q; 217  do_sample_2D(q); 218  p.setFromValues(q.x(), q.y(), 0, q.phi(), 0, 0); 219  } 220  else if (m_pdf3D) 221  { 222  do_sample_3D(p); 223  } 224  else 225  THROW_EXCEPTION("No associated pdf: setPosePDF must be called first."); 226  227  return p; 228  MRPT_END 229 } 230  231 /*--------------------------------------------------------------- 232  do_sample_2D: Sample from a 2D PDF 233  ---------------------------------------------------------------*/ 235 { 236  MRPT_START 237  ASSERT_(m_pdf2D); 238  239  // According to the PDF type: 241  { 242  // ------------------------------ 243  // A single gaussian: 244  // ------------------------------ 245  CVectorDouble rndVector(3); 246  rndVector.setZero(); 247  for (size_t i = 0; i < 3; i++) 248  { 250  for (size_t d = 0; d < 3; d++) 251  rndVector[d] += (m_fastdraw_gauss_Z3(d, i) * rnd); 252  } 253  254  p.x(m_fastdraw_gauss_M_2D.x() + rndVector[0]); 255  p.y(m_fastdraw_gauss_M_2D.y() + rndVector[1]); 256  p.phi(m_fastdraw_gauss_M_2D.phi() + rndVector[2]); 257  p.normalizePhi(); 258  } 259  else if (IS_CLASS(*m_pdf2D, CPosePDFSOG)) 260  { 261  // ------------------------------------- 262  // SOG 263  // ------------------------------------- 264  THROW_EXCEPTION("TODO"); 265  } 266  else if (IS_CLASS(*m_pdf2D, CPosePDFParticles)) 267  { 268  // ------------------------------------- 269  // Particles: just sample as usual 270  // ------------------------------------- 271  const auto& pdf = dynamic_cast<const CPosePDFParticles&>(*m_pdf2D); 272  pdf.drawSingleSample(p); 273  } 274  else 276  "Unsoported class: %s", m_pdf2D->GetRuntimeClass()->className); 277  278  MRPT_END 279 } 280  281 /*--------------------------------------------------------------- 282  do_sample_3D: Sample from a 3D PDF 283  ---------------------------------------------------------------*/ 285 { 286  MRPT_START 287  ASSERT_(m_pdf3D); 288  289  // According to the PDF type: 291  { 292  // ------------------------------ 293  // A single gaussian: 294  // ------------------------------ 295  CVectorDouble rndVector(6); 296  rndVector.setZero(); 297  for (size_t i = 0; i < 6; i++) 298  { 300  for (size_t d = 0; d < 6; d++) 301  rndVector[d] += (m_fastdraw_gauss_Z6(d, i) * rnd); 302  } 303  304  p.setFromValues( 305  m_fastdraw_gauss_M_3D.x() + rndVector[0], 306  m_fastdraw_gauss_M_3D.y() + rndVector[1], 307  m_fastdraw_gauss_M_3D.z() + rndVector[2], 308  m_fastdraw_gauss_M_3D.yaw() + rndVector[3], 309  m_fastdraw_gauss_M_3D.pitch() + rndVector[4], 310  m_fastdraw_gauss_M_3D.roll() + rndVector[5]); 311  } 312  else if (IS_CLASS(*m_pdf3D, CPose3DPDFSOG)) 313  { 314  // ------------------------------------- 315  // SOG 316  // ------------------------------------- 317  THROW_EXCEPTION("TODO"); 318  } 320  { 321  // ------------------------------------- 322  // Particles: just sample as usual 323  // ------------------------------------- 324  const auto& pdf = dynamic_cast<const CPose3DPDFParticles&>(*m_pdf3D); 325  pdf.drawSingleSample(p); 326  } 327  else 329  "Unsoported class: %s", m_pdf3D->GetRuntimeClass()->className); 330  331  MRPT_END 332 } 333  334 /*--------------------------------------------------------------- 335  isPrepared 336  ---------------------------------------------------------------*/ 337 bool CPoseRandomSampler::isPrepared() const { return m_pdf2D || m_pdf3D; } 338 /*--------------------------------------------------------------- 339  getOriginalPDFCov2D 340  ---------------------------------------------------------------*/ 342 { 343  MRPT_START 344  ASSERT_(this->isPrepared()); 345  346  if (m_pdf2D) 347  { 348  m_pdf2D->getCovariance(cov3x3); 349  } 350  else 351  { 352  ASSERT_(m_pdf3D); 353  355  P.copyFrom(*m_pdf3D); 356  cov3x3 = P.cov; 357  } 358  359  MRPT_END 360 } 361  362 /*--------------------------------------------------------------- 363  getOriginalPDFCov3D 364  ---------------------------------------------------------------*/ 366 { 367  MRPT_START 368  ASSERT_(this->isPrepared()); 369  370  if (m_pdf2D) 371  { 373  P.copyFrom(*m_pdf2D); 374  cov6x6 = P.cov; 375  } 376  else 377  { 378  ASSERT_(m_pdf3D); 379  m_pdf3D->getCovariance(cov6x6); 380  } 381  382  MRPT_END 383 } 384  385 /*--------------------------------------------------------------- 386  getSamplingMean2D 387  ---------------------------------------------------------------*/ 389 { 390  MRPT_START 391  ASSERT_(this->isPrepared()); 392  393  if (m_pdf2D) 394  out_mean = m_fastdraw_gauss_M_2D; 395  else 396  out_mean = CPose2D(m_fastdraw_gauss_M_3D); 397  398  return out_mean; 399  MRPT_END 400 } 401  402 /*--------------------------------------------------------------- 403  getSamplingMean3D 404  ---------------------------------------------------------------*/ 406 { 407  MRPT_START 408  ASSERT_(this->isPrepared()); 409  410  if (m_pdf3D) 411  out_mean = m_fastdraw_gauss_M_3D; 412  else 413  out_mean = CPose3D(m_fastdraw_gauss_M_2D); 414  415  return out_mean; 416  MRPT_END 417 } 418  420  mrpt::math::CMatrixDouble& cov3x3) const 421 { 423  this->getOriginalPDFCov2D(M); 424  cov3x3 = mrpt::math::CMatrixDouble(M); 425 } 426  428  mrpt::math::CMatrixDouble& cov6x6) const 429 { 431  this->getOriginalPDFCov3D(M); 432  cov6x6 = mrpt::math::CMatrixDouble(M); 433 } A namespace of pseudo-random numbers generators of diferent distributions. CPose2D & getSamplingMean2D(CPose2D &out_mean) const If the object has been loaded with setPosePDF this method returns the 2D pose mean samples will be dr... void copyFrom(const CPosePDF &o) override Copy operator, translating if necesary (for example, between particles and gaussian representations) ... #define MRPT_START Definition: exceptions.h:241 #define THROW_EXCEPTION(msg) Definition: exceptions.h:67 Declares a class that represents a Probability Density function (PDF) of a 2D pose ... Definition: CPosePDFSOG.h:34 void copyFrom(const CPose3DPDF &o) override Copy operator, translating if necesary (for example, between particles and gaussian representations) ... GLdouble GLdouble GLdouble GLdouble q Definition: glext.h:3727 Declares a class that represents a Probability Density function (PDF) of a 3D(6D) pose ... Definition: CPose3DPDFSOG.h:32 double pitch() const Get the PITCH angle (in radians) Definition: CPose3D.h:552 double yaw() const Get the YAW angle (in radians) Definition: CPose3D.h:546 bool isPrepared() const Return true if samples can be generated, which only requires a previous call to setPosePDF. bool eig_symmetric(Derived &eVecs, std::vector< Scalar > &eVals, bool sorted=true) const Read: eig() mrpt::math::CMatrixDouble33 cov The 3x3 covariance matrix. void getOriginalPDFCov3D(mrpt::math::CMatrixDouble66 &cov6x6) const Retrieves the 6x6 covariance of the original PDF in . void drawSingleSample(CPose2D &outPart) const override Draws a single sample from the distribution (WARNING: weights are assumed to be normalized!) ... #define ASSERT_(f) Defines an assertion mechanism. Definition: exceptions.h:120 This base provides a set of functions for maths stuff. CPose3D & getSamplingMean3D(CPose3D &out_mean) const If the object has been loaded with setPosePDF this method returns the 3D pose mean samples will be dr... void do_sample_3D(CPose3D &p) const Used internally: sample from m_pdf3D. Declares a class that represents a Probability Density function (PDF) of a 2D pose ... void clear() Clear internal pdf. virtual CObject * clone() const =0 Returns a deep copy (clone) of the object, indepently of its class. void setPosePDF(const CPosePDF &pdf) This method must be called to select the PDF from which to draw samples. void getOriginalPDFCov2D(mrpt::math::CMatrixDouble33 &cov3x3) const Retrieves the 3x3 covariance of the original PDF in . void do_sample_2D(CPose2D &p) const Used internally: sample from m_pdf2D. #define IS_CLASS(obj, class_name) True if the given reference to object (derived from mrpt::rtti::CObject) is of the given class... Definition: CObject.h:146 mrpt::math::CMatrixDouble33 m_fastdraw_gauss_Z3 double x() const Common members of all points & poses classes. Definition: CPoseOrPoint.h:143 Declares a class that represents a Probability Density Function (PDF) over a 2D pose (x... void matProductOf_AB(const Derived &A, const Derived &B) this = A*B, with A & B of the same type of this. CMatrixDouble cov(const MATRIX &v) Computes the covariance matrix from a list of samples in an NxM matrix, where each row is a sample... Definition: ops_matrices.h:149 Declares a class that represents a probability density function (pdf) of a 2D pose (x... Definition: CPosePDF.h:38 Classes for 2D/3D geometry representation, both of single values and probability density distribution... double roll() const Get the ROLL angle (in radians) Definition: CPose3D.h:558 mrpt::math::CMatrixDouble66 cov The 6x6 covariance matrix. This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries. void drawSingleSample(CPose3D &outPart) const override Draws a single sample from the distribution (WARNING: weights are assumed to be normalized!) ... A class used to store a 2D pose, including the 2D coordinate point and a heading (phi) angle... Definition: CPose2D.h:39 A class used to store a 3D pose (a 3D translation + a rotation in 3D). Definition: CPose3D.h:85 const double & phi() const Get the phi angle of the 2D pose (in radians) Definition: CPose2D.h:86 #define MRPT_END Definition: exceptions.h:245 CPoseRandomSampler & operator=(const CPoseRandomSampler &o) EIGEN_MAP asEigen() Get as an Eigen-compatible Eigen::Map object. Definition: CMatrixFixed.h:251 Declares a class that represents a Probability Density function (PDF) of a 3D pose ... CPosePDF::Ptr m_pdf2D A local copy of the PDF. CPose2D & drawSample(CPose2D &p) const Generate a new sample from the selected PDF. mrpt::math::CMatrixDouble66 m_fastdraw_gauss_Z6 An efficient generator of random samples drawn from a given 2D (CPosePDF) or 3D (CPose3DPDF) pose pro... #define THROW_EXCEPTION_FMT(_FORMAT_STRING,...) Definition: exceptions.h:69 CRandomGenerator & getRandomGenerator() A static instance of a CRandomGenerator class, for use in single-thread applications. GLfloat GLfloat p Definition: glext.h:6398 Declares a class that represents a Probability Density Function (PDF) of a 3D pose (6D actually)... Definition: CPose3DPDF.h:39 void setDiagonal(const std::size_t N, const Scalar value) Resize to NxN, set all entries to zero, except the main diagonal which is set to value ... Definition: MatrixBase.h:34 Declares a class that represents a Probability Density function (PDF) of a 3D pose. double drawGaussian1D_normalized() Generate a normalized (mean=0, std=1) normally distributed sample. CMatrixDynamic< double > CMatrixDouble Declares a matrix of double numbers (non serializable). CPose3DPDF::Ptr m_pdf3D A local copy of the PDF. Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 4363012a5 Tue Nov 19 10:55:26 2019 +0100 at mar nov 19 11:00:13 CET 2019
__label__pos
0.964342
  Mailinglist Archive: yast-commit (1073 mails) < Previous Next > [yast-commit] r50580 - in /trunk/printer: VERSION package/yast2-printer.changes src/Printerlib.ycp src/overview.ycp src/printingvianetwork.ycp tools/modify_cupsd_conf • From: jsmeix@xxxxxxxxxxxxxxxx • Date: Tue, 02 Sep 2008 14:35:47 -0000 • Message-id: <20080902143547.A5AFA2DF43@xxxxxxxxxxxxxxxx> Author: jsmeix Date: Tue Sep 2 16:35:47 2008 New Revision: 50580 URL: http://svn.opensuse.org/viewcvs/yast?rev=50580&view=rev Log: - The 'Printing via Network'dialog writes the Browsing values to the system (but client-only is not yet implemented). - 2.17.8 Modified: trunk/printer/VERSION trunk/printer/package/yast2-printer.changes trunk/printer/src/Printerlib.ycp trunk/printer/src/overview.ycp trunk/printer/src/printingvianetwork.ycp trunk/printer/tools/modify_cupsd_conf Modified: trunk/printer/VERSION URL: http://svn.opensuse.org/viewcvs/yast/trunk/printer/VERSION?rev=50580&r1=50579&r2=50580&view=diff ============================================================================== --- trunk/printer/VERSION (original) +++ trunk/printer/VERSION Tue Sep 2 16:35:47 2008 @@ -1 +1 @@ -2.17.7 +2.17.8 Modified: trunk/printer/package/yast2-printer.changes URL: http://svn.opensuse.org/viewcvs/yast/trunk/printer/package/yast2-printer.changes?rev=50580&r1=50579&r2=50580&view=diff ============================================================================== --- trunk/printer/package/yast2-printer.changes (original) +++ trunk/printer/package/yast2-printer.changes Tue Sep 2 16:35:47 2008 @@ -1,4 +1,11 @@ ------------------------------------------------------------------- +Tue Sep 2 16:31:57 CEST 2008 - jsmeix@xxxxxxx + +- The 'Printing via Network'dialog writes the Browsing values + to the system (but client-only is not yet implemented). +- 2.17.8 + +------------------------------------------------------------------- Fri Aug 29 14:45:28 CEST 2008 - jsmeix@xxxxxxx - Some code cleanup. Modified: trunk/printer/src/Printerlib.ycp URL: http://svn.opensuse.org/viewcvs/yast/trunk/printer/src/Printerlib.ycp?rev=50580&r1=50579&r2=50580&view=diff ============================================================================== --- trunk/printer/src/Printerlib.ycp (original) +++ trunk/printer/src/Printerlib.ycp Tue Sep 2 16:35:47 2008 @@ -31,6 +31,8 @@ */ global boolean ExecuteBashCommand( string bash_commandline ) { y2milestone( "Executing bash commandline: %1", bash_commandline ); + // Enforce a hopefully sane environment before running the actual command: + bash_commandline = "export PATH='/sbin:/usr/sbin:/usr/bin:/bin' ; export LC_ALL='POSIX' ; export LANG='POSIX' ; umask 022 ; " + bash_commandline; result = (map)SCR::Execute( .target.bash_output, bash_commandline ); if( result["exit"]:9999 != 0 ) { y2warning( "'%1' exit code is: %2", bash_commandline, result["exit"]:9999 ); @@ -66,10 +68,11 @@ } } else - { client_conf_server_name = ""; + { // Use fallback values when the command above failed: + client_conf_server_name = ""; client_only = false; + return false; } - // Ignore when it fails: return true; } @@ -91,7 +94,11 @@ { browsing_on = true; } } - // Ignore when it fails: + else + { // Use fallback value when the command above failed: + browsing_on = true; + return false; + } return true; } @@ -114,9 +121,10 @@ cupsd_conf_browse_allow = toset( splitstring( Printerlib::result["stdout"]:"all", " " ) ); } else - { cupsd_conf_browse_allow = [ "all" ]; + { // Use fallback value when the command above failed: + cupsd_conf_browse_allow = [ "all" ]; + return false; } - // Ignore when it fails: return true; } @@ -125,12 +133,14 @@ global map<string, any> cups_autoconfig = $[]; global void Read() -{ // Determine the 'Browsing [ On | Off ]' value in /etc/cups/cupsd.conf and ignore when it fails: +{ // Determine the 'Browsing [ On | Off ]' value in /etc/cups/cupsd.conf + // and ignore when it fails (i.e. use the fallback value silently): DetermineBrowsing(); // Determine the 'BrowseAllow [ all | none | @LOCAL | IP-address[/netmask] ]' - // values in /etc/cups/cupsd.conf and ignore when it fails: + // values in /etc/cups/cupsd.conf and ignore when it fails (i.e. use the fallback value silently): DetermineBrowseAllow(); - // Determine the 'ServerName' value in /etc/cups/client.conf and ignore when it fails: + // Determine the 'ServerName' value in /etc/cups/client.conf + // and ignore when it fails (i.e. use the fallback value silently): DetermineClientOnly(); // Read cups-autoconfiguration settings: cups_autoconfig = (map<string, any>)SCR::Read(.etc.cups-auto.all); Modified: trunk/printer/src/overview.ycp URL: http://svn.opensuse.org/viewcvs/yast/trunk/printer/src/overview.ycp?rev=50580&r1=50579&r2=50580&view=diff ============================================================================== --- trunk/printer/src/overview.ycp (original) +++ trunk/printer/src/overview.ycp Tue Sep 2 16:35:47 2008 @@ -246,9 +246,7 @@ if (event["EventReason"]:"" == "Activated" && event["ID"]:nil == `add){ // client only - if( Printerlib::client_only - && Printerlib::client_conf_server_name != "localhost" - && Printerlib::client_conf_server_name != "127.0.0.1" ) + if( Printerlib::client_only ) { if( ! Popup::YesNoHeadline( "Disable remote CUPS server setting", "A remote CUPS server setting conflicts with adding a print queue." ) Modified: trunk/printer/src/printingvianetwork.ycp URL: http://svn.opensuse.org/viewcvs/yast/trunk/printer/src/printingvianetwork.ycp?rev=50580&r1=50579&r2=50580&view=diff ============================================================================== --- trunk/printer/src/printingvianetwork.ycp (original) +++ trunk/printer/src/printingvianetwork.ycp Tue Sep 2 16:35:47 2008 @@ -41,39 +41,12 @@ include "printer/helps.ycp"; -boolean something_has_changed = false; -boolean cupsd_restart_required = false; -boolean cupsd_start_required = false; -boolean cupsd_stop_required = false; - -boolean ApplyNetworkPrintingSettings() -{ if( ! something_has_changed ) - { y2milestone( "Nothing changed in 'Printing via Network' dialog." ); - Popup::ShowFeedback( // No title for such a simple feedback message: - "", - // Message of a Popup::ShowFeedback when nothing was changed: - _("Nothing changed.") - ); - sleep( 1000 ); - Popup::ClearFeedback(); - return true; - } - y2milestone( "Writing 'NetworkPrinting' settings to the system." ); - // Nothing implemented yet: - Popup::AnyMessage( // Header of a Popup::AnyMessage when "ApplyNetworkPrintingSettings" is called: - _("Not yet implemented"), - // Body of a Popup::AnyMessage when the "ApplyNetworkPrintingSettings" is called: - _("Writing the settings to the system is not yet implemented.") - ); - return false; -} - term widgetNetworkPrinting = `VBox ( `VStretch(), `Frame ( _("Use CUPS to Print Via Network"), `RadioButtonGroup - ( `id(`browsing_or_client_only_check_boxs), + ( `id(`browsing_or_client_only_check_boxes), `VBox ( `Left ( `RadioButton @@ -101,16 +74,24 @@ `Left ( `ComboBox ( `id(`cupsd_conf_browse_allow_combo_box), + `opt(`notify), _("Usual &General Setting"), - [ `item( `id(`browse_allow_local), "hosts in the local network" ), - `item( `id(`browse_allow_all), "all hosts" ) + [ `item( `id(`browse_allow_all), "all hosts" ), + `item( `id(`browse_allow_local), "hosts in the local network" ), + `item( `id(`browse_allow_specific), "only specific addresses" ), ] ) ), `Left ( `TextEntry ( `id(`cupsd_conf_browse_allow_input), - _("Specific IP Addresses or &Network/Netmask (separated by space)") + _("Optional Specific IP Addresses or &Network/Netmask") + ) + ), + `Left + ( `Label + ( `id(`cupsd_conf_browse_allow_input_label), + _("(each nnn.nnn.nnn.nnn or nnn.nnn.nnn.nnn/mmm.mmm.mmm.mmm separated by one space)") ) ) ) @@ -154,6 +135,11 @@ ) ) ), + `VStretch() + ); + +/* + ), `VStretch(), `Right ( `PushButton @@ -162,15 +148,189 @@ ) ) ); +*/ + +boolean something_has_changed = false; +boolean cupsd_restart_required = false; +boolean cupsd_start_required = false; +boolean cupsd_stop_required = false; +boolean initial_cupsd_conf_browsing_off_radio_button = false; +boolean initial_cupsd_conf_browsing_on_radio_button = false; +any initial_cupsd_conf_browse_allow_combo_box_value = nil; +boolean initial_cupsd_conf_browse_allow_all = false; +boolean initial_cupsd_conf_browse_allow_local = false; +boolean initial_cupsd_conf_browse_allow_specific = false; +string initial_cupsd_conf_browse_allow_input_value = ""; +boolean initial_client_only_radio_button = false; +string initial_client_conf_server_name_input_value = ""; + +boolean ApplyNetworkPrintingSettings() +{ // Get the actual settings and values from the dialog: + any current_radio_button = UI::QueryWidget( `id(`browsing_or_client_only_check_boxes), `CurrentButton ); + any current_browse_allow = UI::QueryWidget( `id(`cupsd_conf_browse_allow_combo_box), `Value ); + string current_browse_allow_input_value = (string)UI::QueryWidget( `id(`cupsd_conf_browse_allow_input), `Value ); + string current_server_name_input_value = (string)UI::QueryWidget( `id(`client_conf_server_name_input), `Value ); + y2milestone( "ApplyNetworkPrintingSettings with\ncurrent_radio_button = '%1'\ncurrent_browse_allow = '%2'\ncurrent_browse_allow_input_value = '%3'\ncurrent_server_name_input_value = '%4'", current_radio_button, current_browse_allow, current_browse_allow_input_value, current_server_name_input_value ); + // Browsing Off: + if( `cupsd_conf_browsing_off_radio_button == current_radio_button ) + { if( initial_cupsd_conf_browsing_off_radio_button ) + { // Nothing has changed: + return true; + } + if( initial_cupsd_conf_browsing_on_radio_button ) + { // It was initially a "Get browsing info" config, + // but now the user has activated the "No browsing info" radio button: + something_has_changed = true; + // Do not change the global "Browsing On/Off" entry in cupsd.conf + // because "Browsing Off" disables also sharing of local printers + // which might be needed by the "Share Printers" dialog. + // Instead set only "BrowseAllow none" in cupsd.conf: + if( ! Printerlib::ExecuteBashCommand( Printerlib::yast_bin_dir + "modify_cupsd_conf BrowseAllow none" ) ) + { Report::Error( // Message of a Report::Error. + // Only a simple message because this error does not happen on a normal system + // (i.e. a system which is not totally broken or totally messed up). + _("Failed to set 'BrowseAllow none' in /etc/cups/cupsd.conf") + ); + return false; + } + return true; + } + if( initial_client_only_radio_button ) + { // Note that initial_client_only_radio_button is only true for a real client-only config + // but not when the server name value for client-only is "localhost" or "127.0.0.1", + // see Printerlib::DetermineClientOnly() and the initNetworkPrinting function below. + // If it is actually a client-only config, + // the user may have only activated the "No browsing info" radio button + // but left the server name value for client-only unchanged: + if( current_server_name_input_value != initial_client_conf_server_name_input_value ) + { something_has_changed = true; + // The user has changed the server name value for client-only + // and afterwards he activated the "No browsing info" radio button. + // This should result a client-only setup with the new server name + // if the new server name is a non-empty string which is also not 'none': + string server_name = deletechars( tolower( current_server_name_input_value ), " " ); + if( "" != server_name + && "none" != server_name + ) + { if( ! Printerlib::ExecuteBashCommand( Printerlib::yast_bin_dir + "cups_client_only " + server_name ) ) + { Report::Error( // Message of a Report::Error + // where %1 will be replaced by the server name. + // Only a simple message because this error does not happen on a normal system + // (i.e. a system which is not totally broken or totally messed up). + sformat( _("Failed to set 'ServerName %1' in /etc/cups/client.conf"), server_name ) + ); + return false; + } + } + else + { // The client-only server name was changed to the empty string or to 'none' + // and afterwards the "No browsing info" radio button was activated. + // This should disable the client-only setup but not start the local cupsd: + if( ! Printerlib::ExecuteBashCommand( Printerlib::yast_bin_dir + "cups_client_only none" ) ) + { Report::Error( // Message of a Report::Error. + // Only a simple message because this error does not happen on a normal system + // (i.e. a system which is not totally broken or totally messed up). + _("Failed to remove the 'ServerName' entry in /etc/cups/client.conf") + ); + return false; + } + } + } + } + // The above change to the client-only setup was successful or + // the user has not changed the server name value for client-only + // and afterwards he activated the "No browsing info" radio button. + // The latter case should also leave the current client-only setup as is: + return true; + } + // Browsing On: + if( `cupsd_conf_browsing_on_radio_button == current_radio_button ) + { if( initial_cupsd_conf_browsing_off_radio_button ) + { // It was initially a "No browsing info" config, + // but now the user has activated the "Get browsing info" radio button: + something_has_changed = true; + } + if( initial_cupsd_conf_browsing_on_radio_button ) + { // It was initially a "Get browsing info" config, + // but now the user may have changed from which hosts browsing info is accepted: + if( current_browse_allow != initial_cupsd_conf_browse_allow_combo_box_value + || current_browse_allow_input_value != initial_cupsd_conf_browse_allow_input_value + ) + { something_has_changed = true; + } + else + { // Nothing has changed: + return true; + } + } + if( initial_client_only_radio_button ) + { // It was initially a client-only config, + // but now the user has activated the "Get browsing info" radio button: + something_has_changed = true; + } + if( something_has_changed ) + { string browse_allow_value = current_browse_allow_input_value; + if( `browse_allow_all == current_browse_allow ) + { // If browsing info is accepted from all hosts, it is actually useless + // to additionally accept it from specific IPs or networks + // but nevertheless the specific addresses are also set in cupsd.conf + // because I do not want to ignore what the user has entered. + // E.g. the user may like to accept browsing info from some specific addresses + // while he plays around with the predefined settings from the combo box: + browse_allow_value = browse_allow_value + " all"; + } + if( `browse_allow_local == current_browse_allow ) + { browse_allow_value = browse_allow_value + " @LOCAL"; + } + if( "" != filterchars( browse_allow_value, " " ) ) + { if( ! Printerlib::ExecuteBashCommand( Printerlib::yast_bin_dir + "modify_cupsd_conf Browsing On" ) ) + { Report::Error( // Message of a Report::Error. + // Only a simple message because this error does not happen on a normal system + // (i.e. a system which is not totally broken or totally messed up). + _("Failed to set 'Browsing On' in /etc/cups/cupsd.conf") + ); + return false; + } + if( ! Printerlib::ExecuteBashCommand( Printerlib::yast_bin_dir + + "modify_cupsd_conf BrowseAllow '" + + browse_allow_value + + "'" + ) + ) + { Report::Error( // Message of a Report::Error + // where %1 will be replaced by the values for BrowseAllow. + // Only a simple message because this error does not happen on a normal system + // (i.e. a system which is not totally broken or totally messed up). + sformat( _("Failed to set BrowseAllow value(s) '%1' in /etc/cups/cupsd.conf"), + browse_allow_value + ) + ); + return false; + } + } + } + // Exit successfully by default and as fallback: + return true; + } + // Client-only: + if( `client_only_radio_button == current_radio_button ) + { // Exit successfully by default and as fallback: + return true; + } + // Exit successfully by default and as fallback: + return true; +} void initNetworkPrinting( string key ) { y2milestone( "entering initNetworkPrinting with key '%1'", key ); - // Determine the 'Browsing [ On | Off ]' value in /etc/cups/cupsd.conf and ignore when it fails: + // Determine the 'Browsing [ On | Off ]' value in /etc/cups/cupsd.conf + // and ignore when it fails (i.e. use the fallback value silently): Printerlib::DetermineBrowsing(); // Determine the 'BrowseAllow [ all | none | @LOCAL | IP-address[/netmask] ]' - // values in /etc/cups/cupsd.conf and ignore when it fails: + // values in /etc/cups/cupsd.conf and ignore when it fails (i.e. use the fallback value silently): Printerlib::DetermineBrowseAllow(); - // Determine the 'ServerName' value in /etc/cups/client.conf and ignore when it fails: + // Determine the 'ServerName' value in /etc/cups/client.conf + // and ignore when it fails (i.e. use the fallback value silently): Printerlib::DetermineClientOnly(); // Have all widgets disabled initially // but nevertheless fill in the values of the current settings in the system: @@ -181,11 +341,18 @@ // When by accident "all" and "@LOCAL" were set as BrowseAllow values, // the "@LOCAL" entry is preselected in cupsd_conf_browse_allow_combo_box // because this is the more secure setting: + initial_cupsd_conf_browse_allow_specific = true; + initial_cupsd_conf_browse_allow_combo_box_value = `browse_allow_specific; + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Value, `id(`browse_allow_specific) ); if( contains( Printerlib::cupsd_conf_browse_allow, "all" ) ) - { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Value, `id(`browse_allow_all) ); + { initial_cupsd_conf_browse_allow_all = true; + initial_cupsd_conf_browse_allow_combo_box_value = `browse_allow_all; + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Value, `id(`browse_allow_all) ); } if( contains( Printerlib::cupsd_conf_browse_allow, "@LOCAL" ) ) - { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Value, `id(`browse_allow_local) ); + { initial_cupsd_conf_browse_allow_local = true; + initial_cupsd_conf_browse_allow_combo_box_value = `browse_allow_local; + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Value, `id(`browse_allow_local) ); } UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, false ); // The preset entry in cupsd_conf_browse_allow_input field @@ -195,7 +362,7 @@ // is implicitely done via cupsd_conf_browsing_off_radio_button: string cupsd_conf_browse_allow_input_value = mergestring( filter( string value, Printerlib::cupsd_conf_browse_allow, - { value = tolower( value ) ; + { value = tolower( value ); return( "all" != value && "@local" != value && "none" != value @@ -204,9 +371,12 @@ ), " " ); + initial_cupsd_conf_browse_allow_input_value = cupsd_conf_browse_allow_input_value; UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Value, cupsd_conf_browse_allow_input_value ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input_label), `Enabled, false ); UI::ChangeWidget( `id(`client_only_radio_button), `Value, false ); UI::ChangeWidget( `id(`client_conf_server_name_input), `Enabled, false ); + initial_client_conf_server_name_input_value = Printerlib::client_conf_server_name; UI::ChangeWidget( `id(`client_conf_server_name_input), `Value, Printerlib::client_conf_server_name ); UI::ChangeWidget( `id(`test_client_conf_server), `Enabled, false ); UI::ChangeWidget( `id(`connection_wizard), `Enabled, false ); @@ -215,7 +385,8 @@ // but there is also an active ServerName (!="localhost") in /etc/cups/client.conf // have only the client-only widgets avtivated because client-only has topmost priority: if( Printerlib::client_only ) - { UI::ChangeWidget( `id(`client_only_radio_button), `Value, true ); + { initial_client_only_radio_button = true; + UI::ChangeWidget( `id(`client_only_radio_button), `Value, true ); UI::ChangeWidget( `id(`client_conf_server_name_input), `Enabled, true ); UI::ChangeWidget( `id(`test_client_conf_server), `Enabled, true ); } @@ -225,13 +396,16 @@ if( Printerlib::browsing_on && ! contains( Printerlib::cupsd_conf_browse_allow, "none" ) ) - { UI::ChangeWidget( `id(`cupsd_conf_browsing_on_radio_button), `Value, true ); + { initial_cupsd_conf_browsing_on_radio_button = true; + UI::ChangeWidget( `id(`cupsd_conf_browsing_on_radio_button), `Value, true ); UI::ChangeWidget( `id(`cupsd_conf_browse_allow_label), `Enabled, true ); UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Enabled, true ); UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, true ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input_label), `Enabled, true ); } else - { UI::ChangeWidget( `id(`cupsd_conf_browsing_off_radio_button), `Value, true ); + { initial_cupsd_conf_browsing_off_radio_button = true; + UI::ChangeWidget( `id(`cupsd_conf_browsing_off_radio_button), `Value, true ); } } y2milestone( "leaving initNetworkPrinting" ); @@ -240,26 +414,41 @@ symbol handleNetworkPrinting( string key, map event ) { y2milestone( "entering handleNetworkPrinting with key '%1'\nand event '%2'", key, event ); if( "ValueChanged" == event["EventReason"]:"" ) - { if( `cupsd_conf_browsing_on_radio_button == event["ID"]:nil ) - { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_label), `Enabled, true ); - UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Enabled, true ); - UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, true ); + { if( `cupsd_conf_browsing_off_radio_button == event["ID"]:nil ) + { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_label), `Enabled, false ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Enabled, false ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, false ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input_label), `Enabled, false ); UI::ChangeWidget( `id(`client_conf_server_name_input), `Enabled, false ); UI::ChangeWidget( `id(`test_client_conf_server), `Enabled, false ); UI::ChangeWidget( `id(`connection_wizard), `Enabled, true ); } - if( `cupsd_conf_browsing_off_radio_button == event["ID"]:nil ) - { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_label), `Enabled, false ); - UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Enabled, false ); - UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, false ); + if( `cupsd_conf_browsing_on_radio_button == event["ID"]:nil ) + { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_label), `Enabled, true ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Enabled, true ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, true ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input_label), `Enabled, true ); UI::ChangeWidget( `id(`client_conf_server_name_input), `Enabled, false ); UI::ChangeWidget( `id(`test_client_conf_server), `Enabled, false ); UI::ChangeWidget( `id(`connection_wizard), `Enabled, true ); } + if( `cupsd_conf_browse_allow_combo_box == event["ID"]:nil ) + { if( `browse_allow_all == UI::QueryWidget( `id(`cupsd_conf_browse_allow_combo_box), `Value ) ) + { // If browsing info is accepted from all hosts, + // it is useless to additionally accept it from specific IPs or networks: + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, false ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input_label), `Enabled, false ); + } + else + { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, true ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input_label), `Enabled, true ); + } + } if( `client_only_radio_button == event["ID"]:nil ) { UI::ChangeWidget( `id(`cupsd_conf_browse_allow_label), `Enabled, false ); UI::ChangeWidget( `id(`cupsd_conf_browse_allow_combo_box), `Enabled, false ); UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input), `Enabled, false ); + UI::ChangeWidget( `id(`cupsd_conf_browse_allow_input_label), `Enabled, false ); UI::ChangeWidget( `id(`client_conf_server_name_input), `Enabled, true ); UI::ChangeWidget( `id(`test_client_conf_server), `Enabled, true ); UI::ChangeWidget( `id(`connection_wizard), `Enabled, false ); @@ -293,7 +482,18 @@ _("Failed to apply the settings to the system.") ); } + if( ! something_has_changed ) + { y2milestone( "Nothing changed in 'Printing via Network' dialog." ); + Popup::ShowFeedback( // No title for such a simple feedback message: + "", + // Message of a Popup::ShowFeedback when nothing was changed: + _("Nothing changed.") + ); + sleep( 1000 ); + Popup::ClearFeedback(); + } y2milestone( "leaving storeNetworkPrinting" ); + return nil; } Modified: trunk/printer/tools/modify_cupsd_conf URL: http://svn.opensuse.org/viewcvs/yast/trunk/printer/tools/modify_cupsd_conf?rev=50580&r1=50579&r2=50580&view=diff ============================================================================== --- trunk/printer/tools/modify_cupsd_conf (original) +++ trunk/printer/tools/modify_cupsd_conf Tue Sep 2 16:35:47 2008 @@ -21,12 +21,12 @@ echo "E.g.: BrowseAllow '@LOCAL 192.168.100.1 192.168.200.0/255.255.255.0'" 1>&2 echo "There is a strict syntax for keywords and values:" 1>&2 echo "Case matters." 1>&2 - echo "Neither leading nor trailing nor in-between spaces are allowed." 1>&2 - echo "Multiple values for a keyword must be separated by exactly one space." 1>&2 + echo "Multiple values for a keyword must be separated by space." 1>&2 exit 1 fi -VALUE="$2" +# Remove duplicates (ignore case) and remove duplicate, leading and trailing spaces: +VALUE="$( for V in $2 ; do echo $V ; done | sort -b -f -u | tr -s '[:space:]' ' ' | sed -e 's/ *$//' )" CUPSDCONF="/etc/cups/cupsd.conf" if ! test -r $CUPSDCONF -a -w $CUPSDCONF -- To unsubscribe, e-mail: yast-commit+unsubscribe@xxxxxxxxxxxx For additional commands, e-mail: yast-commit+help@xxxxxxxxxxxx < Previous Next > This Thread • No further messages
__label__pos
0.985209
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required. Sign up Here's how it works: 1. Anybody can ask a question 2. Anybody can answer 3. The best answers are voted up and rise to the top Today I read the Blue Eyes puzzle here. I also read the solution which I find quite interesting. But there are three follow up questions which I don't know the answer to: 1. What is the quantified piece of information that the Guru provides that each person did not already have? 2. Each person knows, from the beginning, that there are no less than 99 blue-eyed people on the island. How, then, is considering the 1 and 2-person cases relevant, if they can all rule them out immediately as possibilities? 3. Why do they have to wait 99 nights if, on the first 98 or so of these nights, they're simply verifying something that they already know? Can someone explain? EDIT: Most of the answers seem to concentrate on question 1, which, I guess, I understand partly, but I'm also feeling confused (because of different answers). Also can someone share their views on questions 2 and 3? share|cite|improve this question 24   It's a good puzzle, but certainly does not qualify as the hardest logic puzzle in the world. – Ittay Weiss Sep 10 '13 at 10:03 6   A useful reference is en.wikipedia.org/wiki/Common_knowledge_(logic) – Andreas Caranti Sep 10 '13 at 10:47 1   I've read the verions with the monks and the gnomes before. – Raskolnikov Sep 10 '13 at 10:55 7   Previously: Is there no solution to the “hardest” puzzle? – Rahul Sep 10 '13 at 15:08 15   Maybe after 99 answers, someone will post a correct and comprehensible solution. – nbubis Sep 10 '13 at 18:47 24 Answers 24 Here's the story of one blue-eyed islander. The Guru said she saw someone with blue eyes. He looked around and thought "Hey, I don't see anyone with blue eyes. I guess she means me." And so he left right away. Here's the story of two blue-eyed islanders. The Guru said she saw someone with blue eyes. They looked around and thought "OK, I see someone with blue eyes. I guess she means him," and they stayed. But the next day came, and they thought "Hey, that blue-eyed guy didn't figure it out. I guess he must have seen someone else with blue eyes, but I don't see anyone else with blue eyes. I guess that means me." And so they left together on the second day. Here's the story of three blue-eyed islanders. The Guru said she saw someone with blue eyes. They looked around and thought "OK, I see two people with blue eyes. I guess she means one of them," and they stayed. A day passed, and nobody left, and they thought to themselves "OK, this is the day those two guys figure it out." But another day passed, and nobody left. The blue-eyed people thought "Wait; those two guys didn't figure it out yet. I guess they must have seen another person with blue eyes, but I don't see anyone else with blue eyes. I guess that means me." And so they left together on the third day. Here's the story of four blue-eyed islanders. The Guru said she saw someone with blue eyes. They looked around and thought "OK, I see three people with blue eyes. I guess she means one of them," and they stayed. A day passed, and nobody left, but they were not worried; they knew it would take a couple of days. A second day passed, and nobody left, and they all thought to themselves "OK, this is the day those three guys figure it out." But another day passed, and nobody left. The blue-eyed people thought "Wait; those three guys didn't figure it out yet. I guess they all must have seen another person with blue eyes, but I don't see anyone else with blue eyes. I guess that means me." And so they left together on the fourth day. ...and this is why they have to wait the full 99 days. It's not important that the Guru can see someone with blue eyes, unless there's only one islander. What's really important is that, given that the Guru can see someone with blue eyes, "those blue-eyed guys" should be able to figure it out among themselves, and that takes time. It's only when they can't do this that it becomes clear you must have blue eyes too. share|cite|improve this answer 6   But WHY doesn't brown eye leave after 100 days as well? Each islander sees at least 99 brown eyes, KNOWING that each of those knows that there are at least 98 brown eyes in the group? Every single brown eyed person knows that there are 99 or 100 brown eyes in the group, so that is common knowledge as well. – SinisterMJ Sep 10 '13 at 16:31 18   Because the brown-eyes see the blue-eyes leaving the island, and think "Hey, those blue-eyed guys figured it out. I guess that means there aren't any others, so my eyes aren't blue. But what color are they? There are lots of colors; just look at the Guru's green eyes. I still don't know." And so they stayed. – The Spooniest Sep 10 '13 at 16:45 16   This seems to me to be an explanation of the answer to the puzzle, but not an answer to the three enumerated questions the asker is asking about. – Kevin Sep 10 '13 at 17:39 3   I was attempting to illustrate the answers to the three questions. In the first question, the Guru doesn't give the islanders any new information: the new information comes from the fact that, given what the Guru said, they still can't figure it out. The answer to the second question is that the 1-person and 2-person cases establish how to determine if you have blue eyes (though you need a 3-person case to really get it going). These then go on to the third question: you need the full 99 days because that's how long it takes for people to figure it out if you don't have blue eyes. – The Spooniest Sep 10 '13 at 18:10 1   @TheSpooniest: Saying that the Guru did not give new information and that the new information came from the fact that, given what the Guru said, they still can't figure it out is self-contradictory. If there were no new information, then there would be nothing new to figure out, and the fact that indeed nothing was figured out would not be new information either. The speaking of the Guru does provide new information, but that information does not have to be contained in the message itself. – Marc van Leeuwen Sep 14 '13 at 15:33 I'll take up the challenge in nbubis's comment (even though there are not yet $99$ answers), and try to give a precise answer. And since this is a mathematics rather than a philosophy site, I'll try to use some formulas to describe what is going on. As has been noted, the technical notion of common knowledge is important here. Clearly there is in this problem need to distinguish between (the truth of) a proposition and the fact that some person knows this proposition to hold. In fact there is no need distinguish individuals (and actually only the blue-eyed ones really matter), and it suffices to state when everybody (in the problem) knows a proposition. So if $P$ is any proposition, I will note $E(P)$ a new proposition which states that everybody knows $P$ to be true. Since everybody applies logic flawlessly $E(P)$ implies $P$, but $P$ does not imply $E(P)$. And $E(P)$ does not imply $E(E(P))$ either, which is yet a new proposition; it will be convenient to abbreviate it $E^2(P)$, and define $E^n(P)$ similarly for all $n\in\Bbb N$. Finally some things (like the general state of affairs on the island, including the logico-compulsive behaviour of its inhabitants) are common knowledge; I will write $C(P)$ for $\forall n\in\Bbb N:E^n(P)$. Let $n$ denote the number of blue-eyed inhabitants. Now for instance according to the problem statement $n=100$ is true, but $E(n=100)$ is false; in fact none of the inhabitants know that $n=100$. But on the other hand $E(99\leq n\leq 101)$ is true (all inhabitants know that $99\leq n\leq 101$, even though the way they know this differs). I'll focus on lower bounds; while $E^2(n\geq99)$ is false (while everybody knows that $n\geq99$ holds, the blue-eyed inhabitants don't know that the other blue-eyed ones know this), $E^2(n\geq98)$ does hold. Similarly for all $i$ one has $E^i(n\geq100-i)$ but not $E^i(n>100-i)$. The new information provided by the public statement of the Guru is $C(n>0)$; this implies $E^i(n>0)$ for all$~i$, of which the instance relevant to the problem is $E^{100}(n>0)$, which was not previously true. While this points to the key factor in the explanation of the riddle, it is somewhat more challenging to describe in detail what happens with the state of knowledge during the $100$ days before the blue-eyes finally leave the island. For that I will denote by $L(i)$ the statement "on night$~i$, some islanders leave". By the problem statement it is always common knowledge when this happens, but I will still write $C(L(i))$ or $C(\lnot L(i))$ to emphasize this common-knowledge status. The problem statement gives us the following fact, which is in fact common knowledge: For any $i\geq0$ and $k>0$, one has $n=k\land C(\lnot L(i))\land E(n\geq k)\to C(L(i+1))$.$\quad(*)$ In words, if $n$ is actually $k$, and on some day no islanders have left (yet), and everybody knows that $n\geq k$, then some islanders will leave the next night. This is because the $k>0$ blue-eyed islanders see $k-1$ others, and know that there must be at least $k$ of them. The following is true, and (therefore, as its proof is based on logic only) common knowledge: Lemma. For all $l,k\in\Bbb N$ one has $E^{l+k}(n>0)\land C(\forall i\leq k:\lnot L(i))\to E^l(n>k)$. This states informally that with sufficiently general knowledge (i.e., a sufficient power of $E$ applied to it) of the fact that $n>0$, it will after $k$ successive nights of nobody leaving be clear to all that $n>k$, but this new fact will have lost $k$ of its levels of $E(\cdot)$. One could simplify the lemma and its proof considerably by replacing the powers of $E$ by $C$, and given that the Guru indeed provides $C(n>0)$, this would suffice to explain what actually happens. However the refined statement is helpful in understanding for instance why $E^{99}(n>0)$, which is true without the Guru speaking, will not suffice to bring anybody into action. I admit that the lemma does not very well express the temporal element of the problem; it implicitly supposes that the information contained in its hypothesis was available before $(*)$ had the first occasion to be applied, i.e., before night$~1$ (but not before night$~0$, as $C(\lnot L(0))$ represents the given initial state). Proof by induction on $k$, uniformly in $l$. For $k=0$ the conclusion is among the hypotheses; there is nothing to prove. Now assume the statement for $k$, and also the hypotheses $E^{l+k+1}(n>0)\land C(\forall i\leq k+1:\lnot L(i))$ of the statement for $k+1$ in place of $k$. The second part of the hyposthesis implies the weaker $C(\forall i\leq k:\lnot L(i))$, so we can apply the induction hypothesis with $l+1$ in place of $l$, and get its conclusion that $E^{l+1}(n>k)$. We instantiate $(*)$ with $(i,k):=(k,k+1)$, giving $$ n=k+1\land C(\lnot L(k))\land E(n\geq k+1)\to C(L(k+1)), $$ which implies (because $C(\lnot L(k+1))\implies \lnot L(k+1)\implies\lnot C(L(k+1))$) $$ C(\lnot L(k))\land E(n>k)\land C(\lnot L(k+1))\to n\neq k+1. $$ If $H$ is the hypothesis of this last statement, we actually know $E^l(H)$ (from our assumptions and the conclusion of applying our induction hypothesis). This allows us to conclude $E^l(n\neq k+1)$, which together with $E^l(n>k)$ gives $E^l(n>k+1)$, completing the proof. Now to the detailed description of what happens; our $100$ blue-eyes wait until they know that $n\geq100$ before $(*)$ forces them to leave. The lemma for $l=1$ and $k=99$ says this will happen provided $E^{100}(n>0)$ holds and $\forall i\leq99:C(\lnot L(i))$. Our Guru provides $C(n>0)$ and hence $E^{100}(n>0)$, and $C(\lnot L(0))$ holds from the problem statement. One still needs to wait for the $99$ other instances of $C(\lnot L(i))$ to provide the prerequisite facts for action. Summarising, one has the following answers to the questions. $1$. What is the quantified piece of information that the Guru provides that each person did not already have? This is $C(n>0)$, and it is its instance $E^{100}(n>0)$ that is really new information, and necessary for any action to take place (higher powers are also new information, but $E^{100}(n>0)$ alone gets things moving). Note that this requires the statement of the Guru be public (giving the information separately to individual inhabitants would have no effect; indeed it is not new information to them), and moreover the fact that it is public must be public (a television broadcast would not suffice if the inhabitants could have some doubt about whether everybody was watching), and this again must be known to everybody, and so forth $100$ levels deep. (One really needs a very strong problem statement to ensure this. If any inhabitant had a doubt whether another inhabitant might maybe have some doubt whether ... some inhabitant was really paying attention to the Guru, the logic would fail.) So there is genuinely new information in the making of the statement by the Guru, but it is not contained in the message she brings itself, but in the fact that it causes that (everybody is aware that)$^{100}$ there are people with blue eyes. $2$. Each person knows, from the beginning, that there are no less than $99$ blue-eyed people on the island. How, then, is considering the $1$ and $2$-person cases relevant, if they can all rule them out immediately as possibilities? While everyone knows that say $n>10$, wrapping it in a sufficient number of applications of $E(\cdot)$ makes it untrue. It is these wrapped-up statements that play a role in the reasoning. $3$. Why do they have to wait $99$ nights if, on the first $98$ or so of these nights, they're simply verifying something that they already know? Every night brings its new information, namely $C(\lnot L(i))$. While most of the times $\lnot L(i)$ itself was already known to everyone, the fact that it becomes common knowledge is genuine new information, and again this is essential for the problem. Final remark. I note that I have used the rule that if $P\to Q$ holds, then $E^l(P)$ implies $E^l(Q)$. This might seem suspicious, as $E$ does not commute with all logical connectives, notably $E(P\lor Q)$ does not imply $E(P)\lor E(Q)$. Although I am not aware of all rules of the formalism, the one I applied is intuitively valid, by the "infallibly logical" nature of the inhabitants: if $P$ in fact implies $Q$, this will not escape their attention, and anyone who in addition knows $P$ to hold will therefore also know $Q$ to hold; in particular if everyone knows $P$ then they will also all know$~Q$. share|cite|improve this answer 3   Imagine the Guru instead said: "Ask me any question you like". Someone asks "True or false, are their any blue-eyed people on this island?" Before the Guru answers, everybody knows what the answer will be (I think?). Does that mean that the useful information becomes available just by asking the right question!? If the Guru was struck down by lightning just before answering the question, would the blue-eyed people still leave after 100 nights? Like this: "The Guru was going to answer honestly. The answer would have been True, if she had survived. So we will all pretend she said "True" – Aaron McDaid Oct 26 '14 at 20:26 3   @AaronMcDaid: No. As I said in several places, it is not the information given itself, but the fact that everyone is aware that this becomes public knowledge that counts. By killing the Guru before she can speak, this extra information is not given, and nothing changes. It is similar to nobody leaving the first night: everyone knows that it will happen, but it still has to actually happen (in a public way) in order to provide new information. – Marc van Leeuwen Nov 29 '14 at 10:11      Would it be sufficient for all the islanders to gather around in a circle (where it is obvious that everyone can hear what is being said), and for one of the blue-eyed people to declare that $n > 0$? If not, why, and would it be any different if the declarer were brown-eyed? – Tony May 6 '15 at 1:02      @Tony: (1) that would be a different problem, but (2) that scenario would violate the explicitly stated and essential hypothesis that the islanders cannot communicate (and certainly not about eye colour) among each other. So it is rather pointless to even think about that problem. – Marc van Leeuwen May 7 '15 at 4:46 I think the answer to Question 1 is that after the Guru has spoken they all know that they all know that they all know that they all know that (repeat as many times as you like) someone has blue eyes. Previously they did not know that, and the statement is only true when it contains at most 99 "they all know that"s. share|cite|improve this answer 8   That's true, but it doesn't contradict what I wrote! – Derek Holt Sep 10 '13 at 12:16 6   @Keinstein, It is true that the islanders know both of those things. But those two facts alone are not sufficient to qualify as common knowledge. They need to know: "1) there are blue eyed people on the island. 2) Everyone is aware of fact 1. 3) Everyone is aware of fact 2. 4) Everyone is aware of fact 3... X) everyone is aware of fact X-1." for an X of any size. Prior to the guru's statement, each islander only knows facts 1 through N, which falls infinitely short of qualifying as common knowledge. – Kevin Sep 10 '13 at 12:18 5   @Keinstein I disagree. I have answered Question 1, by specifying something that they all knew immediately after the Guru spoke that they did not know before he spoke. – Derek Holt Sep 10 '13 at 13:25 2   @Keinstein: suppose there were 3 people, not 99. Then everybody already knew that “(1): at least one person has blue eyes”, and that “(2): everybody knows fact (1)”, but they didn’t already know that “(3): everybody knows fact (2)”. This statement (3) is the new knowledge the guru gives. Similarly, in the case with 99 people, the 99th fact in this series is the new information the guru gives. – Peter LeFanu Lumsdaine Sep 10 '13 at 16:33 6   @Songo It isn't common knowledge that the remaining people all have brown eyes; I believe it's only common knowledge that they do not have blue eyes. Of course, if every islander knew they had either blue or brown eyes, then I think the answer is yes, but otherwise, no. – Andrew D Sep 10 '13 at 17:43 The guru starts the doomsday clock. Before the guru speaks, there is no "day 1". Without the common reference time, every blue eyed person (BEP) lives happily with the knowledge that there must be either 99 or 100 BEPS. But there is no way to decide which is true. The common reference time is the key to the apparent paradox. Without it, there is no expectation for the timely behavior of others. The guru's statement essentially informs everyone on the island, "you better hope all of the X BEPs that you see leave X days from today otherwise it means you have blue eyes". To a BEP, X=99. Otherwise X=100. Here is slightly different view of where the recursion comes from vs that from the wikipedia page. Every BEP knows there are either 99 or 100 BEPs. And they all know that every BEP they see either sees 98 or 99. Alice BEP (like all BEPs ) knows there are either 99 or 100 BEPs. Bob BEP knows that Alice is considering either the hypotheses {98,99} or {99,100} (Bob himself knows the true number is not 98, he hopes Alice is not considering 100) -- range=[98:100] Carol BEP has the same view of what Alice is thinking as Bob does. Carol hopes that Bob thinks Alice is thinking [97:99] but realizes that if Carol herself has blue eyes, then Bob's Alice range is [98:100]. range=[97:100] Dave BEP hopes Carol's Bob's Alice range is [96:99]. and so on.... On the 99th day, every BEP realizes that lastmost person in the chain of hope has not left. So they all leave. share|cite|improve this answer 1   I think this is the correct insight. The impetus the guru provides is synchronizing the system. This is not well covered in the usual formulation of the problem however. The common knowledge thread of this problem seems like a bit of a red herring: even before the guru it is reasonable to assume of I know that you know etc already is in place. – SEngstrom Oct 7 '14 at 2:20 1   @SEngstrom No it's not a reasonable assumption. You can assume that verybody knows that everybody knows that... repeated 98 times ... there is at least one blue eyed person. You can not assume that everybody knows that everybody knows that... repeated 99 times ... there is a blue eyed person. And that last step of the reasoning is needed. – Taemyr Oct 9 '14 at 11:52 With more than one blue-eyed islander, the guru's statement on its one is obvious to everyone, so in isolation it provides no information. As a result, noone heads for the ferry that night. However, without any more words being spoken, each passing day results in more information. On day one, the guru's statement alone says "There is at least one blue-eyed person". On day two, the guru's statement, plus the fact that the boat left empty, says "There are at least two blue-eyed people" (for if not, then someone would have left). On day three, the guru's statement plus two observations of the boat, says "There are at least three blue-eyed people". Now, the blue-eyed people can all see 99 others, so up to day 99 they still cannot deduce any more than they can see. And each is in the position that he knows there are at least 99 blueys, but he doesn't know if any of the blueys he can see knows that. On the 100th day, however, they have the one extra piece of information that is enough to complete the deduction. share|cite|improve this answer 5   I think the real challenge is that there were also more than $99$ days before the Guru spoke yet nothing happened. Therefore something must have changed due to the Guru speaking; it did provide new information. – Marc van Leeuwen Sep 10 '13 at 12:50 2   It didn't provide new information so much as a coordinating action to begin counting ferry departures. The people were sitting in a state of N=99 or N=100 blue eyed people. – Kyle Hale Sep 10 '13 at 16:04 3   @KyleHale it must have provided new information, since in the absence of new information, how can anything change? – Ittay Weiss Sep 10 '13 at 18:32 3   Suppose that a given person on the island can see k people with blue eyes. The information given by the guru is then, "if k blue-eyed people are gone after k nights, then my eyes are brown, otherwise my eyes are also blue." – Jaycob Coleman Sep 10 '13 at 20:03 3   I will also add: the only way the islanders have to communicate with each other is to get on the ferry or not. The Guru's information is "Today is the day you would get on the ferry if you were the only person with blue eyes." All logic flows from there. Which you can see why it isn't really information, it's more of a ... decision? Again, it's firing the starting pistol. – Kyle Hale Sep 10 '13 at 21:55 The question doesn't ask for the solution to the puzzle, which it already linked to. The first paragraph of the linked puzzle ends with: [...] Everyone on the island knows all the rules in this paragraph. The whole paragraph is crucial, but two strongly interacting aspects may be overlooked. First, "[t]hey are all perfect logicians -- if a conclusion can be logically deduced, they will do it instantly." This means that they will update their knowledge logically and act accordingly. Second, "[e]veryone on the island knows all the rules in this paragraph" is also a rule in the paragraph. It also refers to itself. That implies that everyone knows that everyone knows that [infinite repetition] everyone knows that everyone on the island knows all the rules in this paragraph. This is called common knowledge (which is much stronger than, say, universal knowledge: everybody knows $P$). Combined with the first aspect, this is sometimes called common knowledge of rationality or CKR, which is often used in game theory (although its full power usually isn't needed, as in this case). What is the quantified piece of information that the Guru provides that each person did not already have? "I can see someone who has blue eyes[,]" in itself already was universal knowledge. Its public announcement makes it common knowledge. This, together with the repeated non-leaving of islanders, launches a cascading set of common knowledge that will eventually include that (and which) 100 islanders have blue eyes. (The public observation, i.e., all islanders observe all islanders observe all islanders observe all islanders ... not leaving the island, can, technically, be viewed also as a public announcement.) Each person knows, from the beginning, that there are no less than 99 blue-eyed people on the island. How, then, is considering the 1 and 2-person cases relevant, if they can all rule them out immediately as possibilities? To get the blue-eyed islanders to realize that they are blue-eyed, they need to have i) common knowledge that at least 99 islanders have blue-eyes, and that, after that realization, ii) still nobody left. To get the common knowledge thing going it needs to pass through the 1 and 2-person cases. Why do they have to wait 99 nights if, on the first 98 or so of these nights, they're simply verifying something that they already know? It is only after 99 nights, that they know that 99 nights wasn't sufficient for any blue-eyed islanders to figure out that they had blue-eyes themselves (notwithstanding CKR). After only 98 or less nights, this was still an uncertainty, not deducible and therefore not known. The islanders aren't "simply verifying something that they already know"; they are stepwise turning knowledge into common knowledge that is necessary for the last step. NB: I believe the puzzle is more-or-less identical to (and therefore an adaptation of) "Muddy Children" (Fagin et al. 1995; Geanakoplos 1992), which is a textbook example in modal logic. Keywords: epistemic modal logic, public announcement logic (PAL), dynamic logic of public observation, common knowledge share|cite|improve this answer      I do not think that the claim marked * is true. Consider the case where the guru announces "98 people who have blue eyes": everyone has known this before (universal knowledge), because everyone sees at least 99 blue-eyed people. Moreover, everyone knows that everyone knows: blue-eyed people see 99 other blue-eyed people, so these must each see at least 98 blue-eyed people. But there it stops. It is not true that everyone knows that everyone knows that everyone knows that the guru sees 98 blue-eyed people. This, however, is a necessary condition for "common knowledge". – Ansgar Esztermann Sep 12 '13 at 8:35      You say: He could also have been saying "I got some sand in my eyes, I don't see anything[,]" and still the solution would be the same. Accepting this, it follows by symmetry that the blue-eyeds and brown-eyeds will act the same, contradicting the original answer. A way out of this contradiction would be to say that the original answer is wrong, and all brown-eyeds and blue-eyeds leave on the 100th day. – Fillet Sep 12 '13 at 8:46      The symmetry is that there are "100 blue-eyed people, 100 brown-eyed people, and the Guru (she happens to have green eyes)." The original guru statement could possibly break the symmetry, as it refers to blue eyes. If the guru statement is "I have sand in my eyes", then you have no reason to break the original symmetry. The world views are also symmetric, blue sees 99 blue and 100 brown, brown sees 99 brown and 100 blue. – Fillet Sep 12 '13 at 9:13      @AnsgarEsztermann I tossed it out. My bad. – Kinnisal Mountain Chicken Sep 12 '13 at 14:07 1   This is the best answer in my opinion, thanks! – Philip Feb 16 '14 at 3:56 Just work out the case where there are 2 people, then 3 people, then 4 people. It's the same principle, just more mind-boggling, for higher $n$. When there are just 2 people the situation is pretty much clear. When there are 3 people, does each know that everybody knows that everybody knows that there are people with blue-eyes? (there was no typo in what I wrote). To make it clearer, give the people distinct names and ask yourself: if John has blue eyes, does he know that Jeff knows that Ted knows that there are people with blue eyes. Then answer the question: if John does not have blue eyes, does he know that Jeff knows that Ted knows that there are people with blue eyes. The answers are different. But, the answers become trivially 'yes' if it becomes common knowledge that there are blue-eyed people. share|cite|improve this answer 4   It has always been common knowledge that there are blue-eyed people. So the last sentence is not correct. – Keinstein Sep 10 '13 at 11:29 6   @Keinstein: Though everybody always knew there were blue-eyed people, it was not in a technical sense common knowledge until the Guru spoke. – Marc van Leeuwen Sep 10 '13 at 12:33 5   No. Everyone has seen that there are more than one people with blue eyes. Thus everyone knew that there are people with blue eyes. Everyone knows further that everyone has seen someone with blue eyes. Thus, everyone knows that everyone knows that there are people with blue eyes. As all know that all know this logic. The recursion goes ad infinitum. So it was common knowledge that there have been people with blue eyes. That has been emphasised in the linked version provided by A Googler. The only thing they didn't know was the exact number which became clear after 99 nights. – Keinstein Sep 10 '13 at 12:46 14   @Keinstein: You are wong. Suppose for simplicity there are just three pairs of blue eyes. Everybody knows there are blue eyes (they see two pairs). Everybody also knows that everybody knows this, because they know the two pairs they see can see each other. But nobody among the blue-eyed knows that the previous sentence it true (i.e. that everybody knows that everybody knows), because if those two pairs of blue eyes were the only ones, each of them would see only one pair, and the argument used (I can see two pairs that can see each other) would not apply for them. – Marc van Leeuwen Sep 10 '13 at 14:04 2   This is true for 3 pairs. Ok. But it doesn't imply that it is true for more pairs especially for 100. Otherwise I'd like to see a proof that constructs a real contradiction for $n∈\mathbb N$. We know that there cannot be a circle of knowing the explicit color. But that is not a contradiction against a circle of knowing that someone knows that there is at least one person with blue eyes. So suppose that there has been an external source of information without an initial moment that implanted the common knowledge that there is at least one blue-eyed person. Why should everyone know the truth? – Keinstein Sep 10 '13 at 20:31 The passage of time is important input because an event happens every night, and that event provides information to every islander what the others know or do not know. Whether or not anyone leaves on a given night, the information content changes. By not leaving, everyone has communicated clearly, "I do not know my eye color". When the guru speaks, he polarizes the group into two, let's call them groups S and groups T. Group S is blue-eyed, and so they see one fewer blue-eyed people than group T. Everyone's question is then, do I belong to group S (snappy), or group T (tardy)? And executes this algorithm: "I will leave the island on night X, where X is the number of blue people I see". So for instance if there are 50 blue-eyed people, then group S is planning to leave on night 49, and group T on night 50. Nobody knows whether he or she is part of group S or group T, but this comes to light on night 49 when group S leaves, leaving group T. Of course, group T's travel plan is thereby wrecked! On night 49, everyone in group S knows they are in group S, and thereby know that their eyes are blue, and those in group T also know that they are group T. But all they know is that their eyes are not blue, which does not amount to knowing their own eye color, and so they must stay on the island forever. So, why do the islanders go through this charade of waiting out all these days? Well, the algorithm requires it. They cannot simply trim 49 days out of the wait because that would require a collective decision. To trim 49 days of waiting you have to know that the two days in question are 49 and 50, of which 49 is the minimum. Everyone who plans to leave on night X knows that people with a different plan are either targetting X-1 or X+1, but does not know which! So there is no way to avoid having to count the days: nobody knows what "bias offset" value to subtract from the number of nights to shorten the waiting game. If you look at this another way, counting the nights and leaving is a way for the islanders to communicate a message to all the other islanders. By waiting until night X and bailing from the island, each islander expresses the message "I saw X blue-eyed people on the day the guru spoke". The value of X is significant and so the days must be counted out earnestly; no shortcuts. It is this key piece of communication which triggers the exodus of blue-eyed people. If on day zero everyone were allowed to speak to say how many blue-eyed people he or she sees, then all the blue-eyed people could leave that same night, because only two numbers would be spoken (e.g. 49 and 50). And those uttering 49 would all know that they are part of group S. share|cite|improve this answer 1.) The quantified piece of new information that the Guru provides is not 'at least one person has blue eyes' (except in the $n=1$ case), since everyone knew that already. In fact, this quantified piece of information is rather complicated. If there is one islander, then the new information is exactly 'there is at least one person on the island with blue eyes'. Then the one islander knows that that one person must be them. If there are two people on the island, then it's not news to the first islander that there's someone on the island with blue eyes: they can see that their friend has blue eyes. However, after a day has passed and their friend hasn't left, they know the following piece of information that they didn't know before: The fact that there's at least one person on this island with blue eyes was not news to the other person on the island. If there are three people on the island, then the new piece of information, with brackets added to show structure, is The fact that (the fact that there's at least one person on this island with blue eyes was not news to the other islanders) was not news to the other islanders. And so on. In fact, it occurs to me that you can state the new piece of information for $n$ islanders rather simply if you don't mind hiding the detail of the islander's logical deductions. It is: The information that the Guru can see at least one islander with blue eyes was not enough to convince the other islanders that they had blue eyes in $n-1$ days. Or even: I have blue eyes. But I suppose that those don't really count as 'quantified'. I think that it's because the new piece of information is so complicated (and only becomes more complicated as we increase the number of islanders) that this puzzle seems so counter-intuitive. 2.) This time, we'll start with $n=100$, and work back down. If I am on the island, and I look round, I see $99$ people with blue eyes. If you're on the island with me then, as far as I know, you might be seeing $98$ people with blue eyes and one person (me) with brown eyes. This is because I don't know my own eye colour. So the $n=98$ case becomes relevant. Let's suppose that I am absolutely convinced that I have brown eyes, and that everyone else on the island is convinced that they have brown eyes, at least until they're proved wrong. I look at you, looking at $98$ people with blue eyes, and think, 'Haha! Each of those $98$ people is looking around and seeing $98$ people with blue eyes, but you probably think that you have brown eyes, so you think that those people can only see $97$ people with blue eyes.' In other words, in my imagination, there are $99$ people on the island with blue eyes, and in my imagination of your imagination, there are only $98$. Then in my imagination of your imagination of someone else's imagination, there are only $97$. Eventually, we get to some sub-sub-...-sub-imagination where there are only one or two people with blue eyes even though all of the islanders in fact know that there are at least $99$. Don't worry if you have trouble getting your head round that one. The human mind isn't designed to handle so many conceptual layers - that's why tools such as induction are so useful. share|cite|improve this answer      First explanation that perfectly clicked. Thanks! – John Meacham Nov 23 '14 at 21:10 The reason it's not "common knowledge" beforehand that there is someone with blue eyes is: Let's simplify the case to four people other than the guru: Two (Alice and Bob) with blue eyes, and two (Carol and Dave). It is true that everyone can, in fact, see at least one person with blue eyes. Alice can see Bob, Bob can see Alice, and Carol and Dave can see both of them. However, Alice does not know that Bob can see anyone with blue eyes, or vice versa. Alice and Bob also do not know that Carol and Dave can see two people with blue eyes. Now extend it to six people. Erin has blue eyes, Frank has brown eyes. Erin can see that Alice and Bob both have blue eyes, but as far as she knows, either one of them can only see one person [i.e. the other one respectively], so she does not know that Bob knows that Alice knows that there is someone with blue eyes. Now extend it to eight people. Blue4 can see Alice, Bob, and Erin all have blue eyes, but likewise does not know that Erin knows that Bob knows that Alice knows there is someone with blue eyes. Now extend it to ten people: Blue5 does not know that Blue4 knows that Erin knows that Bob knows that Alice knows. Now twelve, fourteen, etc. This same logic, by the way, extends to why you can't shortcut and say that "people know in advance that nothing happens until day 99", because the Guru has not said there are two people with blue eyes, and [etc] does not know that Blue4 knows that Erin knows that Bob knows that there are two people with blue eyes, until the first day has passed. (since it is common knowledge that if there had been only one, they would have left immediately) share|cite|improve this answer      The induction starts at 3 blue eyed people not with 2. – Keinstein Sep 10 '13 at 13:29 1   @Keinstein how does that mean it's not useful, informally, to describe the case with two? – Random832 Sep 10 '13 at 13:31 1   Lets take A, B, C, D, E, F where A, B, C are blue and D, E, F not. Then A nows that B sees C and that C sees B, B knows that C sees A and A sees C, C knows that A sees B and B sees C. The other three know that. Thus everyone knows that everyone sees someone blue. – Keinstein Sep 10 '13 at 13:43      Doesn't matter, since my point is about what people know about what other people know: i.e. that C doesn't know that A knows that B sees C. Describing the A/B case is useful for explaining it this way, since the facts of A/B are equivalent to what C knows in A/B/C. – Random832 Sep 10 '13 at 13:54 1   I'd love to meet these Alice and Bob, they're all over the mathematics world, even in modern physics. – MyUserIsThis Sep 10 '13 at 16:14 The answer to question 1, if we assume no one ever knew their eye color since the beginning of time on that island and that no one ever left the island, is that the Guru told every blue-eyed islander that their eyes were blue. Because only after she says that can the thought process below be followed by blue-eyed islanders. What she said has no effect on the islanders with other eye colors. After 100 days, no one else can leave until the Guru mentions another color. Regarding questions 2 and 3, to illustrate why we need to wait 100 days, we need to consider what each blue-eyed islander thinks every other blue-eyed islander perceives. When we do that, we can clearly see why we need to go down to the case of 1 and 2 blue-eyed islanders. Each blue-eyed islander thinks: • I can see 99 blue-eyed islanders. If I am not blue-eyed, then: • Each of the 99 blue-eyed islanders I can see will see 98 blue-eyed islanders. If each of the 99 consider the possibility that they are not blue-eyed, then they will each think that: • Each of the 98 blue-eyed islanders they see will see 97 blue-eyed islanders. If each of the 98 consider the possibility that they are not blue-eyed, then they will each think that: • Each of the 97 blue-eyed islanders they see will see 96 blue-eyed islanders. If each of the 97 consider the possibility that they are not blue-eyed, they will think that: • ... • Each of the 2 blue-eyed islanders they see will see 1 blue-eyed islander. If each of the 2 consider the possibility that they are not blue-eyed, they will think that: • The one blue-eyed islander they see will leave today. • If no one leaves today, then the 2 they see will leave on the 2nd day. • ... • If no one leaves on the 96th day, then the 97 they see will leave on the 97th day. • If no one leaves on the 97th day, then the 98 they see will leave on the 98th day. • If no one leaves on the 98th day, then the 99 I can see will leave on the 99th day. • If no one leaves on the 99th day, then I am blue-eyed and I shall leave with the 99 I see on the 100th day. share|cite|improve this answer Without outside information, every islander can prove, for every $k$, that "Island logic" proves $P(k) \implies P(k+1)$ where $P(k)$ is the statement (it is true and is common knowledge that) if nothing happens after $k$ nights then every person can see at least $k$ blue-eyed persons The guru provides common knowledge [arbitrary finite chains of "X knows that Y knows that Z knows ..."] of $P(1)$, which implies all higher $P(k)$ and therefore a relationship between number of nights and number of blue eyes. After $k$ nights it forces common knowledge of the fact that everyone can see at least $k$ blue-eyed persons. At $k=99$, this reveals the exact eye-color distribution to all islanders. Proof of $P(k) \to P(k+1)$: After the $k$th night, every person is known to see at least $k$ blue-eye persons. Anybody who sees only $k$ blue persons knows that those blue-ers see $k-1$ blue on each other and $1$ other (himself), and leaves the island the next night. Thus, $k+1$ nights of inactivity implies that everyone can see at least $k+1$ blue-eye persons. Everyone knows that everyone else can perform this deduction, so that $P(k)$ true and commonly known implies the same for $P(k+1)$. Now, to the numbered questions. 1. The islanders do not have unlimited-depth common knowledge of the fact that there is at least $1$ blue-eyed person, nor of $P(1)$, before the guru speaks. 2. The inductive reasoning that proves $P(k)$, if unwound, contemplates a hypothetical island where an islander (seeing only $k-1$ blue-eyes) has non-blue eyes and thinks about another islander (seeing only $k-2$ blues) contemplating an island in which he has non-blue eyes, etc, arriving eventually at the $1$-person situation which finally has to confront the guru's statement deciding that case. 3. The extent of what is common knowledge is increasing every night, until critical mass is reached. share|cite|improve this answer What is the quantified piece of information that the Guru provides that each person did not already have? The Guru provides the common knowledge that there is somebody with blue eyes. Basically, every person knows that $\exists$ somebody with blue eyes, and every person knows that every person knows that, and so on ad infinitum. Each person knows, from the beginning, that there are no less than 99 blue-eyed people on the island. How, then, is considering the 1 and 2-person cases relevant, if they can all rule them out immediately as possibilities? Because for this person (person A), there are two possibilities: • He is blue eyed (100:100) • He is brown eyed (99:101) So A can't leave immediately. For the second one, let's pick a person B in person A's visualization. B sees only 98. In B's mind (remember, B is a figment of A's imagination while visualizing option 2), there are two possibilities: • He is blue eyed (99:101) • He is brown eyed (98:102) So, A knows that B can't leave immediately. Now, in B's mind in A's mind, there are two possibilities for a person C to leave: • He is blue eyed (98:102) • He is brown eyed (97:103) Again, two possibilities, A knows that B knows that C can't leave. This keeps going, till we reach person Y in an Inception-esque layered imagination of the rest, who has two options: • He is blue eyed (2:198) • He is brown eyed (1:199) If it is the latter, he can see a person Z and imagine his options: • He is blue eyed (1:199) • He is brown eyed (0:200) This is not possible, as there has to be at least one blue eyed person. Z has only one option, then. But we can't just pick this because this option only comes into play if Y knew that he was brown eyed, which only comes into play if X knew he was brown eyed, and so on all the way back up to B. So, on the first day, because Z doesn't leave, the idea of there only being one blue eyed person is ruled out. Wasn't it ruled out from the beginning? Yes, however it could not be ruled out from the minds of the others while visualizing. Remember, A knows that if he had brown eyes (9:101), then B would be considering the option that he has brown eyes too (98:101), even if that doesn't add up from A's perspective. We have to take into account what options are being considered. Why do they have to wait 99 nights if, on the first 98 or so of these nights, they're simply verifying something that they already know? They don't know it. Each blue person knows that it's either 99:100 or 100:100, but can't pick. They need to wait to ensure that it works. A simpler problem Let me try to work out the second part again for 6 islanders, where the actual distribution is (3:3). The bullets are chronologically ordered, the nesting is Inception-esque imagination. • Blue eyed person A knows that there are at least 2 blue eyed people. He knows that if he is blue eyed, the other blue eyes are thinking the same as him. But this isn't the only possible case. The lack of any definite knowledge means that they don't leave (yet). If he considers the case that he has brown eyes, he visualizes that: • Blue eyed person B knows that there is at least 1 blue eyed person. If there were 2, then both would be thinking the same thing, and again, due to lack of definite knowledge, they can't leave. It there is one, he visualizes that: • Blue eyed person C sees 0 blue eyed people. Concludes that he must be The One. Leaves. • On the first day, no one leaves. On the second day, • Blue eyed person A knows that there are at least 2 blue eyed people. He knows that if he is blue eyed, the other blue eyes are thinking the same as him. The lack of any definite knowledge means that they don't leave (yet). However, if he considers that he has brown eyes, he visualizes that: • Blue eyed person B knows that there is at least 1 blue eyed person. If there were 2, then both would be thinking the same thing. If there is one (C), then B knows that C would have left the day earlier. That didn't happen. So.. there must be two. As both are thinking the same thing, both leave. • On the second day, no one leaves. On the third day, • Blue eyed person A knows that there are at least 2 blue eyed people. He knows that if he is blue eyed, the other blue eyes are thinking the same as him. If there are only two blue eyed people, then they would have left the day earlier. Which didn't happen. So he must have blue eyes, and as all three are thinking the same thing, they all have blue eyes. The three leave. • The brown eyes leave the next day. Note that while initially it is clear that the number of blue eyes $>=2$, the number of blue eyes can be less from the point of view of someone when another is considering the option that he is brown eyed. The lower numbers only come in due to this "but what is he thinking" thought that gets nested. share|cite|improve this answer 1   If the guru add no information, then nothing can change. Imagine that it is a written law that all blue-eyes people must leave. A law known to anybody. Without the guru's words nothing will happen and no-one will leave. So the Guru must add some information (look-up complete knowledge). – Ittay Weiss Sep 10 '13 at 18:36      @IttayWeiss The new knowledge is that "nobody else left". – Manishearth Sep 10 '13 at 18:41      that isn't it either, since the guru did not say that. The question is: at the instance the guru speaks, what new information does at least one of the people have that (s)he did not have before. The answers can't be 'nothing' since then behavior can't change (and if the guru said nothing, then nobody ever leaves). So the answer must be something, and it must be some piece of information not knows before guru speaks, yet known immediately afterwards. – Ittay Weiss Sep 10 '13 at 18:49      @IttayWeiss The new information is "nobody left". See the last section, it becomes clearer as the thought process is outlined carefully. Information need not be externally injected. – Manishearth Sep 10 '13 at 18:56 1   @IttayWeiss Ah, so we do agree :p I thought we were talking about incremental knowledge on each day; that's where the confusion seemed to be coming from. I'll correct that. – Manishearth Sep 10 '13 at 20:40 Let $n$ be a natural number and let us think of a statement: $P(n)$: "On the day $n$ all $n$ blue-eyed people leave." Now the piece of information the Guru provides is very important, as it makes $P(1)$ true. Indeed, if there was only one blue-eyed person and the Guru said nothing, that person could not deduce he/she is the only one with blue eyes, like described in the solution (I am assuming, however, that there is no other way to deduce this). So with the information Guru provided, we know, that $P(1)$ holds, so now we can use mathematical induction to prove, that $P(n)$ holds for every natural number $n$. When proving this, we can use the similar steps and thoughts that are used in the solution for the case of two blue-eyed people. share|cite|improve this answer      This doesn't answer question 1.: What information has been provided by the Guru? $P$ is common knowledge as all statements are common knowledge. $1$ is not the information that the Guru provided. This number is a conclusion that arrived one day after her statement. To which knowledge refers this conclusion and which information has been added? – Keinstein Sep 10 '13 at 11:44 2   The statement $P(n)$ is wrong. It is in fact a non-statement for all $n\neq100$ as it makes a false side-remark that there are $n$ blue-eyed people. It is a side-remark because it is not part of what $P(n)$ states, or else $P(n)$ would just state "there are $n$ blue-eyed people and they all leave on day $n$", something that cannot be proved by induction simply because it is false for $n\neq100$. You probably meant $P(n)$ to be "if there are $n$ blue-eyed people then they will all leave on day $n$", but this doesn't work either with induction (the induction hypothesis gives a vacuous truth). – Marc van Leeuwen Sep 10 '13 at 12:43 1. I think the information that the Guru provides, is that all blue eyed people have to leave. This starts the whole process of inductive reasoning. 2. The 1, 2 cases are relevant, because if I had blue eyes and I didn't know, I'd think others would leave at 99th day since each of them would reason other 98 would leave on 98th day, and so on. The number goes down with each blue guy's hypothetical inductive reasoning, where he thinks there could also be one less blue eyed people since he is not sure about himself. 3. On the first $n-1$ nights, they are not verifying. They are waiting, for the remaining $n-2$ blue guys to reason out their stuff. They know for sure nothing will happen on first $n-1$ days, because if there are really $n-1$ blue eyed people, they would each know nothing will happen on the first $n-2$ days and so on. This wait is unavoidable. Only interesting night would be the $n-1$th night, when everyone will leave if others saw only $n-2$ blue eyed, but won't if they also saw $n-1$ blue eyed (i.e. if the person thinking is himself blue eyed). share|cite|improve this answer I believe the key question for a tribesman to ask after the Guru's statement is: If I am not a blue, when would the blues I see be forced to leave? They would then reason that the blues they see would ask the same question with one less blue: If I am not a blue, when would the blues I see be forced to leave? This continues recursively without a clear answer until the 2 blue's question is reached, in which case the 1 blue would be forced to leave the first night. Before the guru had spoken, that sole blue would NOT have left the island because of the knowledge of the color of their eyes. This is the key to why the guru's statement starts the countdown!!! Update: Here are the answers to your questions: 1. That signifies the day that 1 blue would have left. 2. We don't consider the 1 and 2-person cases directly. We consider the 99 case, which necessitates considering the 98 case, which necessitates considering the 97 case, .. which necessitates considering the 2 and 1-blue cases. 3. Blues know that either the other blues will leave on the 99th night (only 99 blues) or they are blue (and will leave on the 100th). If there were only 99, those blues would know that either the other blues will leave on the 98th night or they are blue. Etc.. share|cite|improve this answer Here is my take on question 2. Let's take $n=4$, the first non-obvious case, and look at the perspective of islander 1. He thinks, "I am not sure what my eye color is, so assume it isn't blue. I see three blue-eyed people, but they all also think they are not blue-eyed. Among them is my good friend islander 2." He begins to imagine what islander 2 thinks, creating a fantasy where he (islander 1) is not blue-eyed and putting himself in the head of islander 2. His fantasy self thinks, "Now, I see islander 1, but he is not blue-eyed, so I only see two blue-eyed people. Among them is my friend islander 3." The fantasy islander 1 taking the role of islander 2 now begins to think what islander 3 is thinking, creating a fantasy where neither islanders 1 nor 2 has blue eyes and taking the role of islander 3. His fantasy self's fantasy self thinks, "Now, I see both islanders 1 and 2, neither of which is blue-eyed, so I see only one blue-eyed person, the hated islander 4. I hope that guy picks up on the fact that he is the only blue-eyed person here! " But the real islander 4 is two levels deep in his own fantasy and is waiting for one is the others to "realize" they are the only one with blue eyes. Since everyone is waiting, nothing happens that day. So after one day, when islander 4 does not realize he is the only one with blue eyes, the fantasy of the fantasy of islander 1 realizes he is wrong and thus had blue eyes. Thus, the fantasy of islander 1 (playing the role of islander 2) reconsiders and on the second day thinks that today, both islanders 3 and 4 will realize they are the only ones with blue eyes. However, the real islanders 3 and 4 are one level into their respective fantasies that two of the others will figure it out. Everyone is waiting, so no one does anything. So after two days, the fantasy of islander 1 (as islander 2) realizes that he is wrong and actually has blue eyes. So islander 1 himself reconsiders and expects that today is the day the others all realize they are the only the with blue eyes. But all of the others came out of their own fantasies as well, and are expecting that the other three "figure out" they are the only blue-eyed islanders today. Everyone is waiting, so no one does anything. Three days have passed, all the fantasies have been dissolved, and yet no one has left. The only remaining assumption that islander 1 entertained was that he himself is not blue-eyed. He realizes that this must be false, and leaves the island. Everyone else has the exact same thought process, so they leave too. So that's why the base cases are important even though none of them are realistic: until the last day, every islander is in some fantasy within a fantasy within...and in those fantasies, the island really does have fewer blue-eyed people. They don't communicate directly about their eye color, but by their actions and the common knowledge that they must be thinking identically, they do tell the others what they have deduced. Eventually they collectively deduce that everyone expects all the others to have blue eyes, so since they are perfect logicians, they realize they have blue eyes. The fantasies are necessary because from the start, they all are in denial and all expect the others to be in denial as well, and it takes a few rounds of observation for the fact that it is denial to penetrate all levels of their consciousness. As for question 1, the guru only plays the role of a reference point to synchronize their fantasies. Otherwise no one would know where in their deductions the others were. They are always trying to do deductions, but not knowing what the others' actions mean, they don't get anywhere until someone says "hey, think about it together." As for question 3, I think this is already explained, since on the first 99 days, they are not verifying what they knew; they are actually escaping from some kind of Inception delusion. share|cite|improve this answer      This is dual to the other one: "The inductive reasoning that proves $P(k)$ [the statement 'it is true and common knowledge that if $k$ nights have passed uneventfully, then everyone can see at least $k$ blue-eyes'], if unwound, contemplates a hypothetical island where an islander (seeing only $k−1$ blue-eyes) has non-blue eyes and thinks about another islander (seeing only $k−2$ blues) contemplating an island in which he has non-blue eyes, etc, arriving eventually at the 1-person situation which finally has to confront the guru's statement deciding that case.". – zyx Sep 13 '13 at 18:38      Looks like we had the same idea at the same time. – Ryan Reich Sep 14 '13 at 5:11 Sorry this answer became so long. If you want the two-minute answer, just read the Terminology then skip down to the Answers to the Questions. You can then fill in the details as desired. Terminology • Let $A, B, C, A_i$ denote the blue-eyed islanders. • Let $A_i^*$ denote the proposition that $A_i$ has blue eyes (which does not imply that $A_i$ knows this). • We'll use the standard symbols and rules of propositional logic. • $A\leadsto P$ means islander $A$ knows that $P$ is the case, where $P$ is a proposition. The operator "$\leadsto$" is right-associative and has higher precedence than the logical implication operator "$\Rightarrow$". • $\cal O$ is the proposition that there is at least one blue-eyed islander. This is what the Guru announces on day 1. 1 Blue-eyed Islander To introduce use of this notation, let's briefly go over what happens when there is 1 blue-eyed islander $A$. Day 1 After the Guru makes her announcement, it is the case that $$A\leadsto{\cal O}.\tag{1.1.1}$$ Since $A$ sees no islanders with blue eyes, she concludes it's her: $$A\leadsto A^*.\tag{1.1.2}$$ This fact entitles $A$ to leave the island on day 1, so we are done with the case of the 1 Blue-eyed Islander. 2 Blue-eyed Islanders Before the Guru makes her announcement, the following statements can be said about blue-eyed islanders $A$ and $B$: $$A\leadsto{\cal O}\\ B\leadsto{\cal O}.\tag{2.0.1}$$ This follows simply from the fact that they can each see one other blue-eyed person on the island. Day 1 After the Guru announces $\cal O$, it is the case that $$A\leadsto B\leadsto{\cal O}\tag{2.1.1}$$ as well as the one other permutation of this: $B\leadsto A\leadsto\cal O$. The above reads "$A$ knows that $B$ knows that $\cal O$." It is important to grasp at this point that this fact wasn't the case prior to the Guru's announcement. Even though both $A$ and $B$ knew there was at least one blue-eyed person on the island, $A$ didn't know that $B$ knew this, because for all $A$ knows, she may have brown eyes. (2.1.1) can be written as $$A\leadsto B\leadsto(A^*\vee B^*).\tag{2.1.2}$$ The substitution ${\cal O}\mapsto A^*\vee B^*$ is valid in this particular context, because everyone else on the island other than $A$ and $B$ do not have blue eyes, which is known to both $A$ and $B$, and $A$ knows that $B$ knows this. (2.1.2) can be written as $$A\leadsto(\neg A^*\Rightarrow B\leadsto B^*)\tag{2.1.3}$$ which will be useful for Day 2. To prove this, the following axiom is needed: Knowledge Conjunction Axiom $$((A_i\leadsto P)\;\wedge\;(A_i\leadsto Q))\;\;\Leftrightarrow\;\; (A_i\leadsto(P\wedge Q))$$ $A_i$ knows $P$ and $A_i$ knows $Q$ if and only if $A_i$ knows $P$ and $Q$. The proof for (2.1.3) is of primary importance, as it readily generalizes to any number of blue-eyed islanders and days, so a detailed proof is given here for the interested reader. 1. $A\leadsto(\neg A^*\Rightarrow(B\leadsto\neg A^*))$ 2. $A\leadsto((B\leadsto\neg A^*)\Rightarrow(B\leadsto\neg A^*))$ 3. $A\leadsto(((B\leadsto\neg A^*)\Rightarrow(B\leadsto\neg A^*))\wedge (B\leadsto(A^*\vee B^*)))$ 4. $A\leadsto((B\leadsto\neg A^*)\Rightarrow((B\leadsto\neg A^*)\wedge (B\leadsto(A^*\vee B^*))))$ 5. $A\leadsto((B\leadsto\neg A^*)\Rightarrow(B\leadsto( \neg A^*\wedge(A^*\vee B^*))))$ 6. $A\leadsto((B\leadsto\neg A^*)\Rightarrow(B\leadsto B^*))$ 7. $A\leadsto(\neg A^*\Rightarrow B\leadsto B^*)$ Step-by-step justifications: 1. $A$ knows that if she doesn't have blue eyes, then $B$ will know this. 2. $P\Rightarrow P$ tautology. 3. Knowledge Conjunction Axiom of step 2 with (2.1.2). 4. $((P\Rightarrow P)\wedge Q)\;\Rightarrow\;(P\Rightarrow(P\wedge Q))$ tautology applied to step 3. 5. Knowledge Conjunction Axiom applied to step 4. 6. Disjunctive syllogism applied to step 5. 7. Knowledge Conjunction Axiom applied to steps 1 and 6, and transitivity of $\Rightarrow$. This just delineates in detail what many people can reason without the symbolic logic, which is the fact that $A$ knows that if she doesn't have blue eyes, then $B$ will know he does. The value of this formalism is that it extends readily into more complicated scenarios where our intuition may have trouble keeping up. Day 2 No one left the island on Day 1, so no one knew they had blue eyes. In particular, $$\neg(B\leadsto B^*)\tag{2.2.0}$$ otherwise $B$ would have left. This fact is publicly known, so in particular $A$ knows it: $$A\leadsto\neg(B\leadsto B^*)\tag{2.2.1}.$$ Combining this with (2.1.3) via the Knowledge Conjunction Axiom gives $A\leadsto((\neg A^*\Rightarrow B\leadsto B^*)\wedge\neg(B\leadsto B^*)).$ Modus tollens yields $$A\leadsto A^*.\tag{2.2.2}$$ This is $A$'s ticket off the island, so she leaves today. These arguments for both days are symmetric in $A$ and $B$, so apply to $B$ as well. Both blue-eyed islanders leave the island on Day 2. 3 Blue-eyed Islanders Before the Guru makes her announcement, $C\leadsto\cal O$, $B\leadsto\cal O$, and $A\leadsto\cal O$. In addition, $$A\leadsto B\leadsto{\cal O}\\ B\leadsto C\leadsto{\cal O}\\ C\leadsto A\leadsto{\cal O}.\tag{3.0.1}$$ For example, $A$ knows $B$ knows $\cal O$, because $A$ knows $B$ knows $C^*$. Day 1 After the Guru announces $\cal O$, it is the case that $$A\leadsto B\leadsto C\leadsto{\cal O}\tag{3.1.1}$$ as well as the $3!-1=5$ other permutations of this in $(A,B,C)$. It is important to pause at this point and understand that this was not true prior to the Guru's announcement. Especially if one wishes to understand what quantified information the Guru is actually providing that each person didn't already have, this is it. Even though everyone knew that everyone else knew $\cal O$, that's only 2 levels deep. It required the Guru's public announcement to get to the 3rd level. $A$ did not know that $B\leadsto C\leadsto\cal O$ prior to her announcement. Though the symbols provide the formalism, one informal but ituitive notion to consider is that of each person's "world"—the information available to a person. The world as seen through the eyes of $A$ is one in which there are 2 other blue-eyed people $B$ and $C$. Now consider the world of $B$ as considered by $A$. In this world, there is only 1 person whom with certainty has blue eyes: $C$. Moreover $C$ does not know if anyone else has blue eyes; $C$ does not know $\cal O$ until the Guru speaks, whose announcement penetrates through these worlds so that even in this doubly layered consideration, $C\leadsto\cal O$. In other words, $A\leadsto B\leadsto C\leadsto{\cal O}$. (Why am I reminded of the movie Inception?) Moving forward as before, from (3.1.1), $$A\leadsto B\leadsto C\leadsto(A^*\vee B^*\vee C^*)\tag{3.1.2}$$ using the substitution ${\cal O}\mapsto A^*\vee B^*\vee C^*$. This is just representing the fact that any of $A$, $B$, or $C$ might be the one the Guru was talking about, which everyone knows that everyone knows etc. to arbitrary depth. It follows from (3.1.2) that $$A\leadsto B\leadsto(\neg(A^*\wedge B^*)\Rightarrow C\leadsto C^*). \tag{3.1.3}$$ The proof for this takes on an analogous structure as the proof for (2.1.3) above. Day 2 As before, no one left on Day 1, so it is concluded that $\neg(C\leadsto C^*)$ (as well as for $A$ and $B$). Since this is just as public as the Guru's announcement, everyone knows everyone knows etc. this to arbitrary depth. In particular: $$A\leadsto B\leadsto\neg(C\leadsto C^*)\tag{3.2.1}.$$ This fact, and its 5 other permutations, were not true until it was publicly observed that no one left on the ferry the prior midnight. Combining this with (3.1.3) via the Knowledge Conjunction Axiom, and applying modus tollens as before, yields: $$A\leadsto B\leadsto(A^*\vee B^*).\tag{3.2.2}$$ Now we are beginning to see a pattern here. This can be written as $$A\leadsto(\neg A^*\Rightarrow B\leadsto B^*)\tag{3.2.3}$$ which is identical to (2.1.3). One might wonder, since $A$ knows that $\neg(B\leadsto B)$, because $B$ did not leave last night, can it be deduced from (3.2.3) that $A\leadsto A$? The answer is no, but to see this it must be noted when certain knowledge was obtained. It would be more precise to write (3.2.3) as $$A\leadsto_2(\neg A^*\Rightarrow B\leadsto_2 B^*)\tag{3.2.4}$$ where $\leadsto_k$ denotes knowledge on Day $k$. The knowledge described in (3.2.3) was not known until Day 2, after observing that $C$ did not board the ferry, which means $\neg(C\leadsto_1 C^*)$, or that $C$ did not know she had blue eyes on Day 1. Similarly, $$A\leadsto_2\neg(B\leadsto_1 B^*).\tag{3.2.5}$$ Thus modus tollens cannot be applied to (3.2.4) and (3.2.5) because $B\leadsto_1 B$ and $B\leadsto_2 B$ are two different propositions. Day 3 No one left again the previous night, so $$A\leadsto\neg(B\leadsto B^*).\tag{3.3.1}$$ Combined with (3.2.3), $A\leadsto A^*$ so $A$ can now leave the island. Same reasoning applies to $B$ and $C$, so all 3 islanders leave on Day 3. $n$ Blue-eyed Islanders Assume $2<n$. Prior to the Guru's announcement, it is a fact that $$A_1\leadsto A_2\leadsto\cdots \leadsto A_{n-2}\leadsto A_{n-1}\leadsto{\cal O}\tag{4.0.1}$$ including all other combinations and permutations of this chain of equal or lesser length, out of the the $n$ blue-eyed islanders $A_i$ for $i\in\{1,2,...,n\}$. Note that (4.0.1) includes only $n-1$ islanders, not $n$. This is because $A_1$ can imagine the world through $A_2$'s eyes, who looks through $A_3$'s eyes, ..., who looks through $A_{n-2}$'s eyes, who looks through $A_{n-1}$'s eyes, who gazes upon $A_n$ but in this world no information is available to guarantee any other blue-eyed person is on the island. So it cannot be concluded in this $(n-1)$-nested world that $A_n\leadsto\cal O$. Without the Guru's announcement, the longest chain of distinct blue-eyed islanders that can be stated is one which includes no more than $n-1$ islanders, such as (4.0.1). Day 1 Once the Guru announces $\cal O$, the chain can now include all $n$ blue-eyed islanders. The guru's statement is equivalent to $n!$ statements, which are all the permutations of $A_i$ in $$A_1\leadsto A_2\leadsto\cdots \leadsto A_{n-1}\leadsto A_n\leadsto{\cal O}.\tag{4.1.1}$$ In anyone's world, no matter how deep the levels, the knowledge of $\cal O$ is always available. Substituting as before for $\cal O$, this becomes $$A_1\leadsto A_2\leadsto\cdots \leadsto A_{n-1}\leadsto A_n\leadsto\bigvee_{i=1}^n A_i^*.\tag{4.1.2}$$ Using analogous steps to prove (2.1.3) from (2.1.2), it follows from (4.1.2) that $$A_1\leadsto A_2\leadsto\cdots\leadsto A_{n-2}\leadsto A_{n-1}\leadsto \left(\neg\bigvee_{i=1}^{n-1}A_i^*\Rightarrow A_n\leadsto A_n^*\right) .\tag{4.1.3}$$ Day 2 As in previous scenarios, since $A_n$ in particular didn't leave, it is publicly known that $\neg(A_n\leadsto A_n^*)$. Everyone already knew this so what new information is there? The new information may be expressed as another set of chain statements, of all $n!$ permutations in $A_i$ of $$A_1\leadsto A_2\leadsto\cdots\leadsto A_{n-2}\leadsto A_{n-1}\leadsto\neg(A_n\leadsto A_n^*).\tag{4.2.1}$$ This wasn't the case until the previous ferry left with no passengers. Combining (4.1.3) and (4.2.1) together, using the Knowledge Conjunction Axiom and modus tollens yields $$A_1\leadsto A_2\leadsto\cdots \leadsto A_{n-2}\leadsto A_{n-1}\leadsto \bigvee_{i=1}^{n-1} A_i^*.\tag{4.2.2}$$ Following the same pattern as before, it can be deduced that $$A_1\leadsto A_2\leadsto\cdots\leadsto A_{n-3}\leadsto A_{n-2}\leadsto \left(\neg\bigvee_{i=1}^{n-2}A_i^*\Rightarrow A_{n-1}\leadsto A_{n-1}^*\right) .\tag{4.2.3}$$ Day $k$ Assume $1<k\le n$. On the previous night $A_{n-k+2}$ didn't leave, so it is publicly known that $\neg(A_{n-k+2}\leadsto A_{n-k+2}^*)$. The new information that wasn't previously available allows for all permutations and combinations in $A_i$ of identical length of the following statement to be made: $$A_1\leadsto A_2\leadsto\cdots\leadsto A_{n-k}\leadsto A_{n-k+1}\leadsto\neg(A_{n-k+2}\leadsto A_{n-k+2}^*).\tag{4.3.1}$$ Combined with the conclusions from the previous day, it is the case that $$A_1\leadsto A_2\leadsto\cdots\leadsto A_{n-k}\leadsto A_{n-k+1}\leadsto\bigvee_{i=1}^{n-k+1} A_i^*.\tag{4.3.2}$$ This can be proven from induction on $k$, which is omitted for brevity but is of the same form as the proof for (2.1.3). Also if one follows how (4.2.3) was derived from (4.2.2), (4.2.1) and (4.1.3) then this will also outline how one can prove this via induction. Day $n$ (4.3.2) shrinks by one islander on each passing day, until finally when $k=n$ we are left with $$A_1\leadsto A_1^*.\tag{4.4.0}$$ Since these arguments have been symmetrical in all the $A_i$, $$\forall i\in\{1,2,...,n\}:A_i\leadsto A_i^*.\tag{4.4.1}$$ On Day $n$, all blue-eyed islanders leave the island. Answers to the Questions 1) What is the quantified piece of information that the Guru provides that each person did not already have? All $100!\approx 9.3\times 10^{157}$ permutations in $A_i$ of the statement $$A_1\leadsto A_2\leadsto\cdots \leadsto A_{99}\leadsto A_{100}\leadsto{\cal O}.\tag{5.1.1}$$ Everyone already knows ${\cal O}=\bigvee_{i=1}^{100}A_i^*$. That is not the value of the Guru's announcement. It is that everyone knows that everyone know that everyone knows ... that $\cal O$ is the case, that is the new information provided by the Guru's announcement that wasn't previously known. In contrast, if the Guru were to tell all the islanders in private the same fact $\cal O$, no islanders would be able to leave the island. So it is not simply the information content of her words that we must look at; there is additional information in knowing that everyone else heard her too. Correspondingly, each day that passes provides a new piece of information that is comparably subtle. When an islander doesn't leave, it is like another public announcement, which includes more information than just the fact that $A_i$ didn't leave last night. It is the knowledge that everyone else knows too. This knowledge is quantified in the answer to question 3 below. Eventually, after 100 days, these additional pieces of information will shrink (5.1.1) down to a fact that the islander can act upon. Namely, $A_i\leadsto A_i^*$ for all $i\in\{1,2,...,100\}$. 2) Each person knows, from the beginning, that there are no less than 99 blue-eyed people on the island. How, then, is considering the 1 and 2-person cases relevant, if they can all rule them out immediately as possibilities? Yes, everyone knows that there are no less than 99 blue-eyed people on the island. The key concept to this problem is the recursive nature in which islanders deduce what they can, knowing only the information that they bring with them as they consider the world through one anothers' eyes. As $A_1$ does this from the perspective of $A_2$ who sees through the eyes of $A_3$, ..., who sees through the eyes of $A_{98}$, $A_{98}$ is left only to gaze upon and consider what $A_{99}$ and $A_{100}$ can possibly know within a world of such limited information. In this nested world 98 levels deep, we cannot take for granted that islanders $A_1$ through $A_{98}$ have blue eyes, just as we cannot take for granted that $A_1$ has blue eyes when we consider only her point of view on all the rest of the 99 blue-eyed islanders. Therefore considering the logic of a 2 blue-eyed-inhabited island is a worthwhile consideration. When 2 days go by in which $A_{99}$ and $A_{100}$ don't leave the island, then $A_1$ knows $A_2$ knows ... knows $A_{97}$ knows $A_{98}$ knows that someone else other than $A_{99}$ and $A_{100}$ have blue eyes. Now there's only 98 days to go. If this escapes the intuition, then consider the case of 1, 2, and 3 blue-eyed islanders, and allow the logical formalism as deliniated above to provide the scaffolding that extends the intuition. 3) Why do they have to wait 99 nights if, on the first 98 or so of these nights, they're simply verifying something that they already know? Because they're not. Every day that passes, new information is provided that wasn't previously known. It's not as simple as a statement that islander $A_k$ didn't leave, because yes that was already known and anticipated. There is additional information in the knowledge that everyone else knows that everyone else knows etc. that $A_i$ did not leave the island. To be precise, on day $k$, for $k>1$, the new facts that weren't previously the case are all $100!/(k-2)!$ permutations and combinations in $A_i$ of $$A_1\leadsto A_2\leadsto\cdots\leadsto A_{100-k}\leadsto A_{101-k}\leadsto\neg(A_{102-k}\leadsto A_{102-k}^*).\tag{5.1.2}$$ With each passing day $k$, it is these facts that whittle away at the chain of knowledge (5.1.1) setup by the Guru for each islander on Day 1. share|cite|improve this answer      Sorry to deprive you of the honour of having the fourth longest post on the site with a score of $0$, but I had to upvote ;-) – Donkey_2009 Oct 9 '13 at 8:35      Thanks! I came to the party after it ended, but still wearing my party hat. – Matt Oct 9 '13 at 16:40 Ok may be we can see it as recursion with base case 2 blue eyed people. So lets talk about the case of three blue eyed persons. As everyone is highly logical persons they can easily think about the 2 eyed base case. So lets take one of the three blue eyed person. He can see other 2 blue eyed persons, So as he can easily deduce the 2 eyed situation so he knows that the second day the other two must leave. But as the case they don't leave. So he can easily say he also have blue eyes. So they all leave on 3rd day. Similarly. in case of 4 blue eyed persons. Lets take one person and he can easily deduce the situation of three. So if there are M blue eyed persons then at Nth day all will leave. share|cite|improve this answer I think the rationale here is correct, but I do think the solution is wrong. I think our island critters can deduce that they should leave after 2 days. All blue-eyed people see 99 people with blue eyes, and all brown eyed people see 100 people with blue eyes. They will reason as in the solution, based on common knowledge. However, they don't have to wait 98 days, because everybody knows that nothing will happen the first 98 days. This is based on common knowledge. So logically, they can all be skipped. So on day 1, nobody leaves, on day 2, all people with blue eyes leave. share|cite|improve this answer I'll add one answer to the 99 answers to appear here :) I'll simulate a situation with $3$ islanders, named X, Y and Z. By symmetry, every predicate of the form $P(X, Y, Z)$ that holds will also hold under any permutation of $X$, $Y$ and $Z$, so I will not present the permuted statements. Let's start after the Guru speaks: $X$ thinks that 1. If I don't have blue eyes, then $Y$ and $Z$ would be the only people with blue eyes. $Y$ would think that 1. If I don't have blue eyes, then $Z$ would see no one with blue eyes, and leave the next day. 2. So, if $Z$ does not leave the next day, I must have blue eyes, and we both leave on the second day. 2. So, if $Y$ and $Z$ do not leave in two days, I must have blue eyes, and we all leave on the third day. Now go back to before the Guru speaks. Why would this line of reasoning not work? The obstruction is the innermost reasoning, where only one person has blue eyes. The sequence of reasoning starts by assuming "If I don't have blue eyes", and that propagates to the next person until there is only one person left. Note that this is all in one person's head. In this particular instance, where we have $3$ people, $X$'s reasoning in 1.2 above relies on the fact that $X$ knows that $Y$ knows that $Z$ knows $B$ where $B$ is the statement "there is at least one person with blue eyes". Note that this statement is not true before the Guru speaks. $X$ only knows that $Z$ knows $B$. $X$ does not know that $Y$ knows that $Z$ knows $B$, because $X$ doesn't know $X$'s eye color, and $X$ cannot assume that $Y$ knows $Y$'s eye color either. So, the Guru does add the information: $X$ knows that $Y$ knows that $Z$ knows $B$. Some may argue that 3 people is such a special case. Let's consider when we add another person. Let's say $W$ is added to the system. $W$ also has blue eyes. How can we reason that $X$ knows that $Y$ knows that $Z$ knows that $W$ knows $B$ is not true before the Guru speaks? Again, $X$ doesn't know $X$'s eye color. When $X$ thinks for $Y$, $X$ knows that $Y$ knows that $Z$ knows $B$, because $X$ knows that $Y$ can see that $Z$ sees $W$ with blue eyes. Note that we need $W$'s blue eyes for $X$'s reasoning for $Y$. The fact that $Z$ also sees $X$ with blue eyes is known to $Y$, but is not known to $Y$ in $X$'s mind. Permuting people, we know that $Y$ knows that $Z$ knows that $W$ knows $B$ because $Y$ sees that $Z$ sees $W$ and $X$ with blue eyes. But $Y$ in $X$'s mind does not know this, because it relies on the fact unknown to $X$: that $X$ has blue eyes. I believe this should be enough to convince most people that this situation generalizes to an arbitrary number of people. This is an answer to question 1: the consequence of Guru's speaking is that everyone knows that everyone knows that ... (repeat as many times as desired) that $B$ holds. As some people have suggested, one variant of the problem is when the Guru tells everyone personally about $B$. This would yield no new information, and nothing will ever change. Another interesting variant is if the Guru is specific and says that "$X$ has blue eyes" instead of just "someone has blue eyes". The consequence is obvious: $X$ will leave the next day. Everyone else will retain their behavior. It is somewhat counterintuitive because the sentence "$X$ has blue eyes" seems to give more information than "someone has blue eyes". One explanation of this situation that I can think of is that the statement "$X$ has blue eyes" actually gives no more information except to $X$, and the rules of the game force $X$ to leave the next day, so $X$ cannot give back information to others after $X$ leaves. In a sense, more information on the first day could lead to less information on all the following days because of the island rules. Questions 2 and 3 are kind of answered, but I can try to elaborate more. The reason smaller cases are relevant is because the strategy that each person derives from following "If I don't have blue eyes, then the next would think..." repeatedly until the one person case is reached. In a way, one can say that the small cases help everyone form a strategy. This can sound ignorant or deep, depending on what you think my understanding of the problem is. To me, it is quite an appropriate answer to the question. To answer question 3, suppose everyone had a chance to discuss the strategy before the problem starts (without seeing each other's eyes). They could try to agree on cutting down the number of days if they can agree what the number is. Unfortunately, this is impossible. The problem is this "common number" has to be built from another relevant number, and each person only has as a source the number of blue-eyed people he/she sees. Since not everyone sees the same number of blue-eyed people, not everyone deduces the same number of days to cut down. I will demonstrate why my strategy of cutting down the number of days will not work. (I do think my strategy is quite general though.) Suppose $f(x)$ is the number of days a person who sees $x$ blue-eyed people will cut down. $f$ should be a non-decreasing function, and $f(x) \le x - 1$ for every positive integer $x$. If there are $n$ blue-eyed people, these blue-eyed people will cut down $f(n - 1)$ days, while those without blue eyes will cut down $f(n) \ge f(n - 1)$ days. If $f(n) = f(n - 1)$, then it's a jackpot, and everyone cuts down the same number of days. Otherwise, those without blue eyes will cut down more days than those with blue eyes, and end up leaving on the same day as (or even before) those with blue eyes. So, to make it safe for all $x$, we must have $f(x) = f(x - 1)$ for all $x$. Since $f(1) = 0$, we end up with $f(x) = 0$ for all $x$. share|cite|improve this answer 1. What is the quantified piece of information that the Guru provides that each person did not already have? • Certainty and possibility opening. Everyone knew each other's eyes color, up until the Guru stated someone had blue eyes. That someone could be you, and that is reciprocal to all players. He gave "a hint" that your eye color was blue, a hint you could eventually check. 2. Each person knows, from the beginning, that there are no less than 99 blue-eyed people on the island. How, then, is considering the 1 and 2-person cases relevant, if they can all rule them out immediately as possibilities? • Although they aren't possibilities, they are logical building blocks. The 1-person case is singular, but the 2-person case allows for the 3, 4, 5, n people cases to be inferred from it. 3. Why do they have to wait 99 nights if, on the first 98 or so of these nights, they're simply verifying something that they already know? • Rephrasing: Why do a n group of people have to wait n-1 nights if on the first n-2 nights they are simply verifying something they know? The fact is, as stated on 1., they don't know their eye's colors, they have a hint that their eye's color is blue. As stated on 2., the process is based in inference, so, they need to check that no one figured their eye color during the n-1 nights to finally conclude that their eye color is, by the Guru's hint, blue. Since this process is common to all players, after n-1 nights everyone figures, by deduction, that each one's eye color is blue and as such, exit the island. share|cite|improve this answer Let's skip over the original solution, I'm going to assume you read that. I'm going to answer the questions stated: Imagine we have 2 people on this island of 201. Bob, who has blue eyes, and jane, who has brown eye's. 1) What is the quantified piece of information that the Guru provides that each person did not already have? The Guru gave information about the colour of bob's and Jane's eye's. Namely, Bob and Jane do not know if they have blue, brown, red or green eye's. They still don't know anything about there own eye colour on day 1, but following the original solution, they can deduce it on day 100. 2) Each person knows, from the beginning, that there are no less than 99 blue-eyed people on the island. How, then, is considering the 1 and 2-person cases relevant, if they can all rule them out immediately as possibilities? Imagine that Bob tries to be smart. He decide that no-one will leave the first 99 days, since there are 99 blue-eyed people excluding himself. Jane also tries to be smart, she decide that no-one will leave the first 100 days, since there are 100 blue-eyed people excluding herself. But now what? They can't skip 99 or 100 days, because then the difference between what a blue-eyed and a brown-eyed person would do it no more. Hence they can't deduce anything from the other not leaving on day 1. 3) Why do they have to wait 99 nights if, on the first 98 or so of these nights, they're simply verifying something that they already know? Because they might be verifying something they already know, but they also communicate something they can not communicate otherwise. Bob know he can leave on day 100. Jane know she can leave on day 101. There is no way for them to communicate this information any other way. Ps. How bummed out must Jane be to see 100 blue-eyed people leave on day 100. Perhaps the Guru can be nice and say "I can see someone who has brown eyes.", so that history can repeat itself and 100 brown-eyed people can leave another 100 day's later. share|cite|improve this answer      Who downvoted this, and WHY? – Dorus Sep 12 '13 at 15:28 1. The quantifiable piece of information provided is that at least one person on the island has to have blue eyes. Since they are perfect, logical machines, they will count how many individuals have blue eyes, and come to the conclusion that, if no other person has blue eyes, then they must, and they must leave the island. 2. If, however, they see at least one person with blue eyes, they have only the evidence that one person has blue eyes, and thus, shall remain. If, however, they see TWO blue-eyed people, they must assume that these two blue-eyed people are assuming that the other is the only one remaining, and thus shall wait for the two to leave. If, however, they see THREE blue eye people, they must assuem that each blue-eyed person is assuming there are two blue-eyed people, and that each of those two blue-eyed people will leave. Because they are perfectly logical beings, they can make no presumption of their own eye color, but cannot be aware of it either. But they are aware that other individuals can observe eye colors, and that they will base their own presumptions on those eye colors that they see, so they will presume that their own eye color is excluded, and that each blue-eyed individual also excludes their own eye color. 3. Is actually a short-form explanation of 2. In much, much shorter form, it is because they must exclude themselves from the count, even if they have blue eyes. Ironically, not a single person on the island will know their own eye color until the last day becsause of this exlusion requirement (They MUST stay if they do not have blue eyes), because they assume every blue-eyed person is exluding themselves as well. share|cite|improve this answer 1   the question is what new piece of information do the guru's words provide. Since they each know blue-eyed people exist, your answer does not address that. – Ittay Weiss Sep 10 '13 at 18:39      They all already know blue-eyed people exist, IF there is more than one blue-eyed person. If there are none that they can see, they must be the one. It's an absolute quantity. At LEAST one, but possibly more. They haven't been told how many, just that at least one must exist, because presumably the oracle cannot lie. A more interesting question might ask what would happen if the oracle CAN lie. I suppose a better way to phrase the first conclusion is that at least one blue-eyed person can be observed by the oracle. – Zibbobz Sep 10 '13 at 18:47      but each of them already knows that there is at least one person with blue eyes since there are lots and lots of blue-eyed people. – Ittay Weiss Sep 10 '13 at 19:13      And they can come to the conlusion that if they are not blue-eyed, then that many blue eyed people must exist, but if they ARE, then there must be that many +1, all information that they could already conclude. It is not the fact that blue eyed people exist that they were informed of, nor the number that exist, but that there is a quantity that can be observed and includes as many people as either they can see, or they can see plus one. Without the knowledge, they could only conclude that a certain number exists, and they cannot conclude what anyone else knows either. – Zibbobz Sep 10 '13 at 19:27      I don't understand your distinction between they can conclude that "there is a quantity that can be observed and included as many people as either they can see, or they can see plus 1" and that without the knowledge "they could only conclude that a certain number exists, and they cannot conclude what anyone else knows either". Of course with and without the information they can conclude quite a lot about their own knowledge and the knowledge of others. For instance, "everybody knows blued eyed people exist" is a statement known by everybody. So, I think the distinction you aim at is unclear. – Ittay Weiss Sep 10 '13 at 19:39 protected by Michael Greinecker Dec 20 '14 at 23:04 Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site. Would you like to answer one of these unanswered questions instead? Not the answer you're looking for? Browse other questions tagged or ask your own question.
__label__pos
0.952146
Toggle menu Toggle personal menu Not logged in Your IP address will be publicly visible if you make any edits. User:Colby Russell/Draft:Build profiles From triplescripts.org wiki The simplest possible build command should be `build main.src`, which should do something predictable and useful. By addressing this want, we're presented with an opportunity to solve another nagging problem. This is the origin of the the "default build profile" and the new `publish` command. First the related problem: acute concern that people are unlikely to respect our exhortation to respect the triple script invariants and not impinge/torpedo the triple script file format. exhortation: https://triplescripts.org/format/ So we introduce the "default build profile". When building a program with trplkt, the default profile does not output a file that conforms to the triple script file format. Instead, it (a) uses double slash delimiters, and (b) includes a "byline". Both serve to interfere with dissemination of non-triple scripts masquerading as valid triple scripts triple slash delimiter. The byline is repeated, appearing as the first line in the file and then again as the last line. Double slash script delimiters are used as a hedge against the removal of the first byline. Any file which includes a byline (whether one or both) is to be considered an invalid triple script (regardless of whether triple slash delimiters are used). In the default (aka prerelease) build profile, triple slash directives otherwise still used. Significant, because they're actually part of the dialect--with `/// import`, for example, being one possible representation of the "same" import token (same-ish as `import`, just different forms; they actually vary by 1 bit of information) XXX on second thought, triple slash directives (excluding byline?) should be changed to use prefix of `// @` or `// !` or `// ?` or something. NB: this affects tokenization even for normal triple scripts (otherwise you get collisions) The byline acts as a strong signal that this is *not* a triple script. Byline is the `$sum$` attribute followed by fixed with hex encoding of a checksum (CRC-32?), hex encoding of the time of the build (measured in seconds since New Years Day, 2000), and then the text of the build command-line arguments (the "build" is implied) Example/candidate outputs: /// $sum$: 0x12471248, 0x269B4EE0, `./src/TripleKit.js -m ./src/main.js` /// $sum$: 0x12471248, 0x269B4EE0 // ./src/TripleKit.js -m ./src/main.js /// $sum$: 0x64771248, 0x269B4EE0 // ./src/main.src XXX Byline should/could also encode the version used to build it (but this can wait for the last release before 1.0?) To publish a proper triple script, trplkt will include a new `publish` command, which shall take a build using the default profile and emit a proper triple script instead. Triple script authors will be encouraged to always test their work with a simple `build main.src` during development (and include instructions in the README for the same, for most contributor-friendly approach) Then project maintainers can run it through the `publish` command when they are ready to disseminate it to others. This makes the creation of a file carrying the correct triple script file magic a deliberate act, but a natural enough one that make sense in its place in the workflow. We expect this will be an attractive enough workflow to dicourage folks from torpedoing attempts to allow the triple script file format actually signify something and we expect this to provide a good jumping-off point for people to further explore the concatenated t-block format (read: using d-blocks). Changes to current conventions: Program authors are encouraged to make the top-level module aka the "heart" of the program the first import in main.src. Need to encourage people setting out to write triple scripts by hand to not use triple slash delimiters, and ideally include something that might be dissimilar to the format of the byline, but still serves a similar purpose of disrupting accidental dissemination of scripts that appear (by formatting) to be full-fledged triple scripts even when they really aren't. It could be as simple as: /// $profile$: "handcrafted" or: /// Bumblefudge, a Lisp pretty printer by Mavis Turpin ... and we can even encourage people to omit imports/exports on their first draft, and we'll provide tooling (a helper to "publish") to suss out the correct annotations. (We could call this the "handcrafted" build profile?) XXX requires deep (total) total parsing, rather than our current naive partial parsing strategy... Other notes: If the byline is missing, `publish` will scan the file to make sure it passes basic sniff tests and provide verbose output about the exact decomposition it came up with, for user review. Since the byline would include the full command-line arguments, we can also check if we're able to reproduce the output based on the transient decomposition. If this fails, we will still complete the build, but print warnings to stderr (or equivalent) and return a non-zero exit code. If the byline *is* included, but it has a mismatched checksum, then we will outright refuse to perform the transformation unless `--force` is passed to the build command. --- /// "handcrafted" //? <script> class Foo { } //? </script> //? <script> class Bar { } //? </script> //? <script> class Baz { } //? </script> //? <script> window.onload = () => { document.write(Foo.name); document.write(Bar.name); document.write(Baz.name); } //? </script> 2020 October 09: So this is implemented now in trplkt 0.11, but not necessarily following the design laid out above. There is a problem, though, which is that if we want the generic (g-block-based) form to be suitable for the Web (and it's clear that we do, necessarily...), then we have to do something about the close delimiters. Testing a very simple example, where we create an ordinary HTML document, but add a simple script element after the body and dump an unaltered g-block script into it surfaces concerns about parsing. First, and most minor, each block gets its own script parent, which is not necessarily what we want. Secondly, the stray `//? ` show up in between blocks, which we need to do something about. However, if we omit all close delimiters except for the one on the last line, then we have no strays to take care of, and everything ends up in one script parent. Something to think about (e-profile? i.e. "embedded"/"embeddable"?) Cookies help us deliver our services. By using our services, you agree to our use of cookies.
__label__pos
0.810931
29 - ¿Que es eso de los PPAs? 29 - ¿Que es eso de los PPAs? ¿Que es un repositorio?¿Que es un PPA?¿Para que se utilizan?¿Son seguros?¿Como quitarlos?¿Porque es mas seguro instalar de PPA que instalar de paquete deb? 1:25 -3:15 Si utilizas Ubuntu o alguna distribución derivada de Ubuntu seguro que has visto, leído o escuchado algo sobre añadir un repositorio un repositorio PPA. En numerosos sitios, para que instales una aplicación te indican que realices algunos pasos en el terminal. Algo que contiene un add-apt-repository. En ese paso, lo que estás añadiendo es un repositorio personal. Un lugar donde hay paquetes de software subido por un persona como tu o como yo. Pero ¿que es eso de un PPA?¿Para que se utiliza?¿Es seguro?¿Como se elimina? ¿Que es eso de los PPAs? ¿Que es eso de los PPAs? Sobre los repositorios Antes que nada… si eres nuevo, es probable que no sepas lo que es un repositorio. Un repositorio no es mas que un almacén de software. Al final es lo que hay detrás de la tienda de Ubuntu. En Ubuntu y derivados hay repositorios oficiales y no oficiales. Para cada versión de Ubuntu tienes cuatro repositorios oficiales • Main Software libre soportado por Canonical • Universe Software libre mantenido por la comunidad • Restricted Controladores propietarios. • Multiverse Software propietario o bajo copyright o con aspectos legales Si vas a http://archive.ubuntu.com/ubuntu/dists Puedes verlo en vivo y en directo Puedes habilitar estos repositorios desde Software y actualizaciones en Ubuntu A partir cualquier paquete que puedes instalarlo desde el Centro de Software de Ubuntu o la tienda de tu distribución o bien utilizando apt. Si no conoces apt te recomiendo que leas el artículo sobre apt vs apt-get ¿Que es un PPA? PPA es Personal Package Archive. No es mas que un repositorio o almacén de archivos personal hospedado en Launchpad. ¿Porque se utilizan? Ubuntu controla que software está disponible en sus repositorios y que versiones. Cuando aparece una nueva aplicación o una nueva versión de la aplicación esta no se incorpora de forma inmediata. Se tiene que comprobar que la nueva aplicación, o la nueva versión es compatible con el sistema, para de esta manera contribuir a la estabilidad del mismo. ¿Pero que pasa cuando un desarrollador libera una nueva aplicación o una nueva versión? Simplemente que no la podremos utilizar hasta que no la apruebe Ubuntu, y eso puede suceder en unas semanas, meses o quizá nunca. Otra situación es cuando se libera una versión beta… ¿como puede permitir el desarrollador que la probemos? Uso y funcionamiento El uso es realmente sencillo, tan solo tenemos que utilizar las siguientes líneas sudo add-apt-repository ppa:dr-akulavich/lighttable sudo apt update sudo apt install my-weather-indicator Esto es lo siguiente, • La primera línea nos permite añadir el repositorio • La segunda actualiza la lista de paquetes que se pueden instalar en nuestro dispositivo, • Mientras que la tercera instala el paquete En las últimas versiones de Ubuntu no es necesario actualizar la lista de paquetes Esto que hacemos no es mas que añadir un nuevo archivo a /etc/apt/sources.list.d/ que no es mas que la forma tradicional de añadir repositorios. Pero de esta manera no tenemos que preocuparnos de las direcciones. Al final, Ubuntu nos lo pone lo mas fácil posible, tanto a desarrolladores como a usuarios para utilizar las aplicaciones que no están disponibles en los repositorios oficiales. Algunos desarrolladores cuando instalas un paquete deb directamente añade las entradas correspondientes para su repositorio. ¿Porque utilizar PPA y no paquetes deb directamente? Por las actualizaciones. Si instalas un paquete no tienes garantizado que en caso de una actualización de seguridad o del tipo que sea… Como he comentado anteriormente algunos desarrolladores como Google, añaden su repositorio automáticamente. PPA oficiales y no oficiales Los correspondientes a un desarrollador son oficiales, mientras que los de terceros son no oficiales ¿Porque existen no oficiales? Porque el desarrollador no crea la suya propia, pero si que facilita el código fuente ¿Hay aplicación para mi Ubuntu en la PPA? Una de las problemas mas habituales que me indican es que cuando añaden alguna de mis PPA les da un error. Habitualmente esto es por que no hay versión de la aplicación para su versión de Ubuntu. Para saber la versión de Ubuntu simplemente cat /etc/os-release Una vez hecho esto mira en la página de Launchpad, donde se hospeda la PPA para ver si hay aplicación para tu versión de Ubuntu. Si no la hay me lo dices. Aunque no haya aplicación para mi versión de Ubuntu, puedes intentar instalar la correspondiente a una versión anterior. PAra hacer esto simplemente descarga desde la página de Launchpad del repositorio el paquete deb. ¿Quitar un PPA? Lo puedes quitar fácilmente desde Software y actualizaciones. En la pestaña Otro software. Buscas el repositorio PPA que añadiste y lo quitas También puedes utilizar ppa-purge ¿Es seguro utilizar PPA? Un PPA podría ser un agujero de seguridad en tu equipo. Simplemente estás instalando aplicaciones de un repositorio desconocido en principio. Y remarco lo de desconocido en principio, porque con el paso del tiempo, un desconocido puede convertirse en tu mejor amigo. Así, por ejemplo, puedes confiar totalmente en que yo no voy a añadir ninguna porquería en mis repositorios. Pero no solo esto, todo lo que se sube a un repositorio está firmado por una persona, que es el responsable. Hasta donde yo se, y durante estos últimos diez años no conozco ningún caso de problemas con repositorios personales PPA. Con lo que definitivamente son seguros. Es mas, son mas seguros que instalar un paquete deb que te hayas descargado desde vete a saber donde. Y sobre todo, como te he mencionado tienes la ventaja de que el software instalado desde repositorio se actualiza y mantiene, mientras que ese paquete deb no. Deja un comentario Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *
__label__pos
0.879552
Book HomeCascading Style Sheets: The Definitive GuideSearch this book Friday 28th of April 2017 06:21:46 AM 10.8. Media Types and @-rules Don't get too excited yet. We aren't talking about media types in the sense of things like audio and video authoring. Well, not exactly, anyway. We're talking about creating rules for presentation within various kinds of media. The defined types of media thus far are: These are all values of @media, one of several new @-rules. Some others are: 10.8.1. Paged Media Since I just brought up paged media, I should probably mention that there are some new properties that apply to such media. Five of them apply to page breaks and where they appear: page-break-before page-break-after page-break-inside orphans widows The first two are used to control whether a page break should appear before or after a given element, and the latter two are common desktop publishing terms for the minimum number of lines that can appear at the end or beginning of a page. They mean the same thing in CSS2 as they do in desktop publishing. page-break-inside (first proposed by this author, as it happens) is used to define whether or not page breaks should be placed inside a given element. For example, you might not want unordered lists to have page breaks inside them. You would then declare UL {page-break-inside: avoid;}. The rendering agent (your printer, for example) would avoid breaking unordered lists whenever possible. There is also size, which is simply used to define whether a page should be printed in landscape or portrait mode and the length of each axis. If you plan to print your page to a professional printing system, you might want to use marks, which can apply either cross or crop marks to your page. Thus you might declare: @page {size: 8.5in 11in; margin: 0.5in; marks: cross;} This will set the pages to be U.S. letter-standard, 8.5 inches wide by 11 inches tall, and place cross marks in the corners of each page. In addition, there are the new pseudo-classes :left , :right, and :first, all of which are applied only to the @page rule. Thus, you could set different margins for left and right pages in double-sided printing: @page:left {margin-left: 0.75in; margin-right: 1in;} @page:right{margin-left: 1in; margin-right: 0.75in;} The :first selector applies only to the first page of a document, so that you could give it a larger top margin or a bigger font size: @page:first {margin-top: 2in; font-size: 150%;} interesting part will be recreating the way they hang out into the blank space to the left of the column. If we just give these pictures the style float: left, they'll be completely contained within the column. However, since the first column has a left margin, all we have to do is give images a negative margin-left, like this: IMG {float: left; margin-left: -2.5em;} 10.8.2. The Spoken Word To round things out, we'll cover some of the properties in the area of aural style sheets. These are properties that help define how a speaking browser will actually speak the page. This may not be important to many people, but for the visually impaired, these properties are a necessity. First off, there is voice-family, which is much the same as font-family in its structure: the author can define both a specific voice and a generic voice family. There are several properties controlling the speed at which the page is read (speech-rate), as well as properties for the pitch , pitch-range, stress, richness, and volume of a given voice. There are also properties that let you control how acronyms, punctuation, dates, numerals, and time are spoken. There are ways to specify audio cues, which can be played before, during, or after a given element (such as a hyperlink), ways to insert pauses before or after elements, and even the ability to control the apparent position in space from which a sound comes via the properties azimuth and elevation. With these last two properties, you could define a style sheet where the text is read by a voice "in front of" the user, whereas background music comes from "behind" and audio cues come from "above" the user! Library Navigation Links Copyright © 2002 O'Reilly & Associates. All rights reserved. top: -5em; bottom: 50%; left: 75%; right: -3em; Figure 9-3 Figure 9-3. Positioning an element beyond its containing block Now let's see why leaving out width andheight isn't always a bad thing inpositioning, as well as how declaring them can work to youradvantage. to a point below any previous floats, as illustrated by Figure 8-36 (where the floats start on the next line in order to more clearly illustrate the principle at work here). This rule first appeared in CSS2, to correct its omission in CSS1. Figure 8-36 Figure 8-36. If there isn't room, floats get pushed to a new line 8. A floating element must be placed as high as possible. Subject to the restrictions introduced by the previous seven rules, of course. Historically, browsers aligned the top of a floated around" it. This is familiar behavior with floated images, butthe same is true if you float a paragraph, for example. In Figure 7-64, we can see this effect (a margin has beenadded to make the situation more clear): P.aside {float: left; width: 5em; margin: 1em;} Figure 7-64 Figure 7-64. A floating paragraph One of the first interesting things tonotice about floated elements is that margins around floated elementsdo not collapse. If you float an image with 20-pixel margins, thereH1 elements to have a top margin of 10 pixels, aright margin of 20 pixels, a bottom margin of 15 pixels, and a leftmargin of 5 pixels, here's all we need: H1 {margin: 10px 20px 15px 5px; background-color: silver;} As Figure 7-8 reveals, we have what we wanted. Theorder of the values is obviously important, and follows this pattern: margin: top right bottom left Figure 7-8 Figure 7-8. Uneven margins Here, although the top and bottom margins will stay constant in any situation, the side margins will change based on the width of the browser window. This of course assumes that all H1 elements are the child of the BODY element and that BODY is as wide as the browser window. More properly stated, the side margins of H1 elements will be 10% of the width of the H1's parent element. Let's revisit that example for a moment:
__label__pos
0.840211
How to Automate the Software Bill of Materials (SBOM) How to Automate the Software Bill of Materials [SBOM] Share article twitter linkedin medium facebook Software Bill of Materials (SBOMs) has always been a simple, powerful, and often overlooked security concept. In the software development landscape, it is common for developers to embed chunks of third-party codebases in their applications. Though this makes for an easy alternative to spending hours writing code from scratch, it poses potential security risks. Therefore, understanding what code you include in your software is critical for a developer, technology, or security officer.  Recent attacks of the SolarWinds and Log4J have emphasized the importance of SBOM as a security best practice by showing that even mighty organizations can easily fall victim to malicious practices. But despite its capability to form a security wall between cyberattacks and organizations, enterprises show reluctance to implement SBOM. This has forced the US Government to release an Executive Order to strengthen cybersecurity and specifically highlight the role SBOMs can play. Organizations, however, rally with challenges in implementing SBOMs manually. In this article, we define SBOM, discuss its benefits, and shed light on how to automate the creation of SBOMs in three different ways. What is a Software Bill of Materials (SBOM)? Software Bill of Materials (SBOM) is a comprehensive list of all the components and elements that form a software product. It gives detailed information on the components like dependencies, supply chain relationships, and licenses in proprietary and open source software. Primarily, SBOMs help you manage risks by enabling complete visibility into the software you are adding to your product. SBOM is similar to the list of ingredients you see on packaged food–the number of calories it involves, preservatives used, and other things such as salt, sugar, and flavourings. SBOM is derived from the Bill of Materials (BOM) used in the manufacturing industry. BOM consists of structured information on all manufacturers’ raw materials, components, and parts. This way, you can easily track any faulty component directly to its place of origin and take necessary remediation steps. Similarly, SBOMs identify unique components that contain security flaws and can put your software at risk. Created to be shared between organizations, SBOMs are written in machine-readable metadata. It contains the below-mentioned aspects:  • Open-source libraries that form application dependencies • Plugins and add-ons that an application uses • In-house custom source code prepared by developers • Component information like versions, licensing status, and patch details Why is a Software Bill of Materials (SBOM) important? Lower costs With SBOMs, you can employ a streamlined workflow by reducing critical time to remediate security threats. The documented software components enable you to proactively verify if the software contains any deficient components. This saves a great deal of the cost of efficient scanning resources and the financial burden resulting from cyberattacks. Reduce code bloat When using open-source code blocks, you often end up including different versions of the code with the same functionality. Further, these different versions come with unique defects. SBOMs help you standardize a common set of components to reduce the code bloat significantly. Optimize productivity SBOMs help you maximize your team’s productivity by eliminating unplanned and unscheduled work. By enabling you greater visibility into the codebase you’re using, you can better prioritize and quickly deliver code updates. Once you identify the vulnerable components, you can initiate bug fixes without the extra hassle of further investigating the identified components. Effective monitoring Your capabilities to monitor components you used in your product for vulnerabilities increases exponentially with SBOMs. With them, your team will have to go through a lengthy and tedious process of evaluating each and every component to check if it contains any security risk. You can further assure your clients of better security. Easy EOL management It is possible that you use a third-party code that includes components that reach end-of-life (EOL). Such components lose support from their supplier or vendor. With SBOMs, you can be aware of EOL components and plan for alternate solutions. Although such components may not pose a risk, they could affect performance. Efficient code review By giving detailed information regarding every component and subcomponent included in the software, SBOMs simplify vulnerability detection and highlights any security concerns. Further, it helps you understand the time and effort needed to make your codebase bug-free. Policy compliance SBOM is, in a way, a compliance checklist on what components to use and what not to use, potential security risks, and other such policies. Therefore, employing SBOM enables compliance with policies. Why is Automation key? Formatted to be read by machines, SBOMs comprise an exhaustive list of information, so managing and processing this data manually can be complicated and time-draining. Therefore, automation plays a very critical role in ingesting and creating SBOMs. One major benefit of automating the process is consistency in implementing all the changes as and when they’re released. It also ensures cryptographical signing and verification of components. Furthermore, automation ensures continuous scanning to produce SBOMs, making them a part of the CI/CD pipeline. Another benefit of automation is that it offers ‘machine-speed,’ saving you time. It allows you to deploy your resources on other crucial tasks instead of manually putting together an SBOM. Also, when detecting vulnerabilities, identifying their location becomes an impractically long process. Automation also helps you to run frequent checks to update newly published vulnerabilities and mitigate them.  Below are the three key methods to automate SBOM creation. Three ways to automate SBOM creation 1. Use a composition analysis (SCA) tool You can optimize your resources by using software composition analysis (SCA) tools to automate the process of creating SBOM. SCA is a methodology for analyzing third-party software’s security, license compliance, and code legitimacy. It is an automated process born out of the need to boost productivity without compromising security and code quality. Ideally, SCA tools investigate software composition, including source code, manifest files, container images, and binary files. The open source components are then listed in SBOM and run against databases to identify vulnerabilities, licenses, and security information. SCA tools offer speed, reliability, and security by analyzing an overwhelming number of data points and compiling a comprehensive SBOM. With the emergence of cloud-native applications and complex software development methodologies, SCA tools are gaining major prominence. In this example, we’ll explain how to create SBOM with FOSSA, an open-source dependency management tool ranked as the most significant SCA solution by the Forrester Wave. It helps you protect your software from open source risks such as supply chain threats and license violations. Generating SBOM with FOSSA can be done in four simple steps: 1. You begin by integrating FOSSA with a version control system like GitHub. You can also use its open-source CLI tool and scan your projects. FOSSA automatically scans your projects not just for direct dependencies but also for deep dependencies like licenses. 2. Once your projects are scanned and the details retrieved, you need to pick a reporting format from the ‘Reports’ tab. 3. After selecting the reporting format, you should pick which components you want to add to the report. You can add direct dependencies, deep dependencies, licensing summaries, and other license information. 4. Before generating the SBOM, you can customize the report with your company logo or any other information you want to add. 2. Use an open-source tool Another way of creating SBOM in an automated mode is through open-source tools. Although they help you generate SBOM at no cost, they usually cover only the basics. Also, they generally produce the report in two standard Data Exchange formats, CycloneDX and SPDX. To explain how you can take care of your SBOM automation through an open-source tool, we will cite the example of Paketo, a community-driven open-source project. Paketo supports multiple SBOM formats, including Syft JSON, SPDX JSON, and CycloneDX JSON in addition to Paketo-specific SBOM format. To generate SBOM using Paketo, you will need two tools: Pack CLI and Paketo Buildpacks. Paketo first creates buildpacks that can be used to build container images. Once these images are built, you can run an inspect command. This will automatically produce a full software bill of materials.  3. Use a plugin within CI/CD pipeline The third approach is to create and audit SBOMs within your DevOps pipeline. You can do that by using maven plugins at the build stage of the CI/CD workflow. Let’s go through the process briefly using the CycloneDX Maven Plugin. CycloneDX is OWASP’s lightweight SBOM standard for application security and software composite analysis. It comes with multiple tools for all environments. Its maven plugin generates SBOM featuring all types of dependencies in your projects. Firstly, you need to configure your pom.xml file, after which running the‘ mvn verify’ command will generate a bom.json file. This is followed by auditing SBOM files. For this, you will have to install the Dependency-Check SCA tool, which is a native Maven plugin. Once you run the SCA tool, you can generate your SBOM file again using the ‘mvn verify’ command. Staying on top of the hidden dangers of third-party apps  Generating SBOM is a best practice to secure your application from supply chain threats. With the federal government issuing an EO mandating it, SBOM implementation has become a must-have from a good-to-have feature. However, one point that we wanted to highlight in this blog is the automation of SBOM creation as an alternative to generating SBOMs manually, which is a tedious and time-taking process that could potentially lead to errors like missing out on listing a few defective components or EOL information. Chances are that your business relies on external code not protected by your existing security controls. Automation can help by speeding up SBOM creation and ensuring its accuracy. Explore our free resources on our blog and learning hub to learn how you can detect and mitigate the security and privacy dangers of third-party apps. Subscribe to our newsletter Stay updated with the latest news, articles, and insights from Reflectiz. Your Website looks great! But what’s happening behind the scenes? Discover your website blind spots and vulnerabilities before it’s too late! Try for free
__label__pos
0.713448
青ㄟ Lv 6 青ㄟ asked in 科學數學 · 1 decade ago 高等微積分 Find the closure of A={(x,y)€ R^2,x>y^2} 2 Answers Rating • Anonymous 1 decade ago Favorite Answer Answer: {(x,y)€ R^2: x>= y^2}. proof: Let A={(x,y)€ R^2: x>y^2}, B={(x,y)€ R^2: x = y^2 }, C={(x,y)€ R^2: x>= y^2}. We claim that the closure of A is C. Let p = (x,y) be a point in C, then every neighborhood of p contains a point q different from p, such that q in A. So every point of C is a limit point (cluster point ) of A. By definition of clousre, the closure of A is the union of A and all its limit points. Therefore, the closure of A is C. p.s. How do you find the set of all limit points of A? At first A is open, so every point of A is of course a limit point of A. Secondly, the point in the boundary is also a limit point of A However, the point in the complement of C forms a open set , so every point lying this set is not a limit point of A. Hence, the set of all limit points of A is C, i.e., the union of A and B. So, you just add the boundary B of A to A, you would get the closure of A , the smallest closed set containing A. 2007-12-14 12:30:39 補充: 如何判斷limit point? 要判斷平面上任意一點 P是否為集合A的 limit point, 就以P點為圓心 劃一個圓, 不管此圓的半徑有多小, 此圓的內部除去圓心的部分至少 要與A集合有一交點, 如果是這種情形的話, P點就是集合A的 limit point 了! • 進哥 Lv 7 1 decade ago 應該就是把不等號改成大於等於而已吧, 高微,好久以前的東西了,現在記憶中剩不到1/10. Still have questions? Get your answers by asking now.
__label__pos
0.984398
Search API Connector Documentation Print Import ActiveCampaign Data to Google Sheets In this guide, we’ll walk through how to pull data from the ActiveCampaign API directly into Google Sheets, using the API Connector add-on for Sheets. We’ll first get an API key from ActiveCampaign, and then set up a request to pull in email campaign data from ActiveCampaign to your spreadsheet. CONTENTS BEFORE YOU BEGIN Click here to install the API Connector add-on from the Google Marketplace. PART 1: GET YOUR ACTIVECAMPAIGN API KEY 1. Log in to ActiveCampaign and click “Settings” in the left side navigation menu. api-connector-activecampaign-img1 2. The Account Settings menu will appear. Click “Developer”. api-connector-activecampaign-img2 3. You should now see a page containing your API URL and Key. Keep the key handy as you’ll need it in a moment. Congrats! You’re now ready to use the ActiveCampaign API.api-connector-activecampaign-img3 PART 2: CREATE YOUR API REQUEST URL We’ll first set up a pull to view your contact list. • Base URL: https://YOUR_DOMAIN.api-us1.com/api/3/ • Endpoint: /contacts Putting it all together, we get the full API Request URL: https://YOUR_DOMAIN.api-us1.com/api/3/contacts PART 3: PULL ACTIVECAMPAIGN API DATA INTO SHEETS We can now enter all our values into API Connector and import ActiveCampaign data into Google Sheets. 1. Open up Google Sheets and click Add-ons > API Connector > Open. 2. In the Create Request tab, enter the Request URL we just created api-connector-activecampaign-img4 3. Under Headers, enter a key-value pair like this: Api-TokenYOUR_API_KEY Replace YOUR_API_KEY with the API key provided above in the first part. api-connector-activecampaign-img5 4. We don’t need extra authentication so just leave Authentication as None. Create a new tab and click ‘Set current’ to use that tab as your data destination. 5. Name your request and click Run. A moment later you’ll see ActiveCampaign data populate the AC_contacts tab in your Google Sheet:api-connector-activecampaign-img7 6. If your contacts utilize custom fields, these custom field values can be retrieved using the /fieldValues endpoint. As the fieldValues endpoint will only produce their ID, you can also use the /fields endpoint to get their name. Once you have all the values in Sheets, you can merge them together as desired using queries and other functions native to Sheets. 7. Change the endpoints as described in the documentation to retrieve different data. For example, changing it from /contacts to /campaigns will produce a list of all your ActiveCampaign campaigns. PART 4: HANDLE PAGINATION 1. Note Active Campaign’s limits on the number of records returned on a response. By default, only 20 records will be returned unless you use the ‘limit’ and ‘offset’ parameters as described in their documentation. api-connector-activecampaign-img8 To get 100 records, you’d use the ‘limit’ parameter and to return more than 100 you’d then make a second request using the ‘offset’ parameter. For example: page 1: https://site.api-us1.com/api/3/campaigns?limit=100 page 2: https://site.api-us1.com/api/3/campaigns?limit=100&offset=100 2. With API Connector you can either run these request URLs manually or loop through them automatically with offset-limit pagination handling (paid feature), like this: • API URL: enter your request URL as usual, making sure to include limit=100 • Pagination type: offset-limit • Offset parameter: offset • Limit parameter: limit • Limit value: 100 • Number of pages: enter the number of pages you’d like to fetch pagination-offset-limit Previous Import AccuWeather Data to Google Sheets Next Import AdRoll Data to Google Sheets Leave a Comment Table of Contents
__label__pos
0.758327
Linked Questions 18 votes 1 answer 3k views Command-line flags on front ends Our standard policy regarding command-line flags states that one should count the space before the dash (-) too, when there aren't any "free" options, since it ... 20 votes 1 answer 554 views General rules for custom languages and libraries The rules for what languages and libraries are allowed on this site seem to be scattered all over the place. I'm looking for a simple check list to know if a custom language or a custom library is ... 53 votes 0 answers 2k views How to count bytes FAQ We've got a lot of questions asking how to count the bytes in different situations. This question is here to put them all in one spot. General questions How to count "interactive" answers ... 7 votes 2 answers 437 views Interpreter flags for controlling output: considered cheating? I'm creating a programming language aimed at code golf puzzles. The language has an internal set of tapes, where the computations are saved and then retrieved to the user. At the end of the program, ... 15 votes 3 answers 708 views A proposal on command line flags [duplicate] I've been thinking about command line flags for a while, and I think that we should stop adding them to our byte counts. And instead consider different invocations to be different languages. Now ... 9 votes 5 answers 472 views Can interpreter flags causing major language differences be considered different versions of the language? I recently (this morning) extended Cubically to have an internal cube of variable size. The cube size is passed via a third interpreter flag (3 for a 3x3x3, ... 1 vote 1 answer 130 views Why should Brain-Flak pay for input when Python doesn't have to? Currently if you wish to take input as a string in Brain-Flak you are going to need the -A flag. This looks like: ... 12 votes 5 answers 438 views Potential execution flag rule break I am currently developing a golfing language for a specific type of task. I was hoping to use some command line flags for different options in the language. Since the language is intended to be a ... 0 votes 2 answers 84 views How do mandatory flags in new languages get counted [duplicate] This is different then this I am writing a new code-golf language and am thinking about making two modes. One would be stack and other tacit. However you would have to specify what one you want to ... 5 votes 3 answers 364 views How should we score compiler/interpreter build-time options? Prompted by this comment. The scoring of optional flags passed to compilers/interpreters has already been handled here and here. However there is another case of one more level of indirection. ... 7 votes 1 answer 240 views Bytes for changing a configuration file before running a program? In this answer using Python's turtle module, I discovered that some default settings for the turtles are set in a configuration file called ... 1 vote 0 answers 125 views Is the interpreter part of the language or a separate language? As I understand it, for our purposes a language is more or less defined by its implementation. That's one of the reasons why a program like Vim can also be "language". You just count keystrokes ... 13 votes 1 answer 707 views Is HTML/CSS a programming language? CSS can simulate rule 110 and thus is turing complete. Thus HTML + CSS is considered a programming language for our definition. However, as user @TimmyD mentioned appropriately HTML+CSS is Turing-... 12 votes 2 answers 490 views Is the PHP opening tag mandatory in byte count? After answering the first time on PPCG on "Source code ecological footprint" I had a little discussion about it. I found it's OK if your program throws notices or warnings. But I couldn't find ... 12 votes 2 answers 516 views PHP and warnings Sometimes when golfing in PHP, one uses tricks as reading/pushing to an inexistent variable, or using deprecated functions such as split(), but those things outputs ... 15 30 50 per page
__label__pos
0.797468
blob: 38e427238864237c29173b0ec0f1e87548ecf17b [file] [log] [blame] //===--- IsolateDeclarationCheck.cpp - clang-tidy -------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "IsolateDeclarationCheck.h" #include "../utils/LexerUtils.h" #include "clang/ASTMatchers/ASTMatchFinder.h" using namespace clang::ast_matchers; using namespace clang::tidy::utils::lexer; namespace clang { namespace tidy { namespace readability { namespace { AST_MATCHER(DeclStmt, isSingleDecl) { return Node.isSingleDecl(); } AST_MATCHER(DeclStmt, onlyDeclaresVariables) { return llvm::all_of(Node.decls(), [](Decl *D) { return isa<VarDecl>(D); }); } } // namespace void IsolateDeclarationCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(declStmt(onlyDeclaresVariables(), unless(isSingleDecl()), hasParent(compoundStmt())) .bind("decl_stmt"), this); } static SourceLocation findStartOfIndirection(SourceLocation Start, int Indirections, const SourceManager &SM, const LangOptions &LangOpts) { assert(Indirections >= 0 && "Indirections must be non-negative"); if (Indirections == 0) return Start; // Note that the post-fix decrement is necessary to perform the correct // number of transformations. while (Indirections-- != 0) { Start = findPreviousAnyTokenKind(Start, SM, LangOpts, tok::star, tok::amp); if (Start.isInvalid() || Start.isMacroID()) return SourceLocation(); } return Start; } static bool isMacroID(SourceRange R) { return R.getBegin().isMacroID() || R.getEnd().isMacroID(); } /// This function counts the number of written indirections for the given /// Type \p T. It does \b NOT resolve typedefs as it's a helper for lexing /// the source code. /// \see declRanges static int countIndirections(const Type *T, int Indirections = 0) { if (T->isFunctionPointerType()) { const auto *Pointee = T->getPointeeType()->castAs<FunctionType>(); return countIndirections( Pointee->getReturnType().IgnoreParens().getTypePtr(), ++Indirections); } // Note: Do not increment the 'Indirections' because it is not yet clear // if there is an indirection added in the source code of the array // declaration. if (const auto *AT = dyn_cast<ArrayType>(T)) return countIndirections(AT->getElementType().IgnoreParens().getTypePtr(), Indirections); if (isa<PointerType>(T) || isa<ReferenceType>(T)) return countIndirections(T->getPointeeType().IgnoreParens().getTypePtr(), ++Indirections); return Indirections; } static bool typeIsMemberPointer(const Type *T) { if (isa<ArrayType>(T)) return typeIsMemberPointer(T->getArrayElementTypeNoTypeQual()); if ((isa<PointerType>(T) || isa<ReferenceType>(T)) && isa<PointerType>(T->getPointeeType())) return typeIsMemberPointer(T->getPointeeType().getTypePtr()); return isa<MemberPointerType>(T); } /// This function tries to extract the SourceRanges that make up all /// declarations in this \c DeclStmt. /// /// The resulting vector has the structure {UnderlyingType, Decl1, Decl2, ...}. /// Each \c SourceRange is of the form [Begin, End). /// If any of the create ranges is invalid or in a macro the result will be /// \c None. /// If the \c DeclStmt contains only one declaration, the result is \c None. /// If the \c DeclStmt contains declarations other than \c VarDecl the result /// is \c None. /// /// \code /// int * ptr1 = nullptr, value = 42; /// // [ ][ ] [ ] - The ranges here are inclusive /// \endcode /// \todo Generalize this function to take other declarations than \c VarDecl. static Optional<std::vector<SourceRange>> declRanges(const DeclStmt *DS, const SourceManager &SM, const LangOptions &LangOpts) { std::size_t DeclCount = std::distance(DS->decl_begin(), DS->decl_end()); if (DeclCount < 2) return None; if (rangeContainsExpansionsOrDirectives(DS->getSourceRange(), SM, LangOpts)) return None; // The initial type of the declaration and each declaration has it's own // slice. This is necessary, because pointers and references bind only // to the local variable and not to all variables in the declaration. // Example: 'int *pointer, value = 42;' std::vector<SourceRange> Slices; Slices.reserve(DeclCount + 1); // Calculate the first slice, for now only variables are handled but in the // future this should be relaxed and support various kinds of declarations. const auto *FirstDecl = dyn_cast<VarDecl>(*DS->decl_begin()); if (FirstDecl == nullptr) return None; // FIXME: Member pointers are not transformed correctly right now, that's // why they are treated as problematic here. if (typeIsMemberPointer(FirstDecl->getType().IgnoreParens().getTypePtr())) return None; // Consider the following case: 'int * pointer, value = 42;' // Created slices (inclusive) [ ][ ] [ ] // Because 'getBeginLoc' points to the start of the variable *name*, the // location of the pointer must be determined separately. SourceLocation Start = findStartOfIndirection( FirstDecl->getLocation(), countIndirections(FirstDecl->getType().IgnoreParens().getTypePtr()), SM, LangOpts); // Fix function-pointer declarations that have a '(' in front of the // pointer. // Example: 'void (*f2)(int), (*g2)(int, float) = gg;' // Slices: [ ][ ] [ ] if (FirstDecl->getType()->isFunctionPointerType()) Start = findPreviousTokenKind(Start, SM, LangOpts, tok::l_paren); // It is possible that a declarator is wrapped with parens. // Example: 'float (((*f_ptr2)))[42], *f_ptr3, ((f_value2)) = 42.f;' // The slice for the type-part must not contain these parens. Consequently // 'Start' is moved to the most left paren if there are parens. while (true) { if (Start.isInvalid() || Start.isMacroID()) break; Token T = getPreviousToken(Start, SM, LangOpts); if (T.is(tok::l_paren)) { Start = findPreviousTokenStart(Start, SM, LangOpts); continue; } break; } SourceRange DeclRange(DS->getBeginLoc(), Start); if (DeclRange.isInvalid() || isMacroID(DeclRange)) return None; // The first slice, that is prepended to every isolated declaration, is // created. Slices.emplace_back(DeclRange); // Create all following slices that each declare a variable. SourceLocation DeclBegin = Start; for (const auto &Decl : DS->decls()) { const auto *CurrentDecl = cast<VarDecl>(Decl); // FIXME: Member pointers are not transformed correctly right now, that's // why they are treated as problematic here. if (typeIsMemberPointer(CurrentDecl->getType().IgnoreParens().getTypePtr())) return None; SourceLocation DeclEnd = CurrentDecl->hasInit() ? findNextTerminator(CurrentDecl->getInit()->getEndLoc(), SM, LangOpts) : findNextTerminator(CurrentDecl->getEndLoc(), SM, LangOpts); SourceRange VarNameRange(DeclBegin, DeclEnd); if (VarNameRange.isInvalid() || isMacroID(VarNameRange)) return None; Slices.emplace_back(VarNameRange); DeclBegin = DeclEnd.getLocWithOffset(1); } return Slices; } static Optional<std::vector<StringRef>> collectSourceRanges(llvm::ArrayRef<SourceRange> Ranges, const SourceManager &SM, const LangOptions &LangOpts) { std::vector<StringRef> Snippets; Snippets.reserve(Ranges.size()); for (const auto &Range : Ranges) { CharSourceRange CharRange = Lexer::getAsCharRange( CharSourceRange::getCharRange(Range.getBegin(), Range.getEnd()), SM, LangOpts); if (CharRange.isInvalid()) return None; bool InvalidText = false; StringRef Snippet = Lexer::getSourceText(CharRange, SM, LangOpts, &InvalidText); if (InvalidText) return None; Snippets.emplace_back(Snippet); } return Snippets; } /// Expects a vector {TypeSnippet, Firstdecl, SecondDecl, ...}. static std::vector<std::string> createIsolatedDecls(llvm::ArrayRef<StringRef> Snippets) { // The first section is the type snippet, which does not make a decl itself. assert(Snippets.size() > 2 && "Not enough snippets to create isolated decls"); std::vector<std::string> Decls(Snippets.size() - 1); for (std::size_t I = 1; I < Snippets.size(); ++I) Decls[I - 1] = Twine(Snippets[0]) .concat(Snippets[0].endswith(" ") ? "" : " ") .concat(Snippets[I].ltrim()) .concat(";") .str(); return Decls; } void IsolateDeclarationCheck::check(const MatchFinder::MatchResult &Result) { const auto *WholeDecl = Result.Nodes.getNodeAs<DeclStmt>("decl_stmt"); auto Diag = diag(WholeDecl->getBeginLoc(), "multiple declarations in a single statement reduces readability"); Optional<std::vector<SourceRange>> PotentialRanges = declRanges(WholeDecl, *Result.SourceManager, getLangOpts()); if (!PotentialRanges) return; Optional<std::vector<StringRef>> PotentialSnippets = collectSourceRanges( *PotentialRanges, *Result.SourceManager, getLangOpts()); if (!PotentialSnippets) return; std::vector<std::string> NewDecls = createIsolatedDecls(*PotentialSnippets); std::string Replacement = llvm::join( NewDecls, (Twine("\n") + Lexer::getIndentationForLine(WholeDecl->getBeginLoc(), *Result.SourceManager)) .str()); Diag << FixItHint::CreateReplacement(WholeDecl->getSourceRange(), Replacement); } } // namespace readability } // namespace tidy } // namespace clang
__label__pos
0.916619
How To Exit Python Virtual Environment Introduction Python is a powerful and flexible language that can be used to do almost anything. It’s also very easy to get into a groove with, which makes it great for learning new things or improving your skills. One of the key features of Python is the ability to create virtual environments, which allow you to isolate your Python projects and their dependencies. This can be incredibly useful when working on multiple projects or collaborating with others. In this article, we will explore everything you ever wanted to know about exiting Python Virtual Environment (VPE). Benefits of using virtual environments Virtual environments offer several benefits when it comes to managing your Python projects. Firstly, they allow you to have separate and isolated environments for different projects. This means that each project can have its own set of dependencies without interfering with each other. It also helps in avoiding version conflicts between different packages and libraries. Additionally, virtual environments make it easy to share your projects with others, as you can simply provide them with the environment configuration file. This ensures that they have the same environment setup as you, eliminating any compatibility issues. Another advantage of using virtual environments is the ability to easily switch between different Python versions. If you have multiple projects that require different Python versions, virtual environments allow you to manage this seamlessly. You can create a virtual environment with the desired Python version and activate it whenever you need to work on that specific project. This way, you can avoid the hassle of installing and uninstalling different Python versions on your system. Lastly, virtual environments provide a clean and organized way to manage your project dependencies. You can install specific versions of packages and libraries within each virtual environment without worrying about affecting other projects. This level of control ensures that your projects remain stable and consistent, even when working on updates or collaborating with others. Setting up a Python virtual environment Setting up a Python virtual environment is a straightforward process. The first step is to ensure that you have Python installed on your system. Once you have Python installed, you can use the built-in `venv` module to create a virtual environment. Open your terminal or command prompt and navigate to the directory where you want to create the virtual environment. Then, run the following command: “` python3 -m venv myenv “` This command will create a new directory called `myenv`, which will contain the virtual environment. You can replace `myenv` with the desired name for your virtual environment. Once the command is executed, you can navigate into the `myenv` directory by running: “` cd myenv “` To activate the virtual environment, run the following command: “` source bin/activate “` Congratulations! You have successfully set up and activated your Python virtual environment. You will notice that the prompt in your terminal or command prompt has changed to indicate that you are now working within the virtual environment. Activating and deactivating a virtual environment Activating and deactivating a virtual environment is a simple process. To activate a virtual environment, navigate to the directory where the virtual environment is located and run the following command: “` source bin/activate “` This command changes the environment variables to use the Python interpreter and packages installed within the virtual environment. You will see the name of the virtual environment in your terminal prompt, indicating that it is now active. To deactivate a virtual environment and return to your system’s default Python environment, simply run the following command: “` deactivate “` This will revert the environment variables to their original state, allowing you to switch between different virtual environments or use the global Python installation. Installing packages in a virtual environment Installing packages within a virtual environment is similar to installing them in a global Python environment. Once you have activated your virtual environment, you can use the `pip` package manager to install packages. Simply run the following command: “` pip install package_name “` Replace `package_name` with the name of the package you want to install. You can also specify the version of the package by appending `==version_number` to the package name. If you have a requirements file that lists all the required packages for your project, you can install them all at once using the following command: “` pip install -r requirements.txt “` This command reads the `requirements.txt` file and installs all the packages listed in it. Upgrading and removing packages in a virtual environment Upgrading packages within a virtual environment is similar to installing them. You can use the `pip` package manager to upgrade a package to the latest version. Simply run the following command: “` pip install –upgrade package_name “` Replace `package_name` with the name of the package you want to upgrade. To remove a package from your virtual environment, use the following command: “` pip uninstall package_name “` This command will uninstall the specified package from your virtual environment. Managing multiple virtual environments Managing multiple virtual environments is essential when working on multiple projects or collaborating with others. Each project can have its own virtual environment, ensuring that the dependencies and configurations are isolated. To create a new virtual environment, follow the steps outlined in the “Setting up a Python virtual environment” section. To switch between different virtual environments, deactivate the current virtual environment and activate the desired one. This can be done using the `deactivate` and `source bin/activate` commands, as mentioned earlier. To delete a virtual environment, simply delete its directory. Be cautious when deleting virtual environments, as this action is irreversible and will remove all the installed packages and configurations. Troubleshooting common issues with virtual environments Virtual environments are generally reliable, but occasionally, you may encounter some issues. One common issue is related to activating the virtual environment. If you see an error message stating that the activation script is not found, make sure you are in the correct directory and that the virtual environment was created properly. Another issue you might face is package conflicts. If you experience errors or unexpected behavior when running your Python code, it could be due to conflicting package versions. In such cases, it is recommended to create a new virtual environment, install the required packages, and test your code again. If you encounter any other issues, it is best to consult the official Python documentation or seek help from the Python community. Chances are, someone else has experienced a similar problem and can provide guidance or a solution. Best practices for using virtual environments To make the most of virtual environments, here are some best practices to keep in mind: – Organize your projects by creating individual directories for each project and placing the virtual environment inside the project directory. – Use version control systems like Git to track changes in your code and include the virtual environment configuration file in the repository. – Document the steps required to set up the virtual environment and any additional configuration or dependencies specific to your project. – Regularly update your packages and dependencies to ensure your projects stay secure and up-to-date. – Keep your virtual environments lightweight by only installing the necessary packages. Remove any unused or unnecessary packages to avoid clutter. By following these best practices, you can ensure that your virtual environments are efficient, maintainable, and scalable. Conclusion In this article, we explored the art of exiting Python Virtual Environment (VPE) and learned how to set up, activate, and deactivate virtual environments. We also discovered how to install, upgrade, and remove packages within a virtual environment, as well as manage multiple virtual environments. Additionally, we discussed common issues with virtual environments and best practices for using them effectively. Virtual environments are an essential tool for Python developers, allowing for project isolation, package management, and easy collaboration. By mastering the art of virtual environments, you can enhance your productivity and ensure the stability and consistency of your Python projects. So go ahead, create your virtual environments, and start building amazing Python applications! Leave a Reply Your email address will not be published. Required fields are marked {"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"} Related Posts
__label__pos
0.977027
Updated 2015-09-02 19:48:07 by pooryorick the Bourne Shell is one of the two predominant Unix shells. Reference  edit Wikipedia The Traditional Bourne Shell Family, Sven Mascheck, 2001-10-07 - 2014-05-03 Shell Command Language, The Open Group Base Specifications Issue 7, 2013 sh - shell, the standard command language interpreter, The Open Group Base Specifications Issue 6, 2004 Implementations  edit The Heirloom Bourne Shell Variants  edit Modern variants of the Bourne Shell include ash bash ksh, by David Korn a popular Bourne-compatible shell which is also available on Windows. zsh Load or Generate a Tcl List  edit Here are some shell functions to generate a Tcl list from a sequence of values, and to load a Tcl list into an array. They're handy, among other things, for storing and loading structured data. #! /bin/env bash : ${TCLSH:=tclsh} #generate a Tcl list from a sequence of arguments #example: mylist=$(tcllist one two three '{' ) tcllist () { "${TCLSH[@]}" - "$@" <<-'EOF' proc main {argv0 argv} { puts -nonewline [lrange $argv 0 end] } if {[catch { main $argv0 [lrange $argv[set argv {}] 1 end] } cres copts]} { puts stderr $copts puts stderr $cres exit 1 } EOF } #load a Tcl list into an array #example: tcllist_arr myarray '{one two {three four} five}' tcllist_arr () { eval $1'=()' while read -d $'\0'; do eval $1'[${#'$1'[*]}]="$REPLY"' done < <( "${TCLSH[@]}" - "${@:2:$#}" <<-'EOF' proc main {argv0 argv} { set list [lindex $argv 0] foreach item $list { puts -nonewline $item\0 } puts '' } if {[catch { main $argv0 [lrange $argv[set argv {}] 1 end] } cres copts]} { puts stderr $copts puts stderr $cres exit 1 } EOF ) } Conversely, here is a Tcl procedure to translate a string containing a sequence of words quoted in Bourne shell syntax into a list It handles arbitrariily-complex shell syntax, including command substitution, so watch out for injection attacks. proc shtotcl {value {sh bash}} { set script "printf 'puts \[lrange \$argv 1 end]' | \$1 - $value" return [exec $sh -c $script - [info nameofexecutable]] } Example: shtotcl $env(LDFLAGS) A more updated version of this code might be found at ycl::format::sh::shtotcl. Why Bourne Shell Is not Fit for Programming  edit It is well-known that csh is not fit for programming. Bourne shells also do not rise to the occasion. One big issue is their scoping rules. In the following example, $i in the second function interferes with $i in the first function: f1 () { local i for ((i=0 ;i<10 ;i++)); do echo $i f2 done } f2 () { for ((i=0 ;i<5 ;i++)); do #do something useful : done } f1 PYK 2015-08-04: In my opinion, one of the biggest reasons not to write programs in the Bourne shell language is that subshells swallow errors. In the following example, hello is not expected to print because the interpreter should exit when the unknown variable, $x is referenced, and indeed it doesn't: #! /bin/env sh set -u echo $x echo hello In sh scripting, however, it's extremely common to run commands in a subshell and collect their output. In the following example, hello does print even though the shell is configured as before: #! /bin/env sh set -u echo $(echo $x) echo hello Programming in a dynamic language is already adventurous enough. At least choose a sane dynamic language like Tcl. Beware the This is going to be a smallish script so I'll just write it in sh trap. EMJ 2015-09-02: Well, that's what they do (assuming you meant #!/bin/env sh both times and env really is in /bin - not on my system it isn't), but the second one rather misses the point, since it uses command substitution which just runs whatever and substitutes its output so that you actually get a blank line in the above case - after the error message about an undefined variable from the subshell, but the return status of the command (subshell or anything else) is not checked, only the output (nothing in this case) is used. That's how it works, nothing is propagated up from sub-processes. And yes, shell programming (any shell) is way too complicated, but if you're not allowed to use anything that's not already on the system, or that nobody else in the organisation knows... PYK 2015-09-02: I've fixed the sh-bang line, but my point is exactly that. A Bourne shell may provide a convenient interactive interface, but the behaviour of features such as command substitution make it unfit for writing non-trivial programs. You could even configure the shell to exit with an error status whenever any command invocation fails, and errors will still slide by unnoticed in the case of command substitution: #! /bin/env sh set -e set -u echo $(echo $x) echo hello But switch it up such that command substitution occurs in the context of variable assignment, and suddenly hello isn't printed: #! /bin/env sh set -e set -u a=$(echo $x) echo hello This type of inconsistent behaviour, makes Bourne shells unfit for the purpose of programming. Interactive use, maybe. Programming, no. dbohdan 2015-09-02: I think there's truth to the following PYK quote from the Tcl chatroom. How Tcl and the POSIX shell respectfully go about performing substitution is what makes one a serious competitor to Lisp and the other difficult merely to loop through a list of file names with. 04:20 < pooryorick> And the secret sauce of Tcl compared to sh is that Tcl doesn't rescan substituted values. 04:20 < pooryorick> In retrospect, I think that's Ousterhout's most remarkable contribution. See Also  edit Playing Bourne shell
__label__pos
0.948614
Brian B Brian B - 3 months ago 7 Javascript Question JavaScript API documentation - what does functionName([value[, arguments]]) notation mean? This question is related to: How to read API documentation for newbs?. However, that question does not cover the specific format I am asking about here where there are nested brackets (for example, [value[, args]] ). Although, I presume this could relate to any API, I'm looking at the D3.js API, specifically transition.ease() . I cannot figure out what the following means: transition.ease([value[, arguments]]) It's difficult to find out, as I don't know what search terms to Google! I just want to know: 1. How it is suppose to be read? 2. Is it a general/normal notation? I know how to use that D3 function; it's just the notation I'm interested in. Answer The documentation for transition.ease([value[, arguments]]) appears to make it relatively clear what they are attempting to say. In addition, it follows the "normal" syntax for methods of having optional arguments in []. In this case, it means that ease() is a method of transition. For the ease() method: ([value[, arguments]]), means passing any arguments is optional. Then, value[, arguments] is intended to mean that if the value argument is present, then an unrestricted number of additional arguments may optionally be present. I say "intended to mean" because normally being able to have multiples of an argument is indicated using an ellipse .... Thus, that would normally be: value[, arguments...]. From looking further at the documentation, it is clear that this is what was intended. Parsing the documentation (additional formatting by me): Specifies the transition easing function. If value is a function, it is used to ease the current parametric timing value t, which is typically in the range [0,1]. (At the end of a transition, t may be slightly greater than 1.) You can pass a function as the argument to transition.ease(). If you do, then it is used as the function to determine how the transition occurs. Otherwise, value is assumed to be a string and the arguments are passed to the d3.ease method to generate an easing function. The default easing function is "cubic-in-out". Note that it is not possible to customize the easing function per-element or per-attribute; however, if you use the "linear" easing function, you can apply custom easing inside your interpolator using attrTween or styleTween. If value is not a function, it is assumed that you are going to use d3.ease() as the transition function. In which case, all the arguments to transition.ease() are passed to d3.ease(). d3.ease() assumes that value (called type in the d3.ease() write-up) is a string. d3.ease(type[, arguments…]) has the ability to take additional optional arguments. In order for you to specify any additional arguments you desire to the d3.ease() function, transition.ease() also has the ability to accept such arguments and pass them to d3.ease(). Note: Looking at the interaction between transition.ease() and d3.ease() is where we see that transition.ease([value[, arguments]]) really should have been written with the ellipse as transition.ease([value[, arguments..]]). If that is not the intended use, then the described interaction with d3.ease() would not make sense. If ease is not specified, returns the easing function bound to the first non-null element in the transition. This is actually not clear. I expect that it contains a mistake in that "ease" should be "value". In which case it would read: If value is not specified, returns the easing function bound to the first non-null element in the transition. If this is actually what was intended, then not specifying any arguments to transition.ease() will result in getting back as a returned value the easing function which is bound to the first non-null element in the transition. This would be a normal and expected use of not supplying any arguments to such a function. Thus, I consider that it is quite likely that this issue really is a mistake in the documentation. This could be verified by either looking in the source code, or by experimentation. Comments
__label__pos
0.825699