 to ResponseStatus.UNKNOWN_STATUS,
    0x9000 to ResponseStatus.SUCCESS,
    0x6300 to ResponseStatus.AUTHENTICATION_FAILURE,
    0x6400 to ResponseStatus.PARAMETER_MISMATCH,
    0x6982 to ResponseStatus.SECURITY_STATUS_NOT_SATISFIED,
    0x6983 to ResponseStatus.KEY_EXPIRED,
    0x6985 to ResponseStatus.NO_KEY_REFERENCE,
    0x6A80 to ResponseStatus.NUMBER_PRECONDITION_WRONG,
    0x6A81 to ResponseStatus.UNSUPPORTED_FUNCTION,
    0x6A88 to ResponseStatus.KEY_NOT_FOUND
)

val pinStatus = mapOf(
    0x9000 to ResponseStatus.SUCCESS,
    0x62C1 to ResponseStatus.TRANSPORT_STATUS_TRANSPORT_PIN,
    0x62C7 to ResponseStatus.TRANSPORT_STATUS_EMPTY_PIN,
    0x62D0 to ResponseStatus.PASSWORD_DISABLED,
    0x63C0 to ResponseStatus.RETRY_COUNTER_COUNT_00,
    0x63C1 to ResponseStatus.RETRY_COUNTER_COUNT_01,
    0x63C2 to ResponseStatus.RETRY_COUNTER_COUNT_02,
    0x63C3 to ResponseStatus.RETRY_COUNTER_COUNT_03,
    0x6982 to ResponseStatus.SECURITY_STATUS_NOT_SATISFIED,
    0x6988 to ResponseStatus.PASSWORD_NOT_FOUND
)

val manageSecurityEnvironmentStatus = mapOf(
    0x9000 to ResponseStatus.SUCCESS,
    0x6A81 to ResponseStatus.UNSUPPORTED_FUNCTION,
    0x6A88 to ResponseStatus.KEY_NOT_FOUND
)

val psoComputeDigitalSignatureStatus = mapOf(
    0x9000 to ResponseStatus.SUCCESS,
    0x6400 to ResponseStatus.KEY_INVALID,
    0x6982 to ResponseStatus.SECURITY_STATUS_NOT_SATISFIED,
    0x6985 to ResponseStatus.NO_KEY_REFERENCE,
    0x6A81 to ResponseStatus.UNSUPPORTED_FUNCTION,
    0x6A88 to ResponseStatus.KEY_NOT_FOUND
)

val readStatus = mapOf(
    0x9000 to ResponseStatus.SUCCESS,
    0x6281 to ResponseStatus.CORRUPT_DATA_WARNING,
    0x6282 to ResponseStatus.END_OF_FILE_WARNING,
    0x6981 to ResponseStatus.WRONG_FILE_TYPE,
    0x6982 to ResponseStatus.SECURITY_STATUS_NOT_SATISFIED,
    0x6986 to ResponseStatus.NO_CURRENT_EF,
    0x6A82 to ResponseStatus.FILE_NOT_FOUND,
    0x6B00 to ResponseStatus.OFFSET_TOO_BIG
)

val selectStatus = mapOf(
    0x9000 to ResponseStatus.SUCCESS,
    0x6283 to ResponseStatus.FILE_DEACTIVATED,
    0x6285 to ResponseStatus.FILE_TERMINATED,
    0x6A82 to ResponseStatus.FILE_NOT_FOUND,
    0x6D00 to ResponseStatus.INSTRUCTION_NOT_SUPPORTED
)

val verifySecretStatus = mapOf(
    0x9000 to ResponseStatus.SUCCESS,
    0x63C0 to ResponseStatus.WRONG_SECRET_WARNING_COUNT_00,
    0x63C1 to ResponseStatus.WRONG_SECRET_WARNING_COUNT_01,
    0x63C2 to ResponseStatus.WRONG_SECRET_WARNING_COUNT_02,
    0x63C3 to ResponseStatus.WRONG_SECRET_WARNING_COUNT_03,
    0x6581 to ResponseStatus.MEMORY_FAILURE,
    0x6982 to ResponseStatus.SECURITY_STATUS_NOT_SATISFIED,
    0x6983 to ResponseS


\u5b9a\u540e\uff0c\u5b8b\u5bd2\u6bc5\u5c31\u53bb\u9648\u603b\u5904\u5f00\u4f1a\u3002\u5341\u4e94\u65e5\u665a\uff0c\u5b8b\u901a\u8fc7\u7535\u8bdd\u5e03\u7f6e\uff1a", "type": "appellation"}, {"text": "1\u3001\u7ee7\u7eed\u505a\u597d\u5de6\u6d3e\u7684\u5de5\u4f5c\u3002", "type": "appellation"}, {"text": "2\u3001\u7ee7\u7eed\u9e23\u653e\u3002", "type": "appellation"}, {"text": "3\u3001\u9aa8\u5e72\u7814\u7a76\u4e00\u4e0b\uff0c\u6709\u54ea\u4e9b\u505a\u5f97\u5bf9\uff0c\u8fd8\u6709\u54ea\u4e9b\u5b58\u5728\u7f3a\u70b9\uff0c\u5bf9\uff0c\u9519\uff0c\u5fc3\u4e2d\u8981\u6709\u6570\u3002", "type": "appellation"}, {"text": "4\u3001\u9648\u603b\u6307\u793a\u5bf9\u9ad8\u5360\u660e\u7684\u95ee\u9898\u4e0d\u8981\u5168\u90e8\u80af\u5b9a\uff0c\u4e5f\u4e0d\u8981\u5168\u90e8\u5426\u5b9a\uff0c\u575a\u6301\u5230\u4ec0\u4e48\u5730\u65b9\uff0c\u5fc3\u4e2d\u8981\u6709\u6570\u3002", "type": "appellation"}, {"text": "\u3017", "type": "appellation"}, {"text": "\u6765\u6e90\uff1a", "type": "source"}, {"text": "\u300a\u9648\u6bc5\u8bb2\u8bdd\u96c6\u300b\uff08\u5317\u4eac\uff1a\u9996\u90fd\u5927\u4e13\u9662\u6821\u7ea2\u536b\u5175\u7b2c\u4e09\u5


  </body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://ogp.me/ns#" xml:lang="en" lang="en">
  <head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

  	<!--added for registration bypass2 October 3,2002-->
<!-- CDS hostname /secj2kentwap09/ -->
<title>Panasonic, Sanyo to Pay $56.5 Million for Price Fixing - DOJ - WSJ.com</title>
<link rel="canonical" href="http://online.wsj.com/article/BT-CO-20130718-711176.html" />
  <meta property="og:url" content="http://online.wsj.com/article/BT-CO-20130718-711176.html" />
    <meta name="sitedomain" content="online.wsj.com" />
<meta name="primaryproduct" content="Online Journal" />
<meta name="ctype" content="article" />
<meta name="subsection" content="T   Wire" />
<meta name="author" content="" />
<meta name="language" content="en" />
<meta name="displayname" content="T   Wire" />
<meta name="pagename" content="T   Wire_BT-CO-20130718-711176" />
<meta property="og:title" content="Panasonic, Sanyo to Pay $56.5 Million for Price Fixing - DOJ" />
<meta name="csource" content="WSJ Online" />
<meta name="section" content="Article" />
<meta property="og:image" content="http://s.wsj.net/img/WSJ_profile_lg.gif" />
<meta content="WSJ.com" name="application-name" /><meta content="app-id=364387007" name="apple-itunes-app" /><meta content="368513495882" property="fb:app_id" /><meta content="article" property="og:type" /><meta content="name=MarketWatch;action-uri=http://www.marketwatch.com/;icon-uri=http://www.marketwatch.com/favicon.ico" name="msapplication-task" /><meta content="name=Barron's;action-uri=http://online.barrons.com/;icon-uri=http://online.barrons.com/favicon.ico" name="msapplication-task" /><meta content="name=All Things Digital;action-uri=http://allthingsd.com/;icon-uri=http://allthingsd.com/favicon.ico" name="msapplication-task" /><meta content="name=SmartMoney;action-uri=http://www.smartmoney.com/;icon-uri=http://www.smartmoney.com/favicon.ico" name="msapplication-task" /><meta content="8304333127" property="fb:page_id" /><meta content="telephone=no" name="format-detection" /><meta itemprop="dateModified" value="2013-07-18 15:14:00.0" /><meta itemprop="datePublished" value="2013-07-18 15:14:00.0" /><meta name="pdate" value="20130718031400" /><meta name="udate" value="20130718031400" /><meta name='twitter:image' value='http://s.wsj.net/img/WSJ_profile_lg.gif'/><link rel="stylesheet" href="http://sc.wsj.net/djstyle/2/std/EUROPE_WSJ/0_0


ERATOR_CANCELLED;
	}
	BMO_op_exec(bm, &spinop);
	EDBM_flag_disable_all(em, BM_ELEM_SELECT);
	BMO_slot_buffer_hflag_enable(bm, spinop.slots_out, "geom_last.out", BM_ALL_NOLOOP, BM_ELEM_SELECT, true);
	if (!EDBM_op_finish(em, &spinop, op, true)) {
		return OPERATOR_CANCELLED;
	}

	EDBM_update_generic(em, true, true);

	return OPERATOR_FINISHED;
}

/* get center and axis, in global coords */
static int edbm_screw_invoke(bContext *C, wmOperator *op, const wmEvent *UNUSED(event))
{
	Scene *scene = CTX_data_scene(C);
	View3D *v3d = CTX_wm_view3d(C);
	RegionView3D *rv3d = ED_view3d_context_rv3d(C);

	RNA_float_set_array(op->ptr, "center", ED_view3d_cursor3d_get(scene, v3d));
	RNA_float_set_array(op->ptr, "axis", rv3d->viewinv[1]);

	return edbm_screw_exec(C, op);
}

void MESH_OT_screw(wmOperatorType *ot)
{
	/* identifiers */
	ot->name = "Screw";
	ot->description = "Extrude selected vertices in screw-shaped rotation around the cursor in indicated viewport";
	ot->idname = "MESH_OT_screw";

	/* api callbacks */
	ot->invoke = edbm_screw_invoke;
	ot->exec = edbm_screw_exec;
	ot->poll = ED_operator_editmesh;

	/* flags */
	ot->flag = OPTYPE_REGISTER | OPTYPE_UNDO;

	/* props */
	RNA_def_int(ot->srna, "steps", 9, 1, 100000, "Steps", "Steps", 3, 256);
	RNA_def_int(ot->srna, "turns", 1, 1, 100000, "Turns", "Turns", 1, 256);

	RNA_def_float_vector(ot->srna, "center", 3, NULL, -1e12f, 1e12f,
	                     "Center", "Center in global view space", -1e4f, 1e4f);
	RNA_def_float_vector(ot->srna, "axis", 3, NULL, -1.0f, 1.0f,
	                     "Axis", "Axis in global view space", -1.0f, 1.0f);
}


}
	drag.PointEvent.Position = fyne.NewPos(25, 2)
	slider.Dragged(drag)
	assert.Equal(t, 0, changes)

	drag.PointEvent.Position = fyne.NewPos(25, 2)
	slider.Dragged(drag)
	assert.Equal(t, 0, changes)

	drag.PointEvent.Position = fyne.NewPos(50, 2)
	slider.Dragged(drag)
	slider.DragEnd()
	assert.Equal(t, 1, changes)

	tap := &fyne.PointEvent{}
	tap.Position = fyne.NewPos(25, 2)
	slider.Tapped(tap)
	assert.Equal(t, 2, changes)

	tap.Position = fyne.NewPos(25, 2)
	slider.Tapped(tap)
	assert.Equal(t, 2, changes)

	tap.Position = fyne.NewPos(50, 2)
	slider.Tapped(tap)
	assert.Equal(t, 3, changes)

	slider.TypedKey(&fyne.KeyEvent{Name: fyne.KeyLeft})
	assert.Equal(t, 4, changes)
}

func TestSlider_OnChanged_Float(t *testing.T) {
	slider := NewSlider(0, 1)
	slider.Step = 0.5
	slider.Resize(slider.MinSize())
	assert.Empty(t, slider.OnChanged)

	changes := 0

	slider.OnChanged = func(_ float64) {
		changes++
	}

	assert.Equal(t, 0, changes)

	slider.SetValue(0.15)
	assert.Equal(t, 0, changes)

	drag := &fyne.DragEvent{}
	drag.PointEvent.Position = fyne.NewPos(25, 2)
	slider.Dragged(drag)
	assert.Equal(t, 1, changes)

	drag.PointEvent.Position = fyne.NewPos(25, 2)
	slider.Dragged(drag)
	assert.Equal(t, 1, changes)

	drag.PointEvent.Position = fyne.NewPos(50, 2)
	slider.Dragged(drag)
	assert.Equal(t, 2, changes)

	tap := &fyne.PointEvent{}
	tap.Position = fyne.NewPos(25, 2)
	slider.Tapped(tap)
	assert.Equal(t, 3, changes)

	tap.Position = fyne.NewPos(25, 2)
	slider.Tapped(tap)
	assert.Equal(t, 3, changes)

	tap.Position = fyne.NewPos(50, 2)
	slider.Tapped(tap)
	assert.Equal(t, 4, changes)

	slider.SetValue(0.9)
	assert.Equal(t, 4, changes)
}

func TestSlider_SetValue(t *testing.T) {
	slider := NewSlider(0, 2)
	assert.Equal(t, 0.0, slider.Value)

	slider.SetValue(1.0)
	assert.Equal(t, 1.0, slider.Value)

	slider.SetValue(2.0)
	assert.Equal(t, 2.0, slider.Value)
}

func TestSlider_FocusDesktop(t *testing.T) {
	if fyne.CurrentDevice().IsMobile() {
		return
	}
	slider := NewSlider(0, 10)
	win := test.NewTempWindow(t, slider)
	test.Tap(slider)

	assert.Equal(t, win.Canvas().Focused(), slider)
	assert.True(t, slider.focused)
}

func TestSlider_Focus(t *testing.T) {
	slider := NewSlider(0, 5)
	slider.FocusGained()
	assert.True(t, slider.focused)

	slider.FocusLost()
	assert.False(t, slider.focused)

	slider.MouseIn(nil)
	assert.True(t, slider.hovered)

	slider.MouseOut()
	assert.False(t, slider.hovered)

	left := &fyne.KeyEvent{Name: fyne.KeyLeft}
	right := &fy


8h128a8 8 0 018 8Z" opacity=".2"/><path fill="currentColor" d="M224 100a8 8 0 01-16 0V59.3l-58.4 58.4a8 8 0 01-5.6 2.3 8.3 8.3 0 01-5.7-2.3 8 8 0 010-11.3L196.7 48H156a8 8 0 010-16h60a8 8 0 018 8Zm-40 36a8 8 0 00-8 8v64H48V80h64a8 8 0 000-16H48a16 16 0 00-16 16v128a16 16 0 0016 16h128a16 16 0 0016-16v-64a8 8 0 00-8-8Z"/></svg>';
  static const String arrow_square_out_fill =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="256" height="256" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="currentColor" d="M224 100a8 8 0 01-4.9 7.4 8.5 8.5 0 01-3.1.6 8.3 8.3 0 01-5.7-2.3L186 81.3l-36.4 36.4a8 8 0 01-5.6 2.3 8.3 8.3 0 01-5.7-2.3 8 8 0 010-11.3L174.7 70l-24.4-24.3a8.4 8.4 0 01-1.7-8.8A8 8 0 01156 32h60a8 8 0 018 8Zm-40 36a8 8 0 00-8 8v64H48V80h64a8 8 0 000-16H48a16 16 0 00-16 16v128a16 16 0 0016 16h128a16 16 0 0016-16v-64a8 8 0 00-8-8Z"/></svg>';
  static const String arrow_square_out_light =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="256" height="256" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="currentColor" d="M222 100a6 6 0 01-12 0V54.5l-61.8 61.8a6.2 6.2 0 01-8.5 0 6.1 6.1 0 010-8.5L201.5 46H156a6 6 0 010-12h60a6 6 0 016 6Zm-38 38a6 6 0 00-6 6v64a2 2 0 01-2 2H48a2 2 0 01-2-2V80a2 2 0 012-2h64a6 6 0 000-12H48a14 14 0 00-14 14v128a14 14 0 0014 14h128a14 14 0 0014-14v-64a6 6 0 00-6-6Z"/></svg>';
  static const String arrow_square_out_thin =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="256" height="256" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path fill="currentColor" d="M220 100a4 4 0 01-8 0V49.7l-65.2 65.2a4.3 4.3 0 01-2.8 1.1 4.4 4.4 0 01-2.9-1.1 4.2 4.2 0 010-5.7L206.3 44H156a4 4 0 010-8h60a4 4 0 014 4Zm-36 40a4 4 0 00-4 4v64a4 4 0 01-4 4H48a4 4 0 01-4-4V80a4 4 0 014-4h64a4 4 0 000-8H48a12 12 0 00-12 12v128a12 12 0 0012 12h128a12 12 0 0012-12v-64a4 4 0 00-4-4Z"/></svg>';
  static const String arrow_square_right =
      '<sv


		return nil
	}

	return &frameLoop{

		capture:   graphicsCapture,
		loopCount: loopCount,

		loopStartIdx: api.CmdID.Real(loopStart),
		loopEndIdx:   api.CmdID.Real(loopEnd),

		capturedLoopCmds:   make([]api.Cmd, 0),
		capturedLoopCmdIds: make([]api.CmdID, 0),

		watcher: &stateWatcher{
			memoryWrites: make(map[memory.PoolID]*interval.U64SpanList),
		},

		instanceToDestroy: make(map[VkInstance]bool),
		instanceToCreate:  make(map[VkInstance]bool),

		deviceToDestroy: make(map[VkDevice]bool),
		deviceToCreate:  make(map[VkDevice]bool),

		memoryToFree:           make(map[VkDeviceMemory]bool),
		memoryToAllocate:       make(map[VkDeviceMemory]bool),
		memoryToUnmap:          make(map[VkDeviceMemory]bool),
		memoryToMap:            make(map[VkDeviceMemory]bool),
		memoryForStagingBuffer: make(map[VkDevice]*backupMemory),

		bufferToDestroy: make(map[VkBuffer]bool),
		bufferChanged:   make(map[VkBuffer]bool),
		bufferToCreate:  make(map[VkBuffer]bool),
		bufferToRestore: make(map[VkBuffer]VkBuffer),

		bufferViewToDestroy: make(map[VkBufferView]bool),
		bufferViewToCreate:  make(map[VkBufferView]bool),

		surfaceToDestroy: make(map[VkSurfaceKHR]bool),
		surfaceToCreate:  make(map[VkSurfaceKHR]bool),

		swapchainToDestroy: make(map[VkSwapchainKHR]bool),
		swapchainToCreate:  make(map[VkSwapchainKHR]bool),

		imageToDestroy: make(map[VkImage]bool),
		imageChanged:   make(map[VkImage]bool),
		imageToCreate:  make(map[VkImage]bool),
		imageToRestore: make(map[VkImage]VkImage),

		imageViewToDestroy: make(map[VkImageView]bool),
		imageViewToCreate:  make(map[VkImageView]bool),

		samplerYcbcrConversionToDestroy: make(map[VkSamplerYcbcrConversion]bool),
		samplerYcbcrConversionToCreate:  make(map[VkSamplerYcbcrConversion]bool),

		samplerToDestroy: make(map[VkSampler]bool),
		samplerToCreate:  make(map[VkSampler]bool),

		shaderModuleToDestroy: make(map[VkShaderModule]bool),
		shaderModuleToCreate:  make(map[VkShaderModule]bool),

		descriptorSetLayoutToDestroy: make(map[VkDescriptorSetLayout]bool),
		descriptorSetLayoutToCreate:  make(map[VkDescriptorSetLayout]bool),

		pipelineLayoutToDestroy: make(map[VkPipelineLayout]bool),
		pipelineLayoutToCreate:  make(map[VkPipelineLayout]bool),

		pipelineCacheToDestroy: make(map[VkPipelineCache]bool),
		pipelineCacheToCreate:  make(map[VkPipelineCache]bool),

		pipelineToDestroy:        make(map[VkPipeline]bool),
		computePipelineToCreate:  make(map[VkPipeline]bool),
		graphicsPipelineToCreate: make(map[VkPipeline]bool),

		descriptorPoolToDestroy: make(map[VkDescriptorPool]bool),
		descriptorPoolToCreate:  make(map[VkDescriptorPool]bool),

		descriptorSetToFree:     make(map[VkDescriptorSet]bool),
		descriptorSetToAllocate: make(map[VkDescriptorSet]bool),
		descriptorSetChanged:    make(map[VkDescriptorSet]bool),
		descriptorSetAutoFreed:  make(map[VkDescriptorSet]bool),

		semaphoreToDestroy: make(map[VkSemaphore]bool),
		semaphoreChanged


slicePitch);
                            }
                            finally
                            {
                                Utilities.FreeMemory(temp);
                            }
                        }
                    }
                }
            }
            else
            {
                // No conversion required
                frame.WritePixels(image.Height, image.DataPointer, image.RowStride, image.BufferStride);
            }

            frame.Commit();
        }

        private static void EncodeSingleFrame(PixelBuffer pixelBuffer, WICFlags flags, Guid guidContainerFormat, Stream stream)
        {
            using (var encoder = new BitmapEncoder(Factory, guidContainerFormat, stream))
            {
                using (var frame = new BitmapFrameEncode(encoder))
                {
                    if (guidContainerFormat == ContainerFormatGuids.Bmp)
                    {
                        try
                        {
                            frame.Options.Set("EnableV5Header32bppBGRA", true);
                        }
                        catch
                        {
                        }
                    }
                    EncodeImage(pixelBuffer, flags, frame);
                    encoder.Commit();
                }
            }
        }

        //-------------------------------------------------------------------------------------
        // Encodes an image array
        //-------------------------------------------------------------------------------------
        private static void EncodeMultiframe(PixelBuffer[] images, int count, WICFlags flags, Guid guidContainerFormat, Stream stream)
        {
            if (images.Length < 2)
                throw new ArgumentException("Cannot encode to multiple frame. Image doesn't have multiple frame");

            using (var encoder = new BitmapEncoder(Factory, guidContainerFormat))
            {
                using (var eInfo = encoder.EncoderInfo)
                {
                    if (!eInfo.IsMultiframeSupported)
                        throw new NotSupportedException("Cannot encode to multiple frame. Format is not supporting multiple frame");
                }

                encoder.Initialize(stream);

                for (int i = 0; i < Math.Min(images.Length, count); i++)
                {
                    var pixelBuffer = images[i];
                    using (var frame = new BitmapFrameEncode(encoder))
                        EncodeImage(pixelBuffer, flags, frame);
                }

                encoder.Commit();
            }
        }

        private static Guid GetContainerFormatFromFileType(ImageFileType fileType)
        {
            switch (fileType)


	 * 上次同步月流量，单位KB。
	 */
	@ApiField("before_month_usage")
	private String beforeMonthUsage;

	/**
	 * 卡池套餐周期，例如年包，月包
	 */
	@ApiField("biling_cycle")
	private String bilingCycle;

	/**
	 * 卡池套餐名称，包含档位信息
	 */
	@ApiField("credential_name")
	private String credentialName;

	/**
	 * 当前日流量，单位KB。
	 */
	@ApiField("current_day_usage")
	private String currentDayUsage;

	/**
	 * 当前月流量，单位KB。
	 */
	@ApiField("current_month_usage")
	private String currentMonthUsage;

	/**
	 * 卡池套餐档位信息，例如：单卡通用流量、单卡运营商定向流量
	 */
	@ApiField("data_type")
	private String dataType;

	/**
	 * 流量卡id
	 */
	@ApiField("icc_id")
	private String iccId;

	public String getBeforeDayUsage() {
		return this.beforeDayUsage;
	}
	public void setBeforeDayUsage(String beforeDayUsage) {
		this.beforeDayUsage = beforeDayUsage;
	}

	public String getBeforeMonthUsage() {
		return this.beforeMonthUsage;
	}
	public void setBeforeMonthUsage(String beforeMonthUsage) {
		this.beforeMonthUsage = beforeMonthUsage;
	}

	public String getBilingCycle() {
		return this.bilingCycle;
	}
	public void setBilingCycle(String bilingCycle) {
		this.bilingCycle = bilingCycle;
	}

	public String getCredentialName() {
		return this.credentialName;
	}
	public void setCredentialName(String credentialName) {
		this.credentialName = credentialName;
	}

	public String getCurrentDayUsage() {
		return this.currentDayUsage;
	}
	public void setCurrentDayUsage(String currentDayUsage) {
		this.currentDayUsage = currentDayUsage;
	}

	public String getCurrentMonthUsage() {
		return this.currentMonthUsage;
	}
	public void setCurrentMonthUsage(String currentMonthUsage) {
		this.currentMonthUsage = currentMonthUsage;
	}

	public String getDataType() {
		return this.dataType;
	}
	public void setDataType(String dataType) {
		this.dataType = dataType;
	}

	public String getIccId() {
		return this.iccId;
	}
	public void setIccId(String iccId) {
		this.iccId = iccId;
	}

}
package com.alipay.api.domain;

import java.util.Date;
import java.util.List;

import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.internal.mapping.ApiListField;

/**
 * 理赔反欺诈查询服务
 *
 * @author auto create
 * @since 1.0, 2018-05-25 11:02:22
 */
public class AlipayInsDataAutoFraudQueryModel extends AlipayObject {

	private static final long serialVersionUID = 3688134852954148869L;

	/**
	 * 出险城市，六位国标码
	 */
	@ApiField("accident_city")
	private String accidentCity;

	/**
	 * 出险时间，标准时间格式：yyyy-MM-dd HH:mm:ss
	 */
	@ApiField("accident_date")
	private Date accidentDate;

	/**
	 * 出险地点
	 */
	@ApiField("accident_location")
	private String accidentLocation;

	/**
	 * 立案金额，单位：元


 /* WITH_ASSERT */

	/* Check no tile is related to us. */
	for (TileIndex tile = 0; tile < MapSize(); ++tile) {
		switch (GetTileType(tile)) {
			case MP_HOUSE:
				assert(GetTownIndex(tile) != this->index);
				break;

			case MP_ROAD:
				assert(!HasTownOwnedRoad(tile) || GetTownIndex(tile) != this->index);
				break;

			case MP_TUNNELBRIDGE:
				assert(!TestTownOwnsBridge(tile, this));
				break;

			default:
				break;
		}
	}

	/* Clear the persistent storage list. */
	this->psa_list.clear();

	DeleteSubsidyWith(ST_TOWN, this->index);
	DeleteNewGRFInspectWindow(GSF_FAKE_TOWNS, this->index);
	CargoPacket::InvalidateAllFrom(ST_TOWN, this->index);
	MarkWholeScreenDirty();
}

/**
 * Invalidating of the "nearest town cache" has to be done
 * after removing item from the pool.
 * @param index index of deleted item
 */
void Town::PostDestructor(size_t index)
{
	InvalidateWindowData(WC_TOWN_DIRECTORY, 0, TDIWD_FORCE_REBUILD);
	UpdateNearestTownForRoadTiles(false);

	/* Give objects a new home! */
	for (Object *o : Object::Iterate()) {
		if (o->town == nullptr) o->town = CalcClosestTownFromTile(o->location.tile, UINT_MAX);
	}
}

/**
 * Assigns town layout. If Random, generates one based on TileHash.
 */
void Town::InitializeLayout(TownLayout layout)
{
	if (layout != TL_RANDOM) {
		this->layout = layout;
		return;
	}

	this->layout = static_cast<TownLayout>(TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1));
}

/**
 * Return a random valid town.
 * @return random town, nullptr if there are no towns
 */
/* static */ Town *Town::GetRandom()
{
	if (Town::GetNumItems() == 0) return nullptr;
	int num = RandomRange((uint16)Town::GetNumItems());
	size_t index = MAX_UVALUE(size_t);

	while (num >= 0) {
		num--;
		index++;

		/* Make sure we have a valid town */
		while (!Town::IsValidID(index)) {
			index++;
			assert(index < Town::GetPoolSize());
		}
	}

	return Town::Get(index);
}

void Town::FillCachedName() const
{
	char buf[MAX_LENGTH_TOWN_NAME_CHARS * MAX_CHAR_LENGTH];
	char *end = GetTownName(buf, this, lastof(buf));
	this->cached_name.assign(buf, end);
}

/**
 * Get the cost for removing this house
 * @return the cost (inflation corrected etc)
 */
Money HouseSpec::GetRemovalCost() const
{
	return (_price[PR_CLEAR_HOUSE] * this->removal_cost) >> 8;
}

/* Local */
static int _grow_town_result;

/* Describe the possible states */
enum TownGrowthResult {
	GROWTH_SUCCEED         = -1,
	GROWTH_SEARCH_STOPPED  =  0
//	GROWTH_SEARCH_RUNNING >=  1
};

static bool BuildTownHouse(Town *t, TileIndex tile);
static Town *CreateRandomTown(uint attempts, uint32 townnameparts, TownSize size, bool city, TownLayout layout);

static void TownDrawHouseLift(const TileInfo *ti)
{
	AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
}

typedef void TownDrawTileProc(const TileInfo *ti);
static T


terName.ClassifyAt(104, 3));
        }

        [Test]
        public void XmlNodeTest_ParamRef()
        {
            GetContext(@"XmlDocComment\ParamRef.cs").GetClassifications().AssertContains(
                CSharpNames.ParameterName.ClassifyAt(133, 3));
        }

        [Test]
        public void XmlNodeTest_ParamRefDisableInXml()
        {
            GetContext(@"XmlDocComment\ParamRef.cs")
                .AddInfo(
                    CSharpNames.ParameterName.DisableInXml())
                .GetClassifications().AssertNotContains(
                    CSharpNames.ParameterName.ClassifyAt(133, 3));
        }

        [Test]
        public void XmlNodeTest_Permission()
        {
            GetContext(@"XmlDocComment\Permission.cs").GetClassifications().AssertContains(
                CSharpNames.NamespaceName.ClassifyAt(72, 6),
                CSharpNames.NamespaceName.ClassifyAt(79, 8));
        }

        [Test]
        public void XmlNodeTest_PermissionDisableInXml()
        {
            GetContext(@"XmlDocComment\Permission.cs")
                .AddInfo(
                    CSharpNames.NamespaceName.DisableInXml())
                .GetClassifications().AssertNotContains(
                    CSharpNames.NamespaceName.ClassifyAt(72, 6),
                    CSharpNames.NamespaceName.ClassifyAt(79, 8));
        }

        [Test]
        public void XmlNodeTest_See()
        {
            GetContext(@"XmlDocComment\See.cs").GetClassifications().AssertContains(
                CSharpNames.NamespaceName.ClassifyAt(84, 6));
        }

        [Test]
        public void XmlNodeTest_SeeDisableInXml()
        {
            GetContext(@"XmlDocComment\See.cs")
                .AddInfo(
                    CSharpNames.NamespaceName.DisableInXml())
                .GetClassifications().AssertNotContains(
                    CSharpNames.NamespaceName.ClassifyAt(84, 6));
        }

        [Test]
        public void XmlNodeTest_SeeAlso()
        {
            GetContext(@"XmlDocComment\SeeAlso.cs").GetClassifications().AssertContains(
                CSharpNames.NamespaceName.ClassifyAt(88, 6));
        }

        [Test]
        public void XmlNodeTest_SeeAlsoDisableInXml()
        {
            GetContext(@"XmlDocComment\SeeAlso.cs")
                .AddInfo(
                    CSharpNames.NamespaceName.DisableInXml())
                .GetClassifications().AssertNotContains(
                    CSharpNames.NamespaceName.ClassifyAt(88, 6));
        }

        // TODO: typeparam currently unsupported
    }
}


.url;

  @override
  List<String> get pathParameters => [];

  @override
  Map<String, dynamic> get queryParameters =>
      {'ignore_signature_check': ignoreSignatureCheck.toString()};

  @override
  Map<String, String?> get headers => {'Accept-Language': acceptLanguage};
  @override
  EventResponse onResonse(Map<String, dynamic> result) {
    return EventResponse.fromJson(result);
  }
}
import 'package:ton_dart/src/provider/core/core.dart';
import 'package:ton_dart/src/provider/core/methods.dart';
import 'package:ton_dart/src/provider/models/response/transactions.dart';

/// GetBlockchainMasterchainTransactions invokes getBlockchainMasterchainTransactions operation.
///
/// Get all transactions in all shards and workchains between target and previous masterchain block
/// according to shards last blocks snapshot in masterchain. We don't recommend to build your app
/// around this method because it has problem with scalability and will work very slow in the future.
///
class TonApiGetBlockchainMasterchainTransactions
    extends TonApiRequest<TransactionsResponse, Map<String, dynamic>> {
  final int masterchainSeqno;
  TonApiGetBlockchainMasterchainTransactions(this.masterchainSeqno);
  @override
  String get method => TonApiMethods.getblockchainmasterchaintransactions.url;

  @override
  List<String> get pathParameters => [masterchainSeqno.toString()];

  @override
  TransactionsResponse onResonse(Map<String, dynamic> result) {
    return TransactionsResponse.fromJson(result);
  }
}
import 'package:ton_dart/src/provider/core/core.dart';
import 'package:ton_dart/src/provider/core/methods.dart';
import 'package:ton_dart/src/provider/models/response/blockchain_blocks.dart';

/// GetBlockchainMasterchainBlocks invokes getBlockchainMasterchainBlocks operation.
///
/// Get all blocks in all shards and workchains between target and previous masterchain block
/// according to shards last blocks snapshot in masterchain.  We don't recommend to build your app
/// around this method because it has problem with scalability and will work very slow in the future.
///
class TonApiGetBlockchainMasterchainBlocks
    extends TonApiRequest<BlockchainBlocksResponse, Map<String, dynamic>> {
  final int masterchainSeqno;
  TonApiGetBlockchainMasterchainBlocks(this.masterchainSeqno);
  @override
  String get method => TonApiMethods.getblockchainmasterchainblocks.url;

  @override
  List<String> get pathParameters => [masterchainSeqno.toString()];

  @override
  BlockchainBlocksResponse onResonse(Map<String, dynamic> result) {
    return BlockchainBlocksResponse.fromJson(result);
  }
}
import 'package:ton_dart/src/contracts/exception/exception.dart';

class _HighloadQueryIdConst {
  static const int bitNumberSize = 10; // 10 bit
  static const int maxBitNumber = 1022;
  static const int maxShift = 8191; // 2^13 = 8192
}

class HighloadQueryId {
  BigInt _shift = BigInt.zero;
  BigInt _bitNumber = BigInt.zero;
  BigInt get shift => _shift;
  BigInt get bitNumber => _bitNumber;

  HighloadQueryId();

  HighloadQueryId._(this._shift, this._bitNumber);

  factory HighloadQueryId.fromShiftAndBitNumber(
      BigInt shift, BigInt bitNumber) {
    if (shift < BigInt.zero ||
        shift > BigInt.from(_HighloadQueryIdConst.maxShift)) {
      throw TonContractException('Invalid shift', details: {'shift': shift});
    }
    if (bitNumber < BigInt.zero ||
        bitNumber > BigInt.fr


(0, 0, 0, 0);\n  border: 0;\n}\n.sr-only-focusable:active,\n.sr-only-focusable:focus {\n  position: static;\n  width: auto;\n  height: auto;\n  margin: 0;\n  overflow: visible;\n  clip: auto;\n}\n', "" ]);
}, function(module, exports) {
    module.exports = function(url) {
        return "string" != typeof url ? url : (/^['"].*['"]$/.test(url) && (url = url.slice(1, -1)),
        /["'() \t\n]/.test(url) ? '"' + url.replace(/"/g, '\\"').replace(/\n/g, "\\n") + '"' : url);
    };
}, function(module, exports) {
    function cssWithMappingToString(item, useSourceMap) {
        var content = item[1] || "", cssMapping = item[3];
        if (!cssMapping) return content;
        if (useSourceMap && "function" == typeof btoa) {
            var sourceMapping = toComment(cssMapping);
            return [ content ].concat(cssMapping.sources.map(function(source) {
                return "/*# sourceURL=" + cssMapping.sourceRoot + source + " */";
            })).concat([ sourceMapping ]).join("\n");
        }
        return [ content ].join("\n");
    }
    function toComment(sourceMap) {
        return "/*# sourceMappingURL=data:application/json;charset=utf-8;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
    }
    module.exports = function(useSourceMap) {
        var list = [];
        return list.toString = function() {
            return this.map(function(item) {
                var content = cssWithMappingToString(item, useSourceMap);
                return item[2] ? "@media " + item[2] + "{" + content + "}" : content;
            }).join("");
        }, list.i = function(modules, mediaQuery) {
            "string" == typeof modules && (modules = [ [ null, modules, "" ] ]);
            for (var alreadyImportedModules = {}, i = 0; i < this.length; i++) {
                var id = this[i][0];
                "number" == typeof id && (alreadyImportedModules[id] = !0);
            }
            for (i = 0; i < modules.length; i++) {
                var item = modules[i];
                "number" ==


ense(),)+);

                unsafe {
                    Some((
                        $(self.$idx.get_unchecked(indexes.$idx)?,)+
                    ))
                }
            }

            fn contains(&self, entity: Entity) -> bool {
                $(self.$idx.contains(entity))&&+
            }

            #[allow(clippy::needless_question_mark)]
            fn group_info(&self) -> Option<CombinedGroupInfo<'a>> {
                Some(CombinedGroupInfo::default() $(.combine(self.$idx.group_info()?)?)+)
            }

            fn split_sparse(self) -> (IterData<'a>, Self::Sparse, Self::Data) {
                split_sparse!($((self.$idx, $idx)),+)
            }

            fn split_dense(self) -> (IterData<'a>, Self::Data) {
                split_dense!($((self.$idx, $idx)),+)
            }

            unsafe fn get_from_sparse_parts(
                sparse: &Self::Sparse,
                entity: Entity,
                data: &Self::Data,
                world_tick: Ticks,
                change_tick: Ticks,
            ) -> Option<Self::Item> {
                let indexes = ($(sparse.$idx.get_entity(entity)?.dense(),)+);

                Some((
                    $(
                        $elem::get_from_parts_unchecked(
                            data.$idx.components,
                            data.$idx.ticks,
                            indexes.$idx,
                            &data.$idx.filter,
                            world_tick,
                            change_tick,
                        )?,
                    )+
                ))
            }

            unsafe fn get_from_dense_parts_unchecked(
                data: &Self::Data,
                index: usize,
                world_tick: Ticks,
                change_tick: Ticks,
            ) -> Option<Self::Item> {
                Some((
                    $(
                        $elem::get_from_parts_unchecked(
                            data.$idx.components,
                            data.$idx.ticks,
                            index,
                            &data.$idx.filter,
                            world_tick,
                            change_tick,
                        )?,
                    )+
                ))
            }
        }
    };
}

#[rustfmt::skip]
mod impls {
	use super::*;

	impl_query_base!(1; (A, 0));
    impl_query_base!(2; (A, 0), (B, 1));
    impl_query_base!(3; (A, 0), (B, 1), (C, 2));
    impl_query_base!(4; (A, 0), (B, 1), (C, 2), (D, 3));
    impl_query_base!(5; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4));
    impl_query_base!(6; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5));
    impl_query_base!(7; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6));
    impl_query_base!(8; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7));
    impl_query_base!(9; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8));
    impl_query_base!(10; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4), (F, 5), (G, 6), (H, 7), (I, 8), (J, 9));
    impl_query_base!(11; (A, 0), (B, 1), (C, 2), (D, 3), (E, 4),


-- This software is copyright Kong Inc. and its licensors.
-- Use of the software is subject to the agreement between your organization
-- and Kong Inc. If there is no such agreement, use is governed by and
-- subject to the terms of the Kong Master Software License Agreement found
-- at https://konghq.com/enterprisesoftwarelicense/.
-- [ END OF LICENSE 0867164ffc95e54f04670b5169c09574bdbd9bba ]

--
-- imports
--

local cjson = require("cjson")
local gzip = require("kong.tools.gzip")

--
-- public vars
--

-- some previously generated text embeddings for mocking, using OpenAI's
-- text-embedding-3-small model and 4 dimensions.
local known_text_embeddings = {
  ["dog"] = { 0.56267416, -0.20551957, -0.047182854, 0.79933304 },
  ["cat"] = { 0.4653789, -0.42677408, -0.29335415, 0.717795 },
  ["capacitor"] = { 0.350534, -0.025470039, -0.9204002, -0.17129119 },
  ["smell"] = { 0.23342973, -0.08322083, -0.8492907, -0.46614397 },
  ["Non-Perturbative Quantum Field Theory and Resurgence in Supersymmetric Gauge Theories"] = {
    -0.6826024,
    -0.08655233,
    -0.72073454,
    -0.084287055,
  },
  ["taco"] = { -0.4407651, -0.85174876, -0.27901474, -0.048999753 },
  ["If it discuss any topic about Amazon"] = { -0.86724466, 0.36718428, -0.21300745, -0.26017338 },
  ["If it discuss any topic about Microsoft"] = { -0.8649115, 0.2526763, -0.41767937, -0.11673351 },
  ["If it discuss any topic about Google"] = { -0.8108202, -0.22810346, -0.3790472, -0.38322666 },
  ["If it discuss any topic about Apple"] = { -0.8892975, 0.30626073, -0.336221, 0.048061296 },
  ["tell me something about Microsoft"] = { -0.48062202, -0.4189232, -0.7663229, -0.07908846 },
  ["tell me something about Amazon"] = { -0.9346679, 0.10783355, -0.13593763, -0.31030443 },
  ["tell me something about Google"] = { -0.3132111, -0.87082464, -0.33971936, -0.16779166 },
}

-- some artificial numbers
known_text_embeddings["dog alike"] = known_text_embeddings["dog"]
known_text_embeddings["cat alike"] = known_text_embeddings["cat"]
known_text_embeddings["capacitor alike"] = known_text_embeddings["capacitor"]
known_text_embeddings["taco alike"] = known_text_embeddings["taco"]

--
-- public functions
--

local function mock_embeddings(opts, path)
  if opts.method ~= "POST" then
    return nil, "Only POST method is supported"
  end

  if opts.headers["Content-Type"] ~= "application/json" then
    return nil, "Only application/json content type is supported"
  end

  if opts.headers["Accept-Encoding"] ~= "gzip" then
    return nil, "Only gzip encoding is supported"
  end

  l


local strModuleName = "ZyTabBar";
CCLuaLog("Module ".. strModuleName.. " loaded.");
strModuleName = nil;

local n
 ZyTabBar = {
	_menuItems = nil,
	_labels = nil,
	_menu = nil,
	_callbackFun = nil,
	_picNor = nil,
	_picDown = nil,
	_titles = nil,
	_fontName = nil,
	_fontSize = nil,
	_picLArrow = nil;
	_picRArrow = nil;
	_nNumOfVisibleTab = nil,
	_bDisplayArrows = false,
	_nCurrentFirstTab = 1,
	_nCurrentTab = 1,
	_color = nil,
	_list=nil,
	_nextBtn=nil
 }
function gZytableHandler(pNode)
	local bar = gClassPool[pNode];
	local bSel = true;

	if bar and bar._callbackFun then
		local sel = bar._callbackFun(bar, pNode)
		if sel == false then
			bSel = false
		end
	end

	if bSel then
		bar._nCurrentTab = pNode:getTag();
		for key, value in pairs(bar._menuItems) do
			value:unselected()
		end
		bar._menuItems[bar._nCurrentTab]:selected();
	end
end
-- 刷新Tabbar按钮
function ZyTabBarRefresh(this)
	local nMin = this._nCurrentFirstTab;
	local nMax = this._nCurrentFirstTab + this._nNumOfVisibleTab - 1;
	local titles = {}
	for k, v in pairs(this._titles) do
	    titles[#titles+1]=v
	end

	local width = 0;
	local height = 0;
	local menuItems = {};
	local LButton;
	local RButton;
	local menu = this._menu;
	local sprite=CCSprite:create(P(this._picNor))
	local spriteDown=CCSprite:create(P(this._picDown))

	local listWidth = sprite:getContentSize().width
	--* this._nNumOfVisibleTab
	local showHeight=spriteDown:getContentSize().height
	local width=0
	if this._nNumOfVisibleTab< #titles then
		width=sprite:getContentSize().width/6
	end

	local listSize=SZ(listWidth*this._nNumOfVisibleTab+width,showHeight)
	local list = ScutCxList:node(listWidth,ccc4(124, 124, 124, 255),listSize)
	this._list=list
	list:setTouchEnabled(true)
	--list:registerLoadEvent(gZytableTurnPage)
	list:setAnchorPoint(PT(0,0))
	list:setHorizontal(true)
--	list:setPageTurnEffect(true)--是否翻页
--	list:setRecodeNumPerPage(1)--设置页码
--	list:setSelectedItemColor(ccc3(0, 0, 0), ccc3(0, 0, 0))
       local itemTable={}
	local index=0
	local titleIndex=0
	local layout=CxLayout()
	layout.val_x.t = ABS_WITH_PIXEL
	layout.val_y.t = ABS_WITH_PIXEL
	layout.val_x.val.pixel_val =0
	layout.val_y.val.pixel_val =0
	 for k, v in pairs(this._titles) do
            titleIndex=titleIndex+1
	       		index=index+1
	       		local listItem=ScutCxListItem:itemWithColor(ccc3(32, 24, 3))
	       		listItem:setOpacity(0)
	              --	local Btn=ZyButton:new(this._picNor, this._picDown,nil,v,FONT_NAME,FONT_SM_SIZE)
                    local Btn=ZyButton:new(this._picNor, this._picDown,nil,nil,FONT_NAME,FONT_SM_SIZE)
	              	Btn:setColor(ccC1)
	              	Btn:addto(listItem,layout)
	              	Btn:setTag(k)


, usize)) {
        for (i, image_folder) in self.all_images.iter().enumerate() {
            cb(&(image_folder.clone(), i), i)
        }
    }

    fn for_each_mut(
        &mut self,
        mut cb: impl FnMut(&mut (ImageFolder, usize), usize),
    ) {
        for (i, image_folder) in self.all_images.iter_mut().enumerate() {
            cb(&mut (image_folder.clone(), i), i)
        }
    }

    fn data_len(&self) -> usize {
        self.all_images.len()
    }

    fn child_data(&self) -> Option<(ImageFolder, usize)> {
        match self.all_images.iter().next() {
            Some(folder) => Some((folder.clone(), 0)),
            None => Some((
                ImageFolder {
                    name: Arc::new(PathBuf::from("".to_owned())),
                    folder_thumbnail: Thumbnail {
                        index: 0,
                        image: ImageBuf::empty(),
                    },
                    paths: Vector::new(),
                    selected: None,
                    thumbnails: Vector::new(),
                },
                0,
            )),
        }
    }
}
#[derive(Debug, Clone, Data, PartialEq, Hash, Eq)]
pub enum AppView {
    MainView,
    // this will eventually be used when opening a single file for viewing
    ImageView,
    FolderView,
}

impl View for AppView {}
impl ViewController<AppView> for AppState {
    fn add_view(&mut self, view: AppView) {
        self.views.push_back(view);
    }

    fn pop_view(&mut self) {
        self.views.pop_back();
    }

    fn current_view(&self) -> &AppView {
        self.views.last().unwrap()
    }

    fn len(&self) -> usize {
        self.views.len()
    }

    fn is_empty(&self) -> bool {
        self.views.is_empty()
    }
}

pub struct MainViewController;

impl Controller<AppState, Container<AppState>> for MainViewController {
    fn event(
        &mut self,
        child: &mut Container<AppState>,
        ctx: &mut druid::EventCtx,
        event: &Event,
        data: &mut AppState,
        env: &Env,
    ) {
        match event {
            Event::Command(selector)
                if selector.is(FINISHED_READING_FOLDER_IMAGE) =>
            {
                let image_folder =
                    selector.get_unchecked(FINISHED_READING_FOLDER_IMAGE);
                data.all_images.push_back(image_folder.clone());
                ctx.request_layout();
                ctx.request_paint();
            }
            Event::Command(selector) if selector.is(SELECTED_FOLDER) => {
                let selected = selector.get_unchecked(SELECTED_FOLDER);
                data.selected_folder = Some(*selected);
                data.add_view(AppView::FolderView);
            }
            Event::Command(selector) if selector.is(POP_VIEW) => {
                data.pop_view();
            }
            Event::Command(cmd) if cmd.is(FINISHED_READING_ALL_PATHS) => {
                let current_folders =
                    cmd.get_unchecked(FINISHED_READING_ALL_PATHS);
                data.folder_paths = current_folders.clone();
                let handle = ctx.get_external_handle();
                let folders = data.all_images.clone();
                thread::spawn(move || {
                    for (folder_idx, folder) in folders.iter().enumerate() {


-color($component-active-bg, 70%) !default;
$form-range-thumb-disabled-bg:             var(--#{$prefix}secondary-color) !default;
$form-range-thumb-transition:              background-color .15s ease-in-out, border-color .15s ease-in-out, box-shadow .15s ease-in-out !default;
// scss-docs-end form-range-variables

// scss-docs-start form-file-variables
$form-file-button-color:          $input-color !default;
$form-file-button-bg:             var(--#{$prefix}tertiary-bg) !default;
$form-file-button-hover-bg:       var(--#{$prefix}secondary-bg) !default;
// scss-docs-end form-file-variables

// scss-docs-start form-floating-variables
$form-floating-height:                  add(3.5rem, $input-height-border) !default;
$form-floating-line-height:             1.25 !default;
$form-floating-padding-x:               $input-padding-x !default;
$form-floating-padding-y:               1rem !default;
$form-floating-input-padding-t:         1.625rem !default;
$form-floating-input-padding-b:         .625rem !default;
$form-floating-label-height:            1.5em !default;
$form-floating-label-opacity:           .65 !default;
$form-floating-label-transform:         scale(.85) translateY(-.5rem) translateX(.15rem) !default;
$form-floating-label-disabled-color:    $gray-600 !default;
$form-floating-transition:              opacity .1s ease-in-out, transform .1s ease-in-out !default;
// scss-docs-end form-floating-variables

// Form validation

// scss-docs-start form-feedback-variables
$form-feedback-margin-top:          $form-text-margin-top !default;
$form-feedback-font-size:           $form-text-font-size !default;
$form-feedback-font-style:          $form-text-font-style !default;
$form-feedback-valid-color:         $success !default;
$form-feedback-invalid-color:       $danger !default;

$form-feedback-icon-valid-color:    $form-feedback-valid-color !default;
$form-feedback-icon-valid:          url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><path fill='#{$form-feedback-icon-valid-color}' d='M2.3 6.73.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1'/></svg>") !default;
$form-feedback-icon-invalid-color:  $form-feedback-invalid-color !default;
$form-feedback-icon-invalid:        url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='#{$form-feedback-icon-invalid-color}'><circle cx='6' cy='6' r='4.5'/><path stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/><circle cx='6' cy='8.2' r='.6' fill='#{$form-feedback-icon-invalid-color}' stroke='none'/></svg>") !default;
// scss-docs-end form-feedback-variables

// scss-docs-start form-validation-colors
$form-valid-color:                  $form-feedback-valid-color !default;
$form-valid-border-color:           $form-feedback-valid-color !default;
$form-invalid-color:                $form-feedback


onfigurationProperties(prefix = "app")
@Component
@Validated
public class AppProperties {
    @NotBlank(message = "应用名称不能为空")
    private String name = "Default App Name"; // 提供默认值
}
```

## 8.3 环境变量配置问题

```bash
问题：环境变量无法正确映射
export APP_NAME=MyApp

解决方案：使用正确的环境变量格式
export APP_NAME=MyApp
export APP_VERSION=1.0.0
export APP_FEATURE_ENABLED=true
```

# 9 Spring配置属性管理关联的其它知识

## 9.1 相关技术

- **[Spring IoC容器](0101-Spring%20IoC容器.md)**：配置属性管理的容器基础
- **[Spring注解配置方式](0202-注解配置方式.md)**：配置属性的注解支持
- **[Spring Java配置方式](0203-Java配置方式.md)**：配置属性的Java配置支持
- **[Spring Boot自动配置](0701-Spring%20Boot自动配置.md)**：基于配置属性的自动配置机制
- **[Spring Boot配置管理](0703-Spring%20Boot配置管理.md)**：Spring Boot的配置管理特性

## 9.2 扩展知识

- **外部化配置**：12-Factor App的配置原则
- **配置加密**：敏感配置的保护机制
- **配置中心**：分布式配置管理
- **配置热重载**：动态配置更新机制
- **配置验证**：配置正确性的验证策略 > AbstractQueuedSynchronizer抽象类是核心，需要重点掌握。它提供了一个基于FIFO队列，可以用于构建锁或者其他相关同步装置的基础框架。
+ jdk17的AQS代码详解 https://blog.csdn.net/weixin_49561445/article/details/120598020
+ [ ] 不理解 Condition的逻辑，这篇帖子也是不理解 ： https://blog.csdn.net/jiankunking/article/details/83443351
- 一句话概括AQS：
	- JUC包中多个组件的底层实现，Lock、CountDownLatch、Semaphore都用了AQS
	- AQS提供了两种锁的机制，排它锁和共享锁
		- 排它锁：多个线程竞争一个共享资源。比如Lock中的ReentrantLock重入锁，就是用到了AQS的一个排它锁的功能
		- 共享锁：也称为读锁，就是同一个时刻运行多个线程获得这样一个锁的资源，比如CountDownlatch、Semaphore都用到了AQS中的共享锁的功能
	- AQS作为互斥锁，需要解决三个核心设计
		- 第一个，互斥变量的设计，以及如何保证多线程同时更新互斥变量的时候线程的安全性
		- 第二个，未竞争到锁的资源的线程的等待，竞争到锁的资源释放锁之后的唤醒
		- 第三个，锁竞争的公平性和非公平性
		- AQS采用了一个int类型的互斥变量`state`，用来记录锁的竞争的状态。0标识没有任何线程竞争锁资源，而大于等于1，表示已经有线程正在持有锁资源。
		- 一个线程在获取锁资源的时候，首先判断`state`是否等于0（也就是说它是无锁状态），如果是则更新为1，表示占有锁。这个过程中，如果又个线程同时去做这样一个操作，就会导致线程安全性问题。因此，AQS采用了CAS机制去保证state互斥变量更新的一个原子性。未获得到锁的线程，通过Unsafe类中的park方法，进行阻塞，把阻塞的线程按照先进先出的原则，去加入到一个�


._SelectOnClick) buttonFlags /= Bf.PressedOnClick
        if (flags has Sf._SelectOnRelease) buttonFlags /= Bf.PressedOnRelease
        if (flags has Sf.AllowDoubleClick) buttonFlags /= Bf.PressedOnClickRelease or Bf.PressedOnDoubleClick
        if (flags has Sf.AllowOverlap|| g.lastItemData.inFlags has If.AllowOverlap) buttonFlags /= Bf.AllowOverlap

        val wasSelected = selected

        val behaviour = buttonBehavior(bb, id, buttonFlags)
        var pressed = behaviour[0]
        val hovered = behaviour[1]
        val held = behaviour[2]

        // Auto-select when moved into
        // - This will be more fully fleshed in the range-select branch
        // - This is not exposed as it won't nicely work with some user side handling of shift/control
        // - We cannot do 'if (g.NavJustMovedToId != id) { selected = false; pressed = was_selected; }' for two reasons
        //   - (1) it would require focus scope to be set, need exposing PushFocusScope() or equivalent (e.g. BeginSelection() calling PushFocusScope())
        //   - (2) usage will fail with clipped items
        //   The multi-select API aim to fix those issues, e.g. may be replaced with a BeginSelection() API.
        if (flags has Sf._SelectOnNav && g.navJustMovedToId != 0 && g.navJustMovedToFocusScopeId == g.currentFocusScopeId)
            if (g.navJustMovedToId == id) {
                selected = true; pressed = true
            }

        // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard
        if (pressed || (hovered && flags has Sf._SetNavIdOnHover))
            if (!g.navDisableMouseHover && g.navWindow === window && g.navLayer == window.dc.navLayerCurrent) {
                setNavID(id, window.dc.navLayerCurrent, g.currentFocusScopeId, window rectAbsToRel bb) // (bb == NavRect)
                g.navDisableHighlight = true
            }
        if (pressed)
            markItemEdited(id)

        // In this branch, Selectable() cannot toggle the selection so this will never trigger.
        if (selected != wasSelected)
            g.lastItemData.statusFlags /= ItemStatusFlag.ToggledSelection

        // Render
        if (hovered || selected) {
            val col = if (held && hovered) Col.HeaderActive else if (hovered) Col.HeaderHovered else Col.Header
            renderFrame(bb.min, bb.max, col.u32, false, 0f)
        }
        renderNavHighlight(bb, id, NavHighlightFlag.TypeThin or NavHighlightFlag.NoRounding)

        if (spanAllColumns && window.dc.currentColumns != null)
            popColumnsBackground()
        else if (spanAllColumns && g.currentTable != null)
            tablePopBackgroundChannel()

        renderTextClipped(textMin, textMax, label, labelSize, style.selectableTextAlign, bb)

        // Automatically close popups
        if (pressed && window.flags has Wf._Popup && flags hasnt Sf.DontClosePopups && g.lastItemData.inFlags hasnt If.SelectableDontClosePopup)
            closeCurrentPopup()

        if (disabledItem && !disabledGlobal)
            endDisabled()

        IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.lastItemData.statusFlags)
        return pressed
    }

    /** "bool* p_selected" point to the selection state (read-write), as a convenient helper.   */
    fun selectable(label: String, selectedPtr: KMutableProperty0<Boolean>, flags: SelectableFlags = none, size: Vec2 = Vec2()): Boolean {
        var selected by selectedPtr
        return if (selectable(label, selected, flags, size)) {
            selected = !selected
            true
        } else false
    }
}/*
 * Copyright 2014-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */
package org.jetbrains.dokka.gradle

import io.kotest.assertions.asClue
import io.kotest.assertions.withC


sparent !important;
    box-shadow: none !important;
}
.search-popout .results-group::before,
.search-popout .option::after,
.search-results-wrap .search-result::before,
.search-results-wrap .search-result::after {
    display: none;
}

/* HIGHLIGHTS */
.highlight {
    background-color: rgba(100, 100, 100, .3);
    color: #fff;
}
.markup[style*="color:"] .highlight {
    color: inherit;
    -webkit-filter: saturate(200%);
    filter: saturate(200%);
}

/* REACTIONS MODAL */
.message-reactions-modal {
    background-color: rgba(0, 0, 0, .7);
}
.message-reactions-modal .message-reactions-list .scroller-wrap {
    background-color: rgba(0, 0, 0, .3);
}
.message-reactions-modal .message-reactions-list-inner {
    background-color: transparent;
}
.message-reactions-modal .message-reactions-reactors .reactor {
    box-shadow: inset 0 -1px 0 0 hsla(0, 0%, 100%, .04);
}
.message-reactions-modal .message-reactions-list-inner .reaction {
    -webkit-transition: background-color .3s ease-in-out;
    transition: background-color .3s ease-in-out;
}
.message-reactions-modal .message-reactions-list-inner .reaction + .reaction {
    margin-top: 3px;
}
.message-reactions-modal .message-reactions-list-inner .reaction:not(.selected) {
    background-color: hsla(0, 0%, 100%, .04);
}
.message-reactions-modal .message-reactions-list-inner .reaction:not(.selected):hover {
    background-color: hsla(0, 0%, 100%, .1);
}
.message-reactions-modal .message-reactions-list-inner .reaction.selected {
    background-color: var(--hover-color) !important;
}
.message-reactions-modal .message-reactions-list-inner .reaction.selected:hover {
    background-color: var(--main-color) !important;
}
.message-reactions-modal .message-reactions-list-inner .reaction .count,
.message-reactions-modal .message-reactions-reactors .reactor .name {
    color: hsla(0, 0%, 100%, .5);
}
.message-reactions-modal .message-reactions-list-inner .reaction.selected .count {
    color: hsla(0, 0%, 100%, .7) !important;
}
.message-reactions-modal .message-reactions-reactors .reactor .remove {
    width:0px;
    height:0px;
    padding: 12px;
    margin-top: 8px;
    background-image: url(https://cdn.rawgit.com/Zerthox/ClearVision/master/icons/close.svg);
    background-repeat: no-repeat;
    background-position: center;
    background-size: 18px;
    opacity: .3;
}
.message-reactions-modal .message-reactions-reactors .reactor .remove:hover {
    opacity: .7;
}

/* TOOLTIP */
.tooltip,
.tooltip.tooltip-error {
    position: absolute;
    background-color: var(--main-color);
    -webkit-box-shadow: 0 2px 4px 1px rgba(0, 0, 0, .1);
    box-shadow: 0 2px 4px 1px rgba(0, 0, 0, .1);
    border-radius: 3px;
    font-weight: 600;
    font-size: 12px;
    color: #fff;
    z-index: 1002;
    max-width: 160px;
    box-sizing: border-box;
    word-wrap: break-word;
    padding: 5px 10px;
}
.tooltip::after {

}
.tooltip


/*
 * utils.c
 *
 * Common helper utilities.
 *
 * Copyright (C) 2021 Rinnegatamante
 * Copyright (C) 2022 Volodymyr Atamanenko
 *
 * This software may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */

#include "utils.h"

#include <psp2/io/stat.h>

#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <sys/time.h>

#pragma ide diagnostic ignored "bugprone-reserved-identifier"

// For check_kubridge
SceUID _vshKernelSearchModuleByName(const char *, int *);

void* retNULL(void) {
    return NULL;
}

int ret0(void) {
    return 0;
}

__attribute__((unused)) int ret1(void) {
    return 1;
}

int retminus1(void) {
    return -1;
}

void do_nothing(void) {
    // Silence is golden.
}

int file_exists(const char *path) {
    SceIoStat stat;
    return sceIoGetstat(path, &stat) >= 0;
}

// OpenSLES wants `assert()` and somehow we don't have it?
void assert(int i) {
    if (!i) {
        debugPrintf("assertion failed\n");
    }
}

int debugPrintf(char *text, ...) {
#ifdef DEBUG
    va_list list;
    static char string[0x8000];

    va_start(list, text);
    vsprintf(string, text, list);
    va_end(list);

    fprintf(stderr, "%s", string);
#endif
    return 0;
}

int check_kubridge(void) {
    int search_unk[2];
    return _vshKernelSearchModuleByName("kubridge", search_unk);
}

int string_ends_with(const char * str, const char * suffix)
{
    int str_len = (int)strlen(str);
    int suffix_len = (int)strlen(suffix);

    return
            (str_len >= suffix_len) &&
            (0 == strcmp(str + (str_len-suffix_len), suffix));
}

long long current_timestamp() {
    struct timeval te;
    gettimeofday(&te, NULL); // get current time
    long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate ms
    return milliseconds;
}


.Descriptor> contents;
  final DateTime? published;

  Version get version => Version.parse(pubspec['version'] as String);

  _ServedPackageVersion(this.pubspec, this.contents, {this.published});
}

/// Describes a tar file and its contents.
class TarFileDescriptor extends d.FileDescriptor {
  final List<d.Descriptor> contents;

  TarFileDescriptor(super.name, Iterable<d.Descriptor> contents)
    : contents = contents.toList(),
      super.protected();

  Future<Iterable<TarEntry>> allFiles(
    d.Descriptor descriptor, [
    String path = '.',
  ]) async {
    if (descriptor is d.FileDescriptor) {
      final size = await descriptor.readAsBytes().fold<int>(
        0,
        (i, l) => i + l.length,
      );
      return [
        TarEntry(
          TarHeader(
            name: '$path/${descriptor.name}',
            mode: 420,
            size: size,
            modified: DateTime.now(),
            userName: 'pub',
            groupName: 'pub',
          ),
          descriptor.readAsBytes(),
        ),
      ];
    }

    final dir = descriptor as d.DirectoryDescriptor;
    return [
      for (final c in dir.contents) ...await allFiles(c, '$path/${dir.name}'),
    ];
  }

  @override
  Stream<List<int>> readAsBytes() {
    return Stream.fromFutures(
      contents.map(allFiles),
    ).expand((x) => x).transform(tarWriter).transform(gzip.encoder);
  }
}
// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:convert';

import 'package:test_descriptor/test_descriptor.dart' as d;

/// Convenience for creating a descriptor of a package.
d.DirectoryDescriptor packageWithPathDeps(
  String name, {
  String? sdkConstraint,
  List<String> dependencies = const [],
  List<d.Descriptor> lib = const [],
  Map<String, Object> pubspecExtras = const {},
  List<d.Descriptor> extraFiles = const [],
}) {
  final pubspec = json.encode({
    'name': name,
    if (sdkConstraint != null) 'environment': {'sdk': sdkConstraint},
    'dependencies': {
      for (final dep in dependencies) dep: {'path': '../$dep'},
    },
    ...pubspecExtras,
  });
  final packageConfig = json.encode({
    'configVersion': 2,
    'packages': [
      {
        'name': name,
        'rootUri': '..',
        'packageUri': 'lib/',
        'languageVersion': '2.12',
      },
      for (final dep in dependencies)
        {
          'name': dep,
          'rootUri': '../../$dep',
          'packageUri': 'lib/',
          // TODO(sigurdm) somehow communicate the real language-version
          // Our analysis uses the bound in pubspec.yaml, so this doesn't cause
          // problems yet.
          'languageVersion': '2.12',
        },
    ],
  });
  return d.dir(name, [
    d.dir('.dart_tool', [d.file('package_config.json', packageConfig)]),
    d.file('pubspec.yaml', pubspec),
    d.dir('lib', lib),
    ...extraFiles,
  ]);
}

/// Convenience for creating a descriptor of a package.
d.DirectoryDescriptor package(
  String name, {
  String? version,
  String? sdkConstraint,
  Map<String, Object> dependencies = const {},
  List<d.Descriptor> lib = const [],
  Map<String, Object> pubspecExtras = const {},
  List<d.Descriptor> extraFiles = const [],
}) {
  final pubspec = json.encode({
    '


nteger.alias.hex,
        augend.date.alias["%Y/%m/%d"],
        augend.constant.new {
          elements = { "[x]", "[ ]" },
          word = false,
          cyclic = true,
        },
      },
      common = {
        augend.constant.new {
          elements = { "and", "or" },
          word = true, -- if false, "sand" is incremented into "sor", "doctor" into "doctand", etc.
          cyclic = true, -- "or" is incremented into "and".
        },
        augend.constant.new {
          elements = { "True", "False" },
          word = true,
          cyclic = true,
        },
        augend.constant.new {
          elements = { "yes", "no" },
          word = true,
          cyclic = true,
        },
        augend.constant.new {
          elements = { "&&", "||" },
          word = false,
          cyclic = true,
        },
        augend.date.alias["%Y/%m/%d"],
        augend.constant.alias.bool,
        augend.integer.alias.decimal,
        augend.integer.alias.hex,
        augend.semver.alias.semver,
      },
    }
  end,
  config = function(_, opts) require("dial.config").augends:register_group(opts) end,
}


de naturalista",
[92141] = "Piedra de ira de caminante del bosque",
[92142] = "Ídolo de ira de caminante del bosque",
[92143] = "Piedra de destrucción esclarecida",
[92144] = "Ídolo de destrucción esclarecido",
[92145] = "Piedra de sabiduría de partisano",
[92146] = "Ídolo de sabiduría de partisano",
[92147] = "Ídolo defensor de partisano",
[92148] = "Ídolo de batalla de partisano",
[92149] = "Piedra de batalla de partisano",
[92150] = "Ídolo de sabiduría de repartidor",
[92151] = "Piedra de destrucción de repartidor",
[92152] = "Espaldares de naturalista",
[92153] = "Bufas de caminante del bosque",
[92154] = "Hombreras esclarecidas",
[92155] = "Bufas de partisano",
[92156] = "Espaldares de partisano",
[92157] = "Guardahombros de partisano",
[92158] = "Manto de repartidor",
[92159] = "Hombreras de repartidor",
[92160] = "Sobrehombros de caminante oscuro",
[92161] = "Espaldares del clamatruenos",
[92162] = "Guardahombros del clamatruenos",
[92163] = "Hombreras de secuestrador de almas",
[92164] = "Bufas del clamatruenos",
[92165] = "Espaldares marciales",
[92166] = "Guardahombros marciales",
[92167] = "Ídolo de batalla de corazón de plaga",
[92168] = "Piedra de batalla de corazón de plaga",
[92169] = "Toga esclarecida",
[92170] = "Toga de repartidor",
[92171] = "Vestimentas de repartidor",
[92172] = "Toga de secuestrador de almas",
[92173] = "Baluarte de partisano",
[92174] = "Escudo de partisano",
[92175] = "Égida del clamatruenos",
[92176] = "Escudo del clamatruenos",
[92177] = "Baluarte marcial",
[92178] = "Espaldares de corazón de plaga",
[92179] = "Guardahombros de corazón de plaga",
[92180] = "Bufas de naturalista",
[92181] = "Sobrehombros de naturalista",
[92182] = "Colgante de partisano",
[92183] = "Collar de repartidor",
[92184] = "Medallón de repartidor",
[92185] = "Gargantilla del clamatruenos",
[92186] = "Gargantilla de caminante oscuro",
[92187] = "Medallón del clamatruenos",
[92188] = "Collar del clamatruenos",
[92189] = "Medallón de secuestrador de almas",
[92190] = "Colgante marcial",
[92191] = "Amuleto marcial",
[92192] = "Chafarote de caminante oscuro",
[92193] = "Rifle de caminante del bosque",
[92194] = "Varita esclarecida",
[92195] = "Varita de repartidor",
[92196] = "Varita de secuestrador de almas",
[92197] = "Musleras del clamatruenos",
[92198] = "Leotardos de secuestr


s
}

// Combine the output of all fragments into a strings
func CombineOutput(name string, responses []*crypto_proto.VeloMessage) string {
	result := []byte{}

	for _, item := range responses {
		if item.FileBuffer != nil &&
			item.FileBuffer.Pathspec.Path == name {
			result = append(result, item.FileBuffer.Data...)
		}
	}

	return string(result)
}

func GetIndex(responses []*crypto_proto.VeloMessage) []*actions_proto.Range {
	return responses[len(responses)-1].FileBuffer.Index.Ranges
}

func TestClientUploaderSparse(t *testing.T) {
	ctx := context.Background()

	resp := responder.TestResponderWithFlowId(nil, "TestClientUploaderSparse")
	uploader := NewVelociraptorUploader(ctx, nil, 0, resp)
	defer uploader.Close()

	BUFF_SIZE = 10000

	reader := &TestRangeReader{
		Reader: bytes.NewReader([]byte(
			"Hello world hello world")),
		ranges: []Range{
			{Offset: 0, Length: 6, IsSparse: false},
			{Offset: 6, Length: 6, IsSparse: true},
			{Offset: 12, Length: 6, IsSparse: false},
		},
	}
	range_reader, ok := interface{}(reader).(RangeReader)
	assert.Equal(t, ok, true)

	scope := vql_subsystem.MakeScope()
	uploader.maybeUploadSparse(ctx, scope,
		filename, "ntfs", nil, 1000, nilTime,
		resp.NextUploadId(),
		range_reader)

	responses := resp.Drain.WaitForEof(t)

	// Expected size is the combined sum of all ranges with data
	// in them
	assert.Equal(t, responses[0].FileBuffer.StoredSize, uint64(12))
	assert.Equal(t, responses[0].FileBuffer.Size, uint64(18))

	assert.Equal(t, CombineOutput("/foo", responses), "Hello hello ")
	for _, response := range responses {
		response.ResponseId = 0
	}
	goldie.Assert(t, "ClientUploaderSparse", json.MustMarshalIndent(responses))
}

// Test what happens when the underlying reader is shorter than the
// ranges.
func TestClientUploaderSparseWithEOF(t *testing.T) {
	ctx := context.Background()
	resp := responder.TestResponderWithFlowId(
		nil, "TestClientUploaderSparseWithEOF")
	uploader := NewVelociraptorUploader(ctx, nil, 0, resp)
	defer uploader.Close()

	BUFF_SIZE = 10000

	reader := &TestRangeReader{
		Reader: bytes.NewReader([]byte("Hello world hi")), // len=11
		ranges: []Range{
			{Offset: 0, Length: 6, IsSparse: false},
			{Offset: 6, Length: 6, IsSparse: true},

			// Range exceeds size of reader.
			{Offset: 12, Length: 6, IsSparse: false},
		},
	}
	range_reader, ok := interface{}(reader).(RangeReader)
	assert.Equal(t, ok, true)

	scope := vql_subsystem.MakeScope()
	uploader.maybeUploadSparse(ctx, scope,
		filename, "ntfs", nil, 1000, nilTime,
		resp.NextUploadId(),
		range_reader)

	var responses []*crypto_proto.VeloMessage
	vtesting.WaitUntil(time.Second*5, t, func() bool {
		responses = resp.Drain.Messages()
		return CombineOutput("/foo", responses) == "Hello hi"
	})

	// Expected size is the combined sum of all ranges with data
	// in them
	assert.Equal(


are from the same cartridge
    if (_GCWandLUAareFromDifferentCartridges()) {
      // files belong to different cartridges
      WherigoCartridgeLUAData = _resetLUA('wherigo_error_diff_gwc_lua_1');
      _getLUAOnline = true;
      _WherigoShowLUASourcecodeDialog = true;
      toastMessage =
          i18n(context, 'wherigo_error_diff_gwc_lua_1') + '\n' + i18n(context, 'wherigo_error_diff_gwc_lua_2');
    }
    _fileLoadedState = WHERIGO_FILE_LOAD_STATE.GWC;
    _displayedCartridgeData = WHERIGO_OBJECT.HEADER;

    _updateOutput();

    SchedulerBinding.instance.addPostFrameCallback((_) {
      showSnackBar(toastMessage, duration: toastDuration, context);
    });

    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {});
    });
  }

  bool _GCWandLUAareFromDifferentCartridges() {
    return ((WherigoCartridgeGWCData.CartridgeGUID != WherigoCartridgeLUAData.CartridgeGUID &&
            WherigoCartridgeLUAData.CartridgeGUID != '') &&
        (WherigoCartridgeGWCData.CartridgeLUAName != WherigoCartridgeLUAData.CartridgeLUAName &&
            WherigoCartridgeLUAData.CartridgeLUAName != ''));
  }

  void _updateOutput() {
    _buildZonesForMapExport();
    _buildItemPointsForMapExport();
    _buildCharacterPointsForMapExport();
    buildHeader(context);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      setState(() {});
    });
  }

  void _buildItemPointsForMapExport() {
    _ItemPoints.clear();

    // Build data
    for (var item in WherigoCartridgeLUAData.Items) {
      if (item.ItemZonepoint.Latitude != 0.0 && item.ItemZonepoint.Longitude != 0.0) {
        if (WHERIGONameToObject[item.ItemLUAName] == null) continue;

        _ItemPoints.add(// add location of item
            GCWMapPoint(
                uuid: 'Point ' + WHERIGONameToObject[item.ItemLUAName]!.ObjectName,
                markerText: WHERIGONameToObject[item.ItemLUAName]!.ObjectName,
                point: LatLng(item.ItemZonepoint.Latitude, item.ItemZonepoint.Longitude),
                color: Colors.black));
      }
    }
  }

  void _buildCharacterPointsForMapExport() {
    _CharacterPoints.clear();

    // Build data
    for (var character in WherigoCartridgeLUAData.Characters) {
      if (character.CharacterLocation == 'ZonePoint') {
        if (WHERIGONameToObject[character.CharacterLUAName] == null) continue;

        _CharacterPoints.add(// add location of character
            GCWMapPoint(
                uuid: 'Point ' + WHERIGONameToObject[character.CharacterLUAName]!.ObjectName,
                markerText: WHERIGONameToObject[character.CharacterLUAName]!.ObjectName,
                point: LatLng(character.CharacterZonepoint.Latitude, character.CharacterZonepoint.Longitude),
                color: Colors.black));
      }
    }
  }

  void _buildZonesForMapExport() {
    // Clear data

    _ZonePoints.clear();
    _ZonePolylines.clear();

    // Build data
    for (WherigoZoneData zone in WherigoCartridgeLUAData.Zones) {
      if (WHERIGONameToObject[zone.ZoneLUAName] == null) {
        return;
      }

      _ZonePoints.add(// add originalpoint of zone
          GCWMapPoint(
              uuid: 'Original Point ' + WHERIGONameToObject[zone.ZoneLUAName


"%DF", "%E0", "%E1", "%E2", "%E3", "%E4", "%E5", "%E6",
        "%E7", "%E8", "%E9", "%EA", "%EB", "%EC", "%ED", "%EE",
        "%EF", "%F0", "%F1", "%F2", "%F3", "%F4", "%F5", "%F6",
        "%F7", "%F8", "%F9", "%FA", "%FB", "%FC", "%FD", "%FE",
        "%FF",
    },
    PATH_PART = {
        "%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07",
        "%08", "%09", "%0A", "%0B", "%0C", "%0D", "%0E", "%0F",
        "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17",
        "%18", "%19", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F",
        "%20", "!", "%22", "%23", "$", "%25", "&", "'", "(", ")",
        "*", "+", ",", "-", ".", "%2F", "0", "1", "2", "3",
        "4", "5", "6", "7", "8", "9", ":", ";", "%3C", "=",
        "%3E", "%3F", "@", "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", "%5B", "%5C",
        "%5D", "%5E", "_", "%60", "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", "%7B",
        "%7C", "%7D", "~", "%7F", "%80", "%81", "%82", "%83",
        "%84", "%85", "%86", "%87", "%88", "%89", "%8A", "%8B",
        "%8C", "%8D", "%8E", "%8F", "%90", "%91", "%92", "%93",
        "%94", "%95", "%96", "%97", "%98", "%99", "%9A", "%9B",
        "%9C", "%9D", "%9E", "%9F", "%A0", "%A1", "%A2", "%A3",
        "%A4", "%A5", "%A6", "%A7", "%A8", "%A9", "%AA", "%AB",
        "%AC", "%AD", "%AE", "%AF", "%B0", "%B1", "%B2", "%B3",
        "%B4", "%B5", "%B6", "%B7", "%B8", "%B9", "%BA", "%BB",
        "%BC", "%BD", "%BE", "%BF", "%C0", "%C1", "%C2", "%C3",
        "%C4", "%C5", "%C6", "%C7", "%C8", "%C9", "%CA", "%CB",
        "%CC", "%CD", "%CE", "%CF", "%D0", "%D1", "%D2", "%D3",
        "%D4", "%D5", "%D6", "%D7", "%D8", "%D9", "%DA", "%DB",
        "%DC", "%DD", "%DE", "%DF", "%E0", "%E1", "%E2", "%E3",
        "%E4", "%E5", "%E6", "%E7", "%E8", "%E9", "%EA", "%EB",


(state, (patch) => patches.push(patch));

        return {
            state: Object.assign({}, state, ...patches),
            $currentScene: nextSceneId,
        };
    }
}
import schoolService from '@services/school.service';
import courseService from '@services/course.service';
import personService from '@services/person.service';

import { Request, Response } from 'express';

export const getAllSchoolsRoute = async (req: Request, res: Response) => {
  const allSchools = await schoolService.getAllSchools();

  if (allSchools) {
    return res.json({success: true, msg: 'Successfully added school', schools: allSchools});
  }
  return res.json({success: false, msg: 'Could not add school...'});
};

export const getSchoolInstructorsRoute = async (req: Request, res: Response) => {
  const query = {
    personType: 'instructor',
    schoolID: req.params.schoolID
  }
  const schoolInstructors = await personService.findModelsByQuery(query);

  if (schoolInstructors) {
    return res.json({success: true, msg: 'Found instructors!', instructors: schoolInstructors})
  }
  return res.json({success: false, msg: 'Could not find instructors'});
};

export const getInstructorCoursesRoute = async (req: Request, res: Response) => {
  let query = {
    schoolID: req.params.schoolID,
    instructorID: req.params.profileURL
  };

  const foundCourses = await courseService.findModelsByQuery(query);
  if (foundCourses) {
    return res.json({success: true, msg: 'Successfully found courses', courses: foundCourses});
  } else {
    return res.json({success: false, msg: 'Could not find courses...'});
  }
};
import { configureStore } from "@reduxjs/toolkit"
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux"

import { reducer as users } from "./usersSlice"

export const store = configureStore({
  reducer: {
    users,
  },
})

const oldUsers = store.getState().users.users
store.subscribe(() => {
  const users = store.getState().users.users
  if (oldUsers !== users) {
    console.log("hydrating users..")
    localStorage.setItem("users", JSON.stringify(users))
  }
})

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import {User} from './user.model'
@Injectable({
  providedIn: 'root'
})
export class UserService {
  // Subject Added
  userChange=new Subject<User[]>();

  private userData:User[]=[
    new User(1,'Sourav Sharma','Sourav12@gmail.com')
  ];
  constructor() { }
  addUser(users:User){
    this.userData.push(users);
    this.userChange.next(this.userData.slice());
  }
  showUser(){
    console.log("service"+this.userData.values);
   return this.userData.slice();
  }
}
import { Get, Controller, Post, Query, Body, HttpCode, ValidationPipe } from '@nestjs/common';
import { MovieService } from '../services/movie.service';
import { AddMovieDTO } from '../models/add-movie.dto';

@Controller('/movies')
export class MovieController {
  constructor(


ile.

import 'dart:collection';

import 'package:observable/observable.dart';

/// Describes an entity and its previous location (or marking it as a new one).
class DiffEntry<T> {
  static const _DEFAULT_NEW_ENTRY_INDEX = -1;

  final T entity;
  final int prevIndex;
  bool get isNew => (prevIndex == _DEFAULT_NEW_ENTRY_INDEX);
  bool get isOld => !isNew;

  DiffEntry.oldEntry(this.entity, this.prevIndex) {
    assert(prevIndex >= 0);
  }

  DiffEntry.newEntry(this.entity) : prevIndex = _DEFAULT_NEW_ENTRY_INDEX;
}

/// Describes the difference of two lists.
abstract class ListDiff<T> {
  /// The entries in the current list.
  List<DiffEntry<T>> get entries;

  /// The deleted entries.
  List<DiffEntry<T>> get deleted;

  factory ListDiff.compare(List<T> prev, List<T> curr) =>
      _ComparingListDiff(prev, curr);

  factory ListDiff.fromObservable(List<ListChangeRecord> event) =>
      _ObservedListDiff(event);
}

class _ComparingListDiff<T> implements ListDiff<T> {
  List<DiffEntry<T>> entries = [];
  List<DiffEntry<T>> deleted = [];

  _ComparingListDiff(List<T> prev, List<T> curr) {
    _calculateEntries(prev, curr);
  }

  // TODO(google): make calculation of [entries] or the sorting of [deleted]
  // deferred to the time of the getter call
  void _calculateEntries(List<T> prev, List<T> curr) {
    var map = LinkedHashMap<T, DiffEntry<T>>();
    for (int i = 0; i < prev.length; i++) {
      T entity = prev[i];
      assert(!map.containsKey(entity));
      map[entity] = DiffEntry<T>.oldEntry(entity, i);
    }
    for (int i = 0; i < curr.length; i++) {
      T entity = curr[i];
      var entry = map.remove(entity);
      if (entry == null) {
        entry = DiffEntry<T>.newEntry(entity);
      }
      entries.add(entry);
    }
    deleted.addAll(map.values);
  }
}

class _ObservedListDiff<T> implements ListDiff<T> {
  List<DiffEntry<T>> entries;
  List<DiffEntry<T>> deleted;

  _ObservedListDiff(List<ListChangeRecord> event) {
    _processEvent(event);
  }

  void _processEvent(List<ListChangeRecord> event) {
    var removed = <T, DiffEntry<T>>{};
    entries = <DiffEntry<T>>[];

    int offset = 0;
    for (int eventIndex = 0; eventIndex < event.length; eventIndex++) {
      ListChangeRecord record = event[eventIndex];
      for (int i = entries.length; i < record.index; i++) {
        entries.add(DiffEntry<T>.oldEntry(record.object[i] as T, i + offset));
      }
      for (int i = 0; i < record.removed.length; i++) {
        var entity = record.removed[i] as T;
        assert(!removed.containsKey(entity));
        removed[entity] =
            DiffEntry<T>.oldEntry(entity, record.index + offset + i);
      }
      offset += record.removed.length;
      for (int i = 0; i < record.addedCount; i++) {
        var entity = record.object[record.index + i] as T;
        var entry = removed.remove(entity);
        if (entry == null) {
          entry = DiffEntry<T>.newEntry(entity);
        }
        entries.add(entry);
      }
      offset -= record.addedCount;
    }
    for (int i = entries.length; i < event.last.object.length; i++) {
      entries.add(DiffEntry<T>.oldEntry(event.last.object[i] as T, i + offset));
    }
    if (removed.isNotEmpty


t)=> void): Query
	mouseenter(): Query
	mouseenter(handler: (event: MouseEvent)=> void): Query
	mouseleave(): Query
	mouseleave(handler: (event: MouseEvent)=> void): Query
	mousemove(): Query
	mousemove(handler: (event: MouseEvent)=> void): Query
	mouseout(): Query
	mouseout(handler: (event: MouseEvent)=> void): Query
	mouseover(): Query
	mouseover(handler: (event: MouseEvent)=> void): Query
	mouseup(): Query
	mouseup(handler: (event: MouseEvent)=> void): Query
	change(): Query
	change(handler: (event: Event)=> void): Query
	select(): Query
	on(events: string, handler: (eventObject: Event, ...args: any[]) => any): Query
	isHTMLInput(): boolean
	isHTMLInputText(): boolean
	isHTMLInputNumber(): boolean
	isHTMLInputCheckbox(): boolean
	isHTMLInputRadio(): boolean
	isHTMLTextarea(): boolean
	isHTMLSelect(): boolean
	isHTMLMultipleSelect(): boolean
}
interface QueryStatic {
	(): Query
	(selector: string): Query
	(element: Element | HTMLElement | EventTarget | Document | Window): Query
	(elements: Array<Element> | Array<HTMLElement>): Query
	(loaded: ()=> void): void
	each<T>(each: (array: Array<T>, index: number)=> void): void
	//extend<T>(deep: boolean, obj1: T, obj2: T): T
}
declare var Q: QueryStaticimport { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  form;

  constructor(private fb: FormBuilder, private auth: AuthService) {
    this.form = fb.group({
      email: ['', [Validators.required, Validators.email, emailValid()]],
      password: ['', [Validators.required]]
    });
  }

  ngOnInit() {
  }

  onSubmit() {
    if(this.form.controls.email !== '' && this.form.controls.password !== ''){
      this.auth.login(this.form.value);
    }

  }

  isValid(control) {
    return this.form.controls[control].invalid && this.form.controls[control].touched;
  }

}

function emailValid() {
  return control => {
// tslint:disable-next-line: max-line-length
    let regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    return regex.test(control.value) ? null : {invalidEmail: true};
  };
}
import { VNode, VText } from "./vdom";

/**
 * VElement
 * 静态虚节点，无任何状态
 */
export class VElement {
  public tagName: string;
  public props: VElementProps;
  public children: VNode[];

  constructor(tagName: string, props: VElementProps, children: (VNode | string)[]) {
    this.tagName = tagName;
    this.props = props;
    this.children = [];

    for (const c of children) {
      if (typeof c === "string") {
        this.children.push(new VText(c));
      } else {
        this.children.push(c);
      }
    }
  }
}
//import * as $ from 'jquery';
import WS from '../../../src';

describe('Cut tests.', () => {
    it('Triggers process when cut and updates intervals correctly.', () => {
        const container = document.createElement('div');
        WS.set


:44.2% + PC2:19.5%)
最大方差方向特征：
- PC1: 细胞尺寸相关特征(radius, perimeter, area)
- PC2: 细胞形态相关特征(concavity, concave points)
```

---

### Ⅲ. **动态投影过程模拟**
```python
# 逐步投影演示代码
import numpy as np
from sklearn.decomposition import PCA

# 原始数据标准化
X_centered = X_train_scaled - np.mean(X_train_scaled, axis=0)

# 手动计算主成分
cov_matrix = np.cov(X_centered, rowvar=False)
eigen_values, eigen_vectors = np.linalg.eigh(cov_matrix)
sorted_index = np.argsort(eigen_values)[::-1]
W = eigen_vectors[:, sorted_index[:2]]

# 动态显示前5个样本的投影
print("样本投影轨迹:")
for i in range(5):
    original = X_centered[i]
    projected = original @ W
    print(f"样本{i}: [{original[0]:.1f},..] → [{projected[0]:.1f}, {projected[1]:.1f}]")
```

**输出示例**：
```
样本0: [2.1,..] → [3.2, -0.5] (恶性)
样本1: [-0.3,..] → [-1.8, 0.2] (良性)
样本2: [1.8,..] → [2.7, 1.1] (恶性)
```

---

### Ⅳ. **特征重要性热力图（文本版）**
```
主成分1(PC1)特征载荷Top5:
1. mean radius: ████████ 0.42
2. mean perimeter: ███████ 0.40
3. mean area: ███████ 0.39
4. worst radius: ██████ 0.38
5. worst perimeter: █████ 0.37

主成分2(PC2)特征载荷Top5:
1. worst concave points: ███████ 0.35
2. mean concave points: ██████ 0.33
3. worst concavity: █████ 0.31
4. mean concavity: ████ 0.29
5. symmetry error: ███ 0.25
```
- █ 的长度表示特征对主成分的贡献度

---

### Ⅴ. **决策边界文本模拟**
```
逻辑回归决策边界在PC空间的投影

           |
           |   B        B
           |     B  B
    M M    |   决策边界
  M   M M  |-------/-------
      M    | /
           |/
           +-------------
```
- `B`: 良性样本区域
- `M`: 恶性样本区域
- `/` 斜线表示分类边界


 IVector2 = Vec2d.ZERO
    override val size: IVector2 = Vec2d.ZERO
    override lateinit var gui: IGui

    lateinit var scrollBar: ScrollBar
    lateinit var searchBar: SearchBar
    lateinit var container: ContainerShelvingUnit
    var lastScroll = 0

    override fun init() {
        container = (gui as GuiBase).container as ContainerShelvingUnit
        scrollBar = gui.components.filterIsInstance<ScrollBar>().first()
        searchBar = gui.components.filterIsInstance<SearchBar>().first()
        searchBar.onChange = container::setFilter

        val select = gui.components.filterIsInstance<SelectButton>().first()
        val oldCallback = select.onClick

        select.onClick = {
            searchBar.textField.text = ""
            oldCallback(it)
        }
    }

    override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
        val scroll = scrollBar.section
        val auto = gui as AutoGui
        auto.slots = auto.createSlots(container.inventorySlots)

        if (lastScroll != scroll) {
            lastScroll = scroll
            val scrollPercent = scroll / scrollBar.sections.toFloat()
            container.withScroll(scrollPercent)
            container.sendUpdate(IBD().setFloat(DATA_ID_SHELVING_UNIT_SCROLL, scrollPercent))
        }
    }

    override fun drawSecondLayer(mouse: Vec2d) {
        val scrollPercent = scrollBar.section / scrollBar.sections.toFloat()
        val columnIndex = scrollPercent * ((container.currentSlots.size / 9f) - 5)
        val column = Math.max(0, Math.round(columnIndex))

        gui.bindTexture(guiTexture("misc"))

        (0 until 5 * 9).forEach {
            val pos = it + column * 9
            if (pos >= container.currentSlots.size) {
                val x = it % 9 * 18 + 7
                val y = it / 9 * 18 + 20

                gui.drawTexture(
                    vec2Of(x, y),
                    vec2Of(18, 18),
                    vec2Of(180, 69)
                )
            }
        }

        val filterText = searchBar.textField.text
        if (container.currentSlots.isEmpty() && (filterText.isEmpty() || filterText.isBlank())) {
            val start = vec2Of(6, 56)
            val end = start + vec2Of(164, 17)

            color(1f, 1f, 1f, 1f)
            gui.drawColor(start, end, 0xF0000000.toInt())
            gui.drawCenteredString(
                text = I18n.format("text.magneticraft.shelving_unit_add_chests"),
                pos = vec2Of(88, 61),
                color = 0xFFFFFFFF.toInt()
            )
            enableBlend()
            color(1f, 1f, 1f, 1f)
        }
    }
}package com.cout970.magneticraft.systems.gui.components.buttons

import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.misc.vector.*
import net.minecraft.util.ResourceLocation

class MultiButton(
    id: Int = 0,
    texture: ResourceLocation? = null,
    box: Pair<IVector2, IVector2>,
    textureSize: IVector2 = vec2Of(256),
    uv: (ButtonState) -> Pair<IVector2, IVector2>
) : AbstractButton(id, texture, box, textureSize, uv) {

    lateinit var allButtons: List<MultiButton>

    override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
        if (mouse in (gui.pos + box.pos to box.size)) when {
            state.getBase() == ButtonState.PRESSED -> state = ButtonState.HOVER_PRESSED
            else -> state =


 Neighbors problem
description:
duration: 420
card_type: cue_card
---

### Grid Approach
We can break the entire world into small grids (maybe 1 km sq. grids). Then to get all the points, we only need to consider the locations in the grid of our current location or the points in the adjacent grids. If there are enough points in these grids, then we can get all the nearest neighbors. The query and to get all the neighbors is depicted below:
```sql
SELECT * FROM places WHERE  grid_id IN (grid1, grid2, grid3……)
```
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/752/original/upload_39d248bd073c536e58c2d2737210c188.png?1695264888)

### What should be the size of the grid?
It is not ideal to have a uniform grid size worldwide. The grid size should be small for dense areas and large for sparse areas. For example, the grid size needs to be very large for the ocean and very small for densely populated areas. The thumb rule is that size of the grid is to be decided based on the number of points it contains. We need to design variable-size grids so that they have just enough points. Points are also dynamically evolving sets of places.

![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/753/original/upload_3e3003156a4c27d2bbbdbcbcbceecf19.png?1695264907)

### Dividing the entire world into variable-size grids so that every grid has approximately 100 points
So our problem statement reduces to preprocess all the places in the world so that we can get variable-size grids containing 100 points. We also need to have some algorithm to add or delete a point (a location such as a restaurant).

This can be achieved using **quadtrees**.

---
title: Using QuadTree to solve the Neighbors problem
description: Creation of quad tree.
duration: 420
card_type: cue_card
---

## QuadTree

### Creation
Imagine the entire world with billions of points (think of a world map, a rectangle with points all over).

* We can say that the entire world is a root of a tree and has all of the places of the world. We create a tree; if the current node has more than 100 points, then we need to create its four children (four because we need to create the same shape as a rectangle by splitting the bigger grid into four parts).
![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/754/original/upload_7bbd81a1a4e7dcec78f84f7808d770a4.png?1695264936)

* We recursively repeat the process for the four parts as well. If any children have more than 100 points, it further divides itself into four children. Every child has the same shape as the parent, a rectangle.

![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/755/original/upload_e02b336e3dc16fd988f657e79998ea3b.png?1695268515)

![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/756/original/upload_5c15e05d5a334c9336f49d7e15547770.png?1695268596)

* All the leaf nodes in the tree will have less than 100 points/places. And the tree's height will be ~log(N), N being the number of places in the world.

---
title: Finding Grid ID
description:
duration: 420
card_type: cue_card
---

### Finding Grid ID
Now, suppose I give you my location (x,y) and ask you which grid/leaf I belong to. How will you do that? You can assume the whole world extends between coordinates (x1, y1) and (x2, y2).

![](https://d2beiqkhq929f0.cloudfront.net/public_assets/assets/000/049/757/original/upload_b336849bd8c6630a0ebaba0b1cd625ff.png?1695268632)

What I can do is calculate the middle point for the x and y coordinates, Xmid = (x1 + x2) / 2, Ymid = (y1 + y2) / 2. And then, I can check if the x is bigger than Xmid. If yes


�芹。《红楼梦》写的贾、史、王、薛大家族，他们是奴隶主，三十二人。写奴隶女，鸳鸯、晴雯、小红等，都是很好的，受害的是这些人。林黛玉不是属于四人家族的。

   2．社会主义教育。社会主义教育的方法有两大条：

   第一条是把中央的精神和干部、群众见面，讲解清楚，结合当地的具体情况、具体工作、具体事实，让群众揭盖子。

   第二条，要让老一辈重新回忆受压迫、受剥削的历史，激发阶级感情，让青年一代知道革命斗争果实来之不易，让他们续一续无产阶级的家谱。

   3．依靠贫下中农。依靠谁的问题，一万年也有，到将来总还有唯心主义和唯物主义、先进和落后、左中右的矛盾。在今天依靠谁？总得有一个阶级。依靠全民？说依靠全民，实际上是依靠少数人。有人说“地富听话，中农调皮，贫农糊涂。”地富怎么不听话？又送东西，又送女人，可是他是要你听他的话。

   什么叫心情舒畅？贫农、下中衣受到压抑，不能抬头，心情怎么能舒畅？贫农、下中农不舒畅，干部怎么能够舒畅？

   资产阶级说他们后继无人，怎么说后继无人？黑格尔的后继人是马克思，资产阶级的后继人是无产阶级。资产阶级抓“三自一包”，想卷土重来，我们就要在这方面打击他，打掉他的基础，不让他拉后继人。

   四、四清

   什么叫贪污？五十元？一百元？二百元？只要坦白了，退了赃，就不算贪污。

   赃要退，也要合情合理，退到手脚干净，又要退到让干部能够生活。这样做究竟退多少？是不是采取自报公议的办法。

   惩办要控制在百分之一。

   今年不要开杀戒，明年再说。罪大恶极的也先放慢一些，现行反革命按规定办理。群众要求非杀不可的，是有道理


: string, slack_token: string, slack_channel: string) {
    this.class_name = class_name;
    this.slack_token = slack_token;
    this.slack_channel = slack_channel;
  }
}
import { Client, ClientUser, Message, Guild, GuildMember, PermissionFlagsBits, ChannelType } from 'discord.js'
import { GuildSetting } from '../db/models'
import { Mute } from '.'

interface GuildMap {
  guild: Guild
  messageLimit: number
  messageTimeframe: number
  muteDuration: number
  memberMap: Map<string, MemberMessageMap>
}

interface MemberMessageMap {
  member: GuildMember
  messageMap: Map<string, MessageMap>
}

interface MessageMap {
  message: Message
  timeout: NodeJS.Timeout
}

export class SpamFilter {

  private guildMap: Map<string, GuildMap>

  constructor(client: Client) {
    this.guildMap = new Map<string, GuildMap>()
    this.processMessages(client)
  }

  private processMessages = (client: Client) => {

    client.on('messageCreate', async (message) => {

      const clientUser = client.user as ClientUser

      const { guild, member, channel } = message
      if (!guild || !member) return

      const clientMember = guild.members.cache.get(clientUser.id)
      if (!clientMember) return

      // exemption
      if (member.permissions.has(PermissionFlagsBits.ManageMessages)) return

      if (!this.guildMap.has(guild.id)) {
        await (this.refreshGuildSetting(guild))
      }

      const instance = this.guildMap.get(guild.id)
      if (!instance) return
      if (!instance.memberMap.has(member.id)) {
        instance.memberMap.set(member.id, {
          member,
          messageMap: new Map<string, MessageMap>()
        })
      }

      const memberInstance = instance.memberMap.get(member.id)
      if (!memberInstance) return

      // Add the message to the map
      const timeout = setTimeout(() => {
        memberInstance.messageMap.delete(message.id)
        if (memberInstance.messageMap.size === 0) instance.memberMap.delete(member.id)
        clearTimeout(timeout)
      }, instance.messageTimeframe)
      memberInstance.messageMap.set(message.id, { message, timeout })

      if (memberInstance.messageMap.size + 1 === instance.messageLimit + 1) {
        // Too many messages, execute mute
        const messages = [...memberInstance.messageMap.values()].map(item => item.message)
        if (channel.type === ChannelType.GuildText) (channel as any).bulkDelete(messages)
        new Mute({
          user: clientMember,
          target: member,
          reason: 'Muted by AutoMod for spam.',
          duration: instance.muteDuration,
        })
      }

    })
  }

  private fetchGuildSetting = (guildId: string) => {
    return GuildSetting.fetchByGuildId(guildId)
  }

  public refreshGuildSetting = async (guild: Guild) => {
    const settings = await this.fetchGuildSetting(guild.id)
    if (!settings) return
    this.guildMap.set(guild.id, {
      guild,
      messageLimit: settings.messageLimit,
      messageTimeframe: settings.messageTimeframe,
      muteDuration: settings.muteDuration,
      memberMap: new Map<string, MemberMessageMap>(),
    })
  }

}import { PokemonSheet } from "./pokedex";

export const HP = 0;
export const Attack = 1;
export const Defense = 2;
export const Speed = 3;
e


.0, 4.0), vec2.Create(5.0, 6.0));

		assertEquals(r, {
			r00 : 1.0, r10 : 2.0, r20 : 0.0,
			r01 : 3.0, r11 : 4.0, r21 : 0.0,
			r02 : 5.0, r12 : 6.0, r22 : 1.0
		}, epsilon);
		assert.strictEqual(m, r);
	});
});

describe('ShearMatrix4', () => {
	it('should return a Matrix3 representing a shear', () => {
		assertEquals(mat3.ShearMatrix4({
			r00 :  1.0, r10 :  2.0, r20 :  3.0, r30 :  4.0,
			r01 :  5.0, r11 :  6.0, r21 :  7.0, r31 :  8.0,
			r02 :  9.0, r12 : 10.0, r22 : 11.0, r32 : 12.0,
			r03 : 13.0, r13 : 14.0, r23 : 15.0, r33 : 16.0
		} as mat4.Matrix4), {
			r00 : 1.0, r10 :  2.0, r20 :  3.0,
			r01 : 5.0, r11 :  6.0, r21 :  7.0,
			r02 : 9.0, r12 : 10.0, r22 : 11.0
		}, epsilon);
	});
});

describe('shearMatrix4', () => {
	it('should set a Matrix3 to represent a shear', () => {
		const m = mat4.Identity();
		const r = mat3.shearMatrix4(m, {
			r00 :  1.0, r10 :  2.0, r20 :  3.0, r30 :  4.0,
			r01 :  5.0, r11 :  6.0, r21 :  7.0, r31 :  8.0,
			r02 :  9.0, r12 : 10.0, r22 : 11.0, r32 : 12.0,
			r03 : 13.0, r13 : 14.0, r23 : 15.0, r33 : 16.0
		} as mat4.Matrix4);

		assertEquals(r, {
			r00 : 1.0, r10 :  2.0, r20 :  3.0,
			r01 : 5.0, r11 :  6.0, r21 :  7.0,
			r02 : 9.0, r12 : 10.0, r22 : 11.0
		}, epsilon);
		assert.strictEqual(m, r);
	});
});

describe('Add', () => {
	it('should return a Matrix3 representing an addition', () => {
		assertEquals(mat3.Add({
			r00 : 1.0, r10 :  2.0, r20 :  3.0,
			r01 : 5.0, r11 :  6.0, r21 :  7.0,
			r02 : 9.0, r12 : 10.0, r22 : 11.0
		}, {
			r00 : 0.01, r10 : 0.02, r20 : 0.03,
			r01 : 0.05, r11 : 0.06, r21 : 0.07,
			r02 : 0.09, r12 : 0.10, r22 : 0.11
		}), {
			r00 : 1.01, r10 :  2.02, r20 :  3.03,
			r01 : 5.05, r11 :  6.06, r21 :  7.07,
			r02 : 9.09, r12 : 10.10, r22 : 11.11
		}, epsilon);
	});
});

describe('add', () => {
	it('should set a Matrix3 to represent an addition', () => {
		const m = mat3.Identity();
		const r = mat3.add(m, {
			r00 : 1.0, r


rieves a Census document by its root.
func (ms *MongoStorage) CensusFromElection(electionID types.HexBytes) (*Census, error) {
	ms.keysLock.RLock()
	defer ms.keysLock.RUnlock()
	return ms.censusFromElection(electionID)
}

// censusFromRoot retrieves a Census document by its root. It does not adquire the keysLock.
func (ms *MongoStorage) censusFromElection(electionID types.HexBytes) (*Census, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	var census Census
	err := ms.census.FindOne(ctx, bson.M{"electionId": electionID.String()}).Decode(&census)
	if err != nil {
		if err == mongo.ErrNoDocuments {
			return nil, ErrElectionUnknown
		}
		return nil, fmt.Errorf("cannot find Census with electionID: %w", err)
	}

	return &census, nil
}

// SetElectionIdForCensusRoot updates the electionId for a given census document.
// It will only be set if the electionId field is empty.
// If the census does not exist, it returns nil without error.
func (ms *MongoStorage) SetElectionIdForCensusRoot(root, electionID types.HexBytes) error {
	ms.keysLock.Lock()
	defer ms.keysLock.Unlock()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// Prepare the filter to find the first census document with the given root and an empty electionId
	filter := bson.M{
		"root":       root.String(),
		"electionId": "", // Match only documents where electionId is an empty string
	}

	// Prepare the update document to set the new ElectionID
	update := bson.M{"$set": bson.M{"electionId": electionID.String()}}

	// Execute the update operation, limiting to the first match
	_, err := ms.census.UpdateOne(ctx, filter, update)
	if err != nil {
		return fmt.Errorf("cannot update ElectionID for Census with root %s: %w", root.String(), err)
	}

	return nil
}
package mongo

import (
	"context"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

// SetDelegation inserts a delegation into the database and returns the ID of
// the inserted delegation
func (ms *MongoStorage) SetDelegation(delegation Delegation) (string, error) {
	// Insert the delegation into the database and retrieve the ID
	ms.keysLock.Lock()
	defer ms.keysLock.Unlock()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	delegation.ID = primitive.NewObjectID()
	if _, err := ms.delegations.InsertOne(ctx, delegation); err != nil {
		return "", err
	}
	return delegation.ID.Hex(), nil
}

// Delegation retrieves a delegation from the database by its ID
func (ms *MongoStorage) Delegation(id string) (Delegation, error) {
	ms.keysLock.RLock()
	defer ms.keysLock.RUnlock()

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	_id, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return Delegation{}, err
	}

	var delegation Delegation
	if err = ms.delegations.FindOne(ctx, bson.M{"_id": _id}).Decode(&delegation); err != nil {
		return Delegation{},