问:
How can I access and change the tag description property of a JPEG image in the Windows 7 file explorer through the use of Python?
I am having a difficult time understanding how I can change the Tags of a JPEG file through Python. The "Tags" I'm referring to are those under the description properties of any arbitrary file, where comments, subjects, and ratings would also be found. I am uncertain whether or not there is a .os function similar to the filename rename function which can do this, or if this kind of operation of changing the tags would fall under the category of JPEG Metadata/EXIFDATA manipulation.

Say, for example, I want to add 3 tags to a JPEG image through Python, those being the tags BLUE, SQUARE, and 9. Manually I would go to the file, access the description properties either by right-clicking the file to view its tags, or clicking the bottom bar menu, and click tags to then input BLUE, SQUARE, and 9 into the text box, with a semicolon after each individual tag. With Python, I would need a script that could inject those individual tags into the description properties of the JPEG to make the process less painful if I were to do this iteratively for multiple JPEG files.

I doubt this would require any heavy-handed knowledge of programing with Python, but at the same time the specificity of my issue seems to elude an easy resolution. I can't seem to find a semi-clear or straightforward answer, as I'm a bit of a greenhorn when it comes to programing with python in general.

Any help would be very, very useful. I am using Python 3.5.2. by the way.

答:
So, here is my revised answer.
So, all info in a jpg is metadata stored with an "id" number so for instance 0th is the discription area you are looking for heres a table.

```<code>0th:
283 = (720000, 10000)
296 = 2
34665 = 11444
306 = b'2011:08:22 21:39:05'
270 = b''
271 = b'OLYMPUS IMAGING CORP.'
272 = b'E-P1'
305 = b'Adobe Photoshop CS5 Windows'
274 = 1
33432 = b'Robin Parmar'
282 = (720000, 10000)
315 = b'Robin Parmar'
</code>```

source http://www.theatreofnoise.com/2016/10/how-to-retrieve-photo-metadata-in-python.html

So to change like the subject all you need to do is...

```<code>pip install piexif
</code>```

This works with 2.7 & 3

```<code>import piexif

def insert_sample():
    zeroth_ifd = {270: "test"}
    exif_bytes = piexif.dump({"0th":zeroth_ifd})
    piexif.insert(exif_bytes,'img.jpg')

insert_sample()
</code>```

Hope this helps :D
 Heres a list of all the ids

```<code><< Inspect piexif >>

11 = ProcessingSoftware
18246 = Rating
18249 = RatingPercent
254 = NewSubfileType
255 = SubfileType
256 = ImageWidth
257 = ImageLength
258 = BitsPerSample
259 = Compression
262 = PhotometricInterpretation
263 = Threshholding
264 = CellWidth
265 = CellLength
266 = FillOrder
269 = DocumentName
270 = ImageDescription
271 = Make
272 = Model
273 = StripOffsets
274 = Orientation
277 = SamplesPerPixel
278 = RowsPerStrip
279 = StripByteCounts
282 = XResolution
283 = YResolution
284 = PlanarConfiguration
290 = GrayResponseUnit
291 = GrayResponseCurve
292 = T4Options
293 = T6Options
296 = ResolutionUnit
301 = TransferFunction
305 = Software
306 = DateTime
315 = Artist
316 = HostComputer
317 = Predictor
318 = WhitePoint
319 = PrimaryChromaticities
320 = ColorMap
321 = HalftoneHints
322 = TileWidth
323 = TileLength
324 = TileOffsets
325 = TileByteCounts
32781 = ImageID
330 = SubIFDs
332 = InkSet
333 = InkNames
334 = NumberOfInks
33421 = CFARepeatPatternDim
33422 = CFAPattern
33423 = BatteryLevel
33432 = Copyright
33434 = ExposureTime
336 = DotRange
337 = TargetPrinter
338 = ExtraSamples
339 = SampleFormat
340 = SMinSampleValue
341 = SMaxSampleValue
342 = TransferRange
343 = ClipPath
34377 = ImageResources
344 = XClipPathUnits
345 = YClipPathUnits
346 = Indexed
34665 = ExifTag
34675 = InterColorProfile
347 = JPEGTables
34853 = GPSTag
34857 = Interlace
34858 = TimeZoneOffset
34859 = SelfTimerMode
351 = OPIProxy
37387 = FlashEnergy
37388 = SpatialFrequencyResponse
37389 = Noise
37390 = FocalPlaneXResolution
37391 = FocalPlaneYResolution
37392 = FocalPlaneResolutionUnit
37393 = ImageNumber
37394 = SecurityClassification
37395 = ImageHistory
37397 = ExposureIndex
37398 = TIFFEPStandardID
37399 = SensingMethod
40091 = XPTitle
40092 = XPComment
40093 = XPAuthor
40094 = XPKeywords
40095 = XPSubject
50341 = PrintImageMatching
50706 = DNGVersion
50707 = DNGBackwardVersion
50708 = UniqueCameraModel
50709 = LocalizedCameraModel
50710 = CFAPlaneColor
50711 = CFALayout
50712 = LinearizationTable
50713 = BlackLevelRepeatDim
50714 = BlackLevel
50715 = BlackLevelDeltaH
50716 = BlackLevelDeltaV
50717 = WhiteLevel
50718 = DefaultScale
50719 = DefaultCropOrigin
50720 = DefaultCropSize
50721 = ColorMatrix1
50722 = ColorMatrix2
50723 = CameraCalibration1
50724 = CameraCalibration2
50725 = ReductionMatrix1
50726 = ReductionMatrix2
50727 = AnalogBalance
50728 = AsShotNeutral
50729 = AsShotWhiteXY
50730 = BaselineExposure
50731 = BaselineNoise
50732 = BaselineSharpness
50733 = BayerGreenSplit
50734 = LinearResponseLimit
50735 = CameraSerialNumber
50736 = LensInfo
50737 = ChromaBlurRadius
50738 = AntiAliasStrength
50739 = ShadowScale
50740 = DNGPrivateData
50741 = MakerNoteSafety
50778 = CalibrationIlluminant1
50779 = CalibrationIlluminant2
50780 = BestQualityScale
50781 = RawDataUniqueID
50827 = OriginalRawFileName
50828 = OriginalRawFileData
50829 = ActiveArea
50830 = MaskedAreas
50831 = AsShotICCProfile
50832 = AsShotPreProfileMatrix
50833 = CurrentICCProfile
50834 = CurrentPreProfileMatrix
50879 = ColorimetricReference
50931 = CameraCalibrationSignature
50932 = ProfileCalibrationSignature
50934 = AsShotProfileName
50935 = NoiseReductionApplied
50936 = ProfileName
50937 = ProfileHueSatMapDims
50938 = ProfileHueSatMapData1
50939 = ProfileHueSatMapData2
50940 = ProfileToneCurve
50941 = ProfileEmbedPolicy
50942 = ProfileCopyright
50964 = ForwardMatrix1
50965 = ForwardMatrix2
50966 = PreviewApplicationName
50967 = PreviewApplicationVersion
50968 = PreviewSettingsName
50969 = PreviewSettingsDigest
50970 = PreviewColorSpace
50971 = PreviewDateTime
50972 = RawImageDigest
50973 = OriginalRawFileDigest
50974 = SubTileBlockSize
50975 = RowInterleaveFactor
50981 = ProfileLookTableDims
50982 = ProfileLookTableData
51008 = OpcodeList1
51009 = OpcodeList2
51022 = OpcodeList3
51041 = NoiseProfile
512 = JPEGProc
513 = JPEGInterchangeFormat
514 = JPEGInterchangeFormatLength
515 = JPEGRestartInterval
517 = JPEGLosslessPredictors
518 = JPEGPointTransforms
519 = JPEGQTables
520 = JPEGDCTables
521 = JPEGACTables
529 = YCbCrCoefficients
530 = YCbCrSubSampling
531 = YCbCrPositioning
532 = ReferenceBlackWhite
60606 = ZZZTestSlong1
60607 = ZZZTestSlong2
700 = XMLPacket
</code>```

Body:
So, here is my revised answer.
So, all info in a jpg is metadata stored with an "id" number so for instance 0th is the discription area you are looking for heres a table.

0th:
283 = (720000, 10000)
296 = 2
34665 = 11444
306 = b'2011:08:22 21:39:05'
270 = b''
271 = b'OLYMPUS IMAGING CORP.'
272 = b'E-P1'
305 = b'Adobe Photoshop CS5 Windows'
274 = 1
33432 = b'Robin Parmar'
282 = (720000, 10000)
315 = b'Robin Parmar'

source http://www.theatreofnoise.com/2016/10/how-to-retrieve-photo-metadata-in-python.html

So to change like the subject all you need to do is...

pip install piexif

This works with 2.7 & 3

import piexif

def insert_sample():
    zeroth_ifd = {270: "test"}
    exif_bytes = piexif.dump({"0th":zeroth_ifd})
    piexif.insert(exif_bytes,'img.jpg')

insert_sample()

Hope this helps :D
 Heres a list of all the ids

<< Inspect piexif >>

11 = ProcessingSoftware
18246 = Rating
18249 = RatingPercent
254 = NewSubfileType
255 = SubfileType
256 = ImageWidth
257 = ImageLength
258 = BitsPerSample
259 = Compression
262 = PhotometricInterpretation
263 = Threshholding
264 = CellWidth
265 = CellLength
266 = FillOrder
269 = DocumentName
270 = ImageDescription
271 = Make
272 = Model
273 = StripOffsets
274 = Orientation
277 = SamplesPerPixel
278 = RowsPerStrip
279 = StripByteCounts
282 = XResolution
283 = YResolution
284 = PlanarConfiguration
290 = GrayResponseUnit
291 = GrayResponseCurve
292 = T4Options
293 = T6Options
296 = ResolutionUnit
301 = TransferFunction
305 = Software
306 = DateTime
315 = Artist
316 = HostComputer
317 = Predictor
318 = WhitePoint
319 = PrimaryChromaticities
320 = ColorMap
321 = HalftoneHints
322 = TileWidth
323 = TileLength
324 = TileOffsets
325 = TileByteCounts
32781 = ImageID
330 = SubIFDs
332 = InkSet
333 = InkNames
334 = NumberOfInks
33421 = CFARepeatPatternDim
33422 = CFAPattern
33423 = BatteryLevel
33432 = Copyright
33434 = ExposureTime
336 = DotRange
337 = TargetPrinter
338 = ExtraSamples
339 = SampleFormat
340 = SMinSampleValue
341 = SMaxSampleValue
342 = TransferRange
343 = ClipPath
34377 = ImageResources
344 = XClipPathUnits
345 = YClipPathUnits
346 = Indexed
34665 = ExifTag
34675 = InterColorProfile
347 = JPEGTables
34853 = GPSTag
34857 = Interlace
34858 = TimeZoneOffset
34859 = SelfTimerMode
351 = OPIProxy
37387 = FlashEnergy
37388 = SpatialFrequencyResponse
37389 = Noise
37390 = FocalPlaneXResolution
37391 = FocalPlaneYResolution
37392 = FocalPlaneResolutionUnit
37393 = ImageNumber
37394 = SecurityClassification
37395 = ImageHistory
37397 = ExposureIndex
37398 = TIFFEPStandardID
37399 = SensingMethod
40091 = XPTitle
40092 = XPComment
40093 = XPAuthor
40094 = XPKeywords
40095 = XPSubject
50341 = PrintImageMatching
50706 = DNGVersion
50707 = DNGBackwardVersion
50708 = UniqueCameraModel
50709 = LocalizedCameraModel
50710 = CFAPlaneColor
50711 = CFALayout
50712 = LinearizationTable
50713 = BlackLevelRepeatDim
50714 = BlackLevel
50715 = BlackLevelDeltaH
50716 = BlackLevelDeltaV
50717 = WhiteLevel
50718 = DefaultScale
50719 = DefaultCropOrigin
50720 = DefaultCropSize
50721 = ColorMatrix1
50722 = ColorMatrix2
50723 = CameraCalibration1
50724 = CameraCalibration2
50725 = ReductionMatrix1
50726 = ReductionMatrix2
50727 = AnalogBalance
50728 = AsShotNeutral
50729 = AsShotWhiteXY
50730 = BaselineExposure
50731 = BaselineNoise
50732 = BaselineSharpness
50733 = BayerGreenSplit
50734 = LinearResponseLimit
50735 = CameraSerialNumber
50736 = LensInfo
50737 = ChromaBlurRadius
50738 = AntiAliasStrength
50739 = ShadowScale
50740 = DNGPrivateData
50741 = MakerNoteSafety
50778 = CalibrationIlluminant1
50779 = CalibrationIlluminant2
50780 = BestQualityScale
50781 = RawDataUniqueID
50827 = OriginalRawFileName
50828 = OriginalRawFileData
50829 = ActiveArea
50830 = MaskedAreas
50831 = AsShotICCProfile
50832 = AsShotPreProfileMatrix
50833 = CurrentICCProfile
50834 = CurrentPreProfileMatrix
50879 = ColorimetricReference
50931 = CameraCalibrationSignature
50932 = ProfileCalibrationSignature
50934 = AsShotProfileName
50935 = NoiseReductionApplied
50936 = ProfileName
50937 = ProfileHueSatMapDims
50938 = ProfileHueSatMapData1
50939 = ProfileHueSatMapData2
50940 = ProfileToneCurve
50941 = ProfileEmbedPolicy
50942 = ProfileCopyright
50964 = ForwardMatrix1
50965 = ForwardMatrix2
50966 = PreviewApplicationName
50967 = PreviewApplicationVersion
50968 = PreviewSettingsName
50969 = PreviewSettingsDigest
50970 = PreviewColorSpace
50971 = PreviewDateTime
50972 = RawImageDigest
50973 = OriginalRawFileDigest
50974 = SubTileBlockSize
50975 = RowInterleaveFactor
50981 = ProfileLookTableDims
50982 = ProfileLookTableData
51008 = OpcodeList1
51009 = OpcodeList2
51022 = OpcodeList3
51041 = NoiseProfile
512 = JPEGProc
513 = JPEGInterchangeFormat
514 = JPEGInterchangeFormatLength
515 = JPEGRestartInterval
517 = JPEGLosslessPredictors
518 = JPEGPointTransforms
519 = JPEGQTables
520 = JPEGDCTables
521 = JPEGACTables
529 = YCbCrCoefficients
530 = YCbCrSubSampling
531 = YCbCrPositioning
532 = ReferenceBlackWhite
60606 = ZZZTestSlong1
60607 = ZZZTestSlong2
700 = XMLPacket


来源: stackexchange

问:
convenient way to take out class members to external class or trait?
In my TestSpec class I have bunch of properties and its starting to be crowded, something like:

```<code>implicit val formats: Formats = DefaultFormats

  val client: WSClient = app.injector.instanceOf[WSClient]
  val env: Environment = app.injector.instanceOf[Environment]
  val config: Configuration = app.configuration
  val j4s: Json4s = app.injector.instanceOf[Json4s]
  val actSys: ActorSystem = app.injector.instanceOf[ActorSystem]
  implicit lazy val materializer: Materializer = app.materializer

  // mocking service
  val myService: ChironApiService = mock[MyService]

  val rawTextModel: String =
    """{"message":"a message","reason":"Done","list":[34,2,12]}"""
  val badResponseModel: ModelOne = JsonMethods.parse(rawTextModel).extract[BadResModel]

  val futureOfEither: Future[Either[String, Int]] = Future(Left("fr"))
.
.
.
</code>```

so I thought taking it out to a trait and add this trait to TestSpec and then I can access the info, is there a more elegant scala way to do something like this?

thanks

答:
You can try something like</p>

```<code>trait TestConfig {
    val client: WSClient = app.injector.instanceOf[WSClient]
    val env: Environment = app.injector.instanceOf[Environment]
    val config: Configuration = app.configuration
    val j4s: Json4s = app.injector.instanceOf[Json4s]
    val actSys: ActorSystem = app.injector.instanceOf[ActorSystem]
    implicit lazy val materializer: Materializer = app.materializer
 }

 class TestSpec extends TestConfig {
    // mocking service
    val myService: ChironApiService = mock[MyService]

    val rawTextModel: String =
        """{"message":"a message","reason":"Done","list":[34,2,12]}"""
    val badResponseModel: ModelOne = JsonMethods.parse(rawTextModel).extract[BadResModel]

    val futureOfEither: Future[Either[String, Int]] = Future(Left("fr"))
    .
    .
    .
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my TestSpec class I have bunch of properties and its starting to be crowded, something like:

implicit val formats: Formats = DefaultFormats

  val client: WSClient = app.injector.instanceOf[WSClient]
  val env: Environment = app.injector.instanceOf[Environment]
  val config: Configuration = app.configuration
  val j4s: Json4s = app.injector.instanceOf[Json4s]
  val actSys: ActorSystem = app.injector.instanceOf[ActorSystem]
  implicit lazy val materializer: Materializer = app.materializer

  // mocking service
  val myService: ChironApiService = mock[MyService]

  val rawTextModel: String =
    """{"message":"a message","reason":"Done","list":[34,2,12]}"""
  val badResponseModel: ModelOne = JsonMethods.parse(rawTextModel).extract[BadResModel]

  val futureOfEither: Future[Either[String, Int]] = Future(Left("fr"))
.
.
.

so I thought taking it out to a trait and add this trait to TestSpec and then I can access the info, is there a more elegant scala way to do something like this?

thanks

Body:
You can try something like

trait TestConfig {
    val client: WSClient = app.injector.instanceOf[WSClient]
    val env: Environment = app.injector.instanceOf[Environment]
    val config: Configuration = app.configuration
    val j4s: Json4s = app.injector.instanceOf[Json4s]
    val actSys: ActorSystem = app.injector.instanceOf[ActorSystem]
    implicit lazy val materializer: Materializer = app.materializer
 }

 class TestSpec extends TestConfig {
    // mocking service
    val myService: ChironApiService = mock[MyService]

    val rawTextModel: String =
        """{"message":"a message","reason":"Done","list":[34,2,12]}"""
    val badResponseModel: ModelOne = JsonMethods.parse(rawTextModel).extract[BadResModel]

    val futureOfEither: Future[Either[String, Int]] = Future(Left("fr"))
    .
    .
    .
 }


问:
Cannot ssh into EC2 instance. Operation timed out
1The security group allows SSH at port 22 Inbound Rule

This is the first time I've had this problem. I logged in from a friend's AWS account to one of his instances and it connects. so the problem isn't at my end.

Here's the debug log:

```<code>OpenSSH_7.2p2, LibreSSL 2.4.1
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 20: Applying options for *
debug2: resolving "ec2-54-215-233-245.us-west-1.compute.amazonaws.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to ec2-54-215-233-245.us-west-1.compute.amazonaws.com [54.215.233.245] port 22.
</code>```

I followed AWS's troubleshooting guide and even that didn't work. Any idea what's wrong?

答: It's probably due to your key.pem's permission not securely set.  You might want to try set it to 0400 or 0600 (e.g. sudo chmod 400 key.pem).

Body:
1The security group allows SSH at port 22 Inbound Rule

This is the first time I've had this problem. I logged in from a friend's AWS account to one of his instances and it connects. so the problem isn't at my end.

Here's the debug log:

OpenSSH_7.2p2, LibreSSL 2.4.1
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 20: Applying options for *
debug2: resolving "ec2-54-215-233-245.us-west-1.compute.amazonaws.com" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to ec2-54-215-233-245.us-west-1.compute.amazonaws.com [54.215.233.245] port 22.

I followed AWS's troubleshooting guide and even that didn't work. Any idea what's wrong?


问:
PowerShell random file generator too slow
Trying to generate random files in Windows with this PowerShell script:

```<code>param([string]$path = "C:\temp", [int]$size = "1024", [long]$number= "1000")
Write-Host "Path: $path"
Write-Host "Size of file: $size"
Write-Host "Number of files: $number"

Write-Host "Started at:"
Get-Date -Format HH:mm:ss

md -Force $path |out-null

$script:StartTime = $(Get-Date)
for($i=0; $i -le $number - 1 ; $i++){
    [Byte[]]$out=@(); 0..($size-1) | %{$out += Get-Random -Minimum 0 -Maximum 255};
    [System.IO.File]::WriteAll("$path\$i.bin",$out)
    if (-Not ($i % 100) -and ($i -ne 0 )) {
        Write-Host "$i were created"
        $elapsedTime = $(Get-Date) - $script:StartTime
        $script:StartTime = $(Get-Date)
        Write-Host "$elapsedTime"
    }
}
</code>```

When I want to increase filesize from 1KB to 1MB, it take a long time for even one file, but I need thousands of those. Is there way to solve this bottleneck?

答:
```<code>Function New-RandomFile {
    Param(
        $Path = '.',
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )
    (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubString(1, 126) }) | set-content "$Path\$FileName"
}
</code>```

This took 491 milliseconds to generate a 1mb file. Running:

```<code>New-RandomFile -FileSize 1mb
</code>```

UPDATE:

I've updated my function to use a ScriptBlock, so you can replace the 'NewGuid()' method with anything you want.

In this scenario, I make 1kb chunks, since I know I'm never creating smaller files. This improved the speed of my function drastically!

Set-Content forces a NewLine at the end, which is why you need to remove 2 Characters each time you write to file. I've replaced it with [io.file]::WriteAllText() instead.

```<code>Function New-RandomFile_1kChunks {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }

    $Chunks = [math]::Ceiling($FileSize/1kb)

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}
</code>```

If you dont care that all chunks are random, you can simply Invoke() the generation of the 1kb chunk once.. this improves the speed drastically, but won't make the entire file random.

```<code>Function New-RandomFile_Fast {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }
    $Chunks = [math]::Ceiling($FileSize/1kb)
    $ChunkString = $Chunk.Invoke()

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkString }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}
</code>```

Measure-Command all these changes to generate a 10mb file:

Executing New-RandomFile: 35.7688241 seconds.

Executing New-RandomFile_1kChunks: 25.1463777 seconds.

Executing New-RandomFile_Fast: 1.1626236 seconds.

Body:
Trying to generate random files in Windows with this PowerShell script:

param([string]$path = "C:\temp", [int]$size = "1024", [long]$number= "1000")
Write-Host "Path: $path"
Write-Host "Size of file: $size"
Write-Host "Number of files: $number"

Write-Host "Started at:"
Get-Date -Format HH:mm:ss

md -Force $path |out-null

$script:StartTime = $(Get-Date)
for($i=0; $i -le $number - 1 ; $i++){
    [Byte[]]$out=@(); 0..($size-1) | %{$out += Get-Random -Minimum 0 -Maximum 255};
    [System.IO.File]::WriteAll("$path\$i.bin",$out)
    if (-Not ($i % 100) -and ($i -ne 0 )) {
        Write-Host "$i were created"
        $elapsedTime = $(Get-Date) - $script:StartTime
        $script:StartTime = $(Get-Date)
        Write-Host "$elapsedTime"
    }
}

When I want to increase filesize from 1KB to 1MB, it take a long time for even one file, but I need thousands of those. Is there way to solve this bottleneck?

Body:
Function New-RandomFile {
    Param(
        $Path = '.',
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )
    (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubString(1, 126) }) | set-content "$Path\$FileName"
}

This took 491 milliseconds to generate a 1mb file. Running:

New-RandomFile -FileSize 1mb

UPDATE:

I've updated my function to use a ScriptBlock, so you can replace the 'NewGuid()' method with anything you want.

In this scenario, I make 1kb chunks, since I know I'm never creating smaller files. This improved the speed of my function drastically!

Set-Content forces a NewLine at the end, which is why you need to remove 2 Characters each time you write to file. I've replaced it with [io.file]::WriteAllText() instead.

Function New-RandomFile_1kChunks {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }

    $Chunks = [math]::Ceiling($FileSize/1kb)

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}

If you dont care that all chunks are random, you can simply Invoke() the generation of the 1kb chunk once.. this improves the speed drastically, but won't make the entire file random.

Function New-RandomFile_Fast {
    Param(
        $Path = (Resolve-Path '.').Path,
        $FileSize = 1kb,
        $FileName = [guid]::NewGuid().Guid + '.txt'
        )

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid +
               [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" }
    $Chunks = [math]::Ceiling($FileSize/1kb)
    $ChunkString = $Chunk.Invoke()

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkString }))")

    Write-Warning "New-RandomFile: $Path\$FileName"

}

Measure-Command all these changes to generate a 10mb file:

Executing New-RandomFile: 35.7688241 seconds.

Executing New-RandomFile_1kChunks: 25.1463777 seconds.

Executing New-RandomFile_Fast: 1.1626236 seconds.


问:
Google Places Api - pass an address with the right encoding
In order to make a Google Places Api call, I use this function:

```<code>def build_URL(search_text='',types_text=''):
    base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
    key_string = '?key=mykey'
    query_string = '&query='+urllib.quote(search_text)
    sensor_string = '&sensor=false'
    type_string = ''
    if types_text!='':
        type_string = '&types='+urllib.quote(types_text)
    url = base_url+key_string+query_string+sensor_string+type_string
    return url
</code>```

but the address I'm passing as an argument has encoding issues:

```<code>   print(build_URL(search_text='R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'))
</code>```

I have tried 'R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'.encode('utf-8'), to no avail. I get the error:

```<code>{
error_message: "Invalid request. One of the input parameters contains a non-UTF-8 string.",
html_attributions: [ ],
results: [ ],
status: "INVALID_REQUEST"
}
</code>```

my script also has #-*- coding: utf-8 -*- at the top.

how do I fix this?

答:
A workaround may be to use the Unidecode package which makes a best-attempt to represent Unicode in ASCII:

```<code>search_text_unicode=u'R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'

search_text_ascii = unidecode(search_text_unicode)
# check the conversion
print(search_text_ascii) # R. Fradique Coutinho, 1332 - Pinheiros, Sao Paulo - SP, 05416-001, Brazil
# got valid ASCII which can be passed to your function
print(build_URL(search_text=search_text_ascii))
</code>```

upon which the returned URL is recognized in the Google Maps API.

Body:
In order to make a Google Places Api call, I use this function:

def build_URL(search_text='',types_text=''):
    base_url = 'https://maps.googleapis.com/maps/api/place/textsearch/json'
    key_string = '?key=mykey'
    query_string = '&query='+urllib.quote(search_text)
    sensor_string = '&sensor=false'
    type_string = ''
    if types_text!='':
        type_string = '&types='+urllib.quote(types_text)
    url = base_url+key_string+query_string+sensor_string+type_string
    return url

but the address I'm passing as an argument has encoding issues:

   print(build_URL(search_text='R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'))

I have tried 'R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'.encode('utf-8'), to no avail. I get the error:

{
error_message: "Invalid request. One of the input parameters contains a non-UTF-8 string.",
html_attributions: [ ],
results: [ ],
status: "INVALID_REQUEST"
}

my script also has #-*- coding: utf-8 -*- at the top.

how do I fix this?

Body:
A workaround may be to use the Unidecode package which makes a best-attempt to represent Unicode in ASCII:

search_text_unicode=u'R. Fradique Coutinho, 1332 - Pinheiros, S\xe3o Paulo - SP, 05416-001, Brazil'

search_text_ascii = unidecode(search_text_unicode)
# check the conversion
print(search_text_ascii) # R. Fradique Coutinho, 1332 - Pinheiros, Sao Paulo - SP, 05416-001, Brazil
# got valid ASCII which can be passed to your function
print(build_URL(search_text=search_text_ascii))

upon which the returned URL is recognized in the Google Maps API.


问:
Nested Navigation List close but not exactly what I had in mind
I'm currently using a nested navigation list for my website.

```<code><header>
    <nav>
        <h1><a href="index.php"><img src="mommyinfologo.png"/></h1>
        <ul class="navMenu">
            <a href="index.php">
                <li class="parentMenu">Home
                    <ul class="sub-menu">
                        <a href="mommymadness.php">
                            <li>This Mommy's Madness</li>
                        </a>
                        <a href="about.php">
                            <li>About Mommy Info</li>
                        </a>
                        <a href="contact.php">
                            <li>Contact Mommy Info</li>
                        </a>
                    </ul>

                </li>
            </a>

            <a href="pregnancysplash.php">
                <li class="parentMenu">Pregnancy
                    <ul class="sub-menu">
                        <a href="ttc.php">
                            <li>Trying To Conceive</li>
                        </a>
                        <a href="fetaldev.php">
                            <li>Fetal Development</li>
                        </a>
                        <a href="genderpredictions.php">
                            <li>Gender Predictions</li>
                        </a>
                        <a href="labordelivery.php">
                            <li>Labor and Delivery</li>
                        </a>
                    </ul>
                </li>
            </a>
            <a href="aabsplash.php">
                <li class="parentMenu">All About Baby
                    <ul class="sub-menu">
                        <a href="advice.php">
                            <li>Advice</li>
                        </a>
                        <a href="guidelines.php">
                            <li>Guidelines</li>
                        </a>
                        <a href="milestones.php">
                            <li>Milestones</li>
                        </a>
                        <a href="learndev.php">
                            <li>Learning Development</li>
                        </a>
                    </ul>
                </li>
            </a>
            <a href="healthsplash.php">
                <li class="parentMenu">Health
                    <ul class="sub-menu">
                        <a href="pregnutrition.php">
                            <li>Pregnancy Nutrition</li>
                        </a>
                        <a href="breastfeeding.php">

                            <li>Breastfeeding</li>
                        </a>
                        <a href="formula.php">
                            <li>Formula Feeding</li>
                        </a>
                        <a href="toddlers.php">
                            <li>Toddlers</li>
                        </a>
                        <a href="preexercise.php">
                            <li>Prenatal Exercise</li>
                        </a>
                        <a href="postexercise.php">
                            <li>Postpartum Exercise</li>
                        </a>
                        <a href="organic.php">
                            <li>Organic DIY Health</li>
                        </a>
                    </ul>
                </li></a>
                <a href="partymommasplash.php">
                    <li class="parentMenu">Party Momma
                        <ul class="sub-menu">
                            <a href="pregann.php">
                                <li>Pregnancy Announcement</li>
                            </a>
                                <a href="genderreveal.php">
                                    <li>Gender Reveal</li>
                                </a>
                            <a href="babyshower.php"><li>Baby Shower</li></a>
                            <a href="birthann.php">  <li>Birth Announcement</li></a>
                            <a href="birthdays.php">    <li>Birthdays</li></a>
                        </ul>
                    </li></a>
            <a href="stationssplash.php"><li class="parentMenu">Stations
                            <ul class="sub-menu">
                                <a href="hospitalbag.php"><li>Hospital Bag</li></a>
                                <a href="diaperbag.php"><li>Diaper Bag</li></a>
                                <a href="changingstation.php">   <li>Changing Station</li></a>
                                <a href="babygear.php"><li>Baby Gear</li></a>
                            </ul>
                    </li></a>
            <a href="memorymarkerssplash.php"><li class="parentMenu">Memory Markers
                            <ul class="sub-menu">
                                <a href="diymemories.php"><li>Do It Yourself</li></a>
                                <a href="purchasable.php"><li>Buy It</li></a>
                            </ul>
                </li></a>
            <a href="reviewsplash.php"><li class="parentMenu">Reviews
                            <ul class="sub-menu">
                                <a href="games.php"> <li>Games</li></a>
                                    <a href="gear.php"><li>Gear</li></a>
                                        <a href="learning.php"><li>Learning</li></a>
                            </ul>
                </li></a>
            <a href="mommymadness.php"><li class="parentMenu">Blog
                    </li></a>

        </ul>
        <?php include_once ("header2.php"); ?>
    </nav>

</header>
</code>```

I'm creating header2.php for the responsive website navigation.

```<code><div id="handle">☰Menu
<ul id="navSmall">
    <li class="parentMenuSmall">Home
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">Pregnancy
        <ul class="sub-menu-small">
            <a href="pregnancysplash.php"><li>Pregnancy</li></a>
            <a href="ttc.php"><li>Trying to Conceive</li></a>
            <a href="about.php"><li>Fetal Development</li></a>
            <a href="contact.php"><li>Gender Predictions</li></a>
            <a href="mommymadness.php"><li>Labor and Delivery</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">All About Baby
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">Health
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">Party Momma
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">Stations
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">Memory Markers
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">Reviews
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
    <li class="parentMenuSmall">Blog
        <ul class="sub-menu-small">
            <a href="index.php"><li>Home</li></a>
            <a href="about.php"><li>About</li></a>
            <a href="contact.php"><li>Contact</li></a>
            <a href="mommymadness.php"><li>Mommy Madness</li></a>
        </ul>
    </li>
</ul>

</div>
</code>```

My current CSS:

```<code>body {
    color:#ADD8E6;
    background-image:url(backgroundarrows.png);
    font-family:"Monotype Corsiva", sans-serif;
    margin:0;
    padding:0;
}
/* Global */
ul{
    list-style-type: none;
    margin: 0;
    padding: 0;
}

a{
    text-decoration: none;
    color:#737597;
;
}

.section {
    background-color:#fafbff;
    border:thin solid #D3D3D3;
    border-radius:10px;
    box-shadow:lightgray;
    color:#696969;
    display:inline;
    float:left;
    width:63%;
    margin:0 1% 1%;
    padding:5px 8px;
}

.section h2 {
    border-bottom:solid medium #90cdd0;
    color:#90cdd0;
    text-align:center;
}

#about {
    color:dimgrey;
    float:right;
    font-size:medium;
    margin:1% 1% 0;
    text-align:center;
    width:30%;
}

.nav li {
    text-align:left;
    font-size:large;
    padding:1%;
}

.nav a {
    text-decoration:none;
    color:darkgrey;
}

#home {
    margin:1% 0 1% 1%;
}

#home div {
    font-size:20px;
    line-height:30px;
    padding:1% 3%;
    text-align:center;
}

#home div p{
    font-family:"Times New Roman", serif;
    font-size:20px;
    line-height: 30px;
    text-align:left;
}

.hide {
    display: none;
}

/* Header */
header {
    background-color:#cff1ff;
    height:60px;
    padding:5px 0;
}

header h1 {
    color:#809dc6;
    display:inline;
    font-family:"Monotype Corsiva", sans-serif;
    font-size:45px;
    height:50px;
    padding:5px 15px;
}

/*Website Navigation */
.navMenu {
    display:inline;
    font-size:20px;
}

.navMenu .parentMenu {
    background-color:#cff1ff;
    display:inline-block;
    padding:5px 10px;
    position:relative;
    z-index:100000;
}

.navMenu .parentMenu:hover{
    background-color:#bfd3ee;
}

.navMenu .parentMenu a{
    color:#737597;
}

.navMenu .parentMenu:hover a:hover{
    color:#87a2be;
}

.navMenu .parentMenu .sub-menu{
    display:none;
    left:0;
    padding:0;
    position:absolute;
    top:33px;
    width:180px;
    z-index:10000;
}

.navMenu .parentMenu:hover .sub-menu{
    display:block;
    white-space:nowrap;
}

.navMenu .parentMenu:hover .sub-menu li{
    background-color:#bfd3ee;
    font-size:17px;
    padding:10px;
    text-align:left;
    white-space:nowrap;
    width:100%;
    z-index:10000;
}

.navMenu .parentMenu .sub-menu li:hover{
    background-color:#9ac9ed;
}

#handle{
    font-size: 20px;
    display: none;
    color: #87a2be;
    float: left;
    width: 100%;
    text-align: left;
}

#navSmall {
    display: none;
    text-align: center;
    background-color: #cff1ff;
    z-index: 10000000;
    height: 25px;
}

#handle:hover #navSmall {
    display: inline;
}

.sub-menu-small{
    display: none;
    background-color: #9ac9ed;
}

.sub-menu-small li {
    border-bottom: solid thin #809dc6;
    padding:1px 3px;
}

#navSmall .parentMenuSmall {
    background-color: inherit;
    text-align: left;
    padding: 15px;
    border-bottom: solid thin #809dc6;
    font-size: 18px;
}
#navSmall .parentMenuSmall:hover .sub-menu-small {
    display: inline-block;
    margin-left: 25px;
}
#construct {
    width: 100%;
    height: 100%;
    margin-top: 100px;
    border-radius: 20%;
}
/* Media Queries */
/*tablet*/
/*remove floats */
@media(max-width: 768px) {
    body{
        width: 100%;
    }
    header {
        float: none;
        text-align: center;
        width: 100%;
        height: 90px;
    }

    .section{
        width: 95%;
    }

    #about{
        display: none;
    }

    #handle{
        display: block;
    }

    .navMenu {
        display: none;
    }

}
</code>```

I want my .sub-menu-small to show to the left outside of my .parentMenuSmall items. Right now it's inside the .parentMenuSmall list items and it pushes all of the other .parentMenuSmall items down. Do I need to pull it out of the list items, if so how do I make it work like it does?

答:
Im really worried , why you do not use a responsive framework like getbootstrap

It's one minute job to create responsive navigation as same as your site behavior
you may need to include bootstrap css and js to your site and add navigation
http://getbootstrap.com/components/#nav as you like that's all

Body:
I'm currently using a nested navigation list for my website.

Home

This Mommy's Madness

About Mommy Info

Contact Mommy Info

Pregnancy

Trying To Conceive

Fetal Development

Gender Predictions

Labor and Delivery

All About Baby

Advice

Guidelines

Milestones

Learning Development

Health

Pregnancy Nutrition

Breastfeeding

Formula Feeding

Toddlers

Prenatal Exercise

Postpartum Exercise

Organic DIY Health

Party Momma

Pregnancy Announcement

Gender Reveal

Baby Shower

Birth Announcement

Birthdays

Stations

Hospital Bag

Diaper Bag

Changing Station

Baby Gear

Memory Markers

Do It Yourself

Buy It

Reviews

Games

Gear

Learning

Blog

        <?php include_once ("header2.php"); ?>

I'm creating header2.php for the responsive website navigation.

☰Menu

Home

Home

About

Contact

Mommy Madness

Pregnancy

Pregnancy

Trying to Conceive

Fetal Development

Gender Predictions

Labor and Delivery

All About Baby

Home

About

Contact

Mommy Madness

Health

Home

About

Contact

Mommy Madness

Party Momma

Home

About

Contact

Mommy Madness

Stations

Home

About

Contact

Mommy Madness

Memory Markers

Home

About

Contact

Mommy Madness

Reviews

Home

About

Contact

Mommy Madness

Blog

Home

About

Contact

Mommy Madness

My current CSS:

body {
    color:#ADD8E6;
    background-image:url(backgroundarrows.png);
    font-family:"Monotype Corsiva", sans-serif;
    margin:0;
    padding:0;
}
/* Global */
ul{
    list-style-type: none;
    margin: 0;
    padding: 0;
}

a{
    text-decoration: none;
    color:#737597;
;
}

.section {
    background-color:#fafbff;
    border:thin solid #D3D3D3;
    border-radius:10px;
    box-shadow:lightgray;
    color:#696969;
    display:inline;
    float:left;
    width:63%;
    margin:0 1% 1%;
    padding:5px 8px;
}

.section h2 {
    border-bottom:solid medium #90cdd0;
    color:#90cdd0;
    text-align:center;
}

#about {
    color:dimgrey;
    float:right;
    font-size:medium;
    margin:1% 1% 0;
    text-align:center;
    width:30%;
}

.nav li {
    text-align:left;
    font-size:large;
    padding:1%;
}

.nav a {
    text-decoration:none;
    color:darkgrey;
}

#home {
    margin:1% 0 1% 1%;
}

#home div {
    font-size:20px;
    line-height:30px;
    padding:1% 3%;
    text-align:center;
}

#home div p{
    font-family:"Times New Roman", serif;
    font-size:20px;
    line-height: 30px;
    text-align:left;
}

.hide {
    display: none;
}

/* Header */
header {
    background-color:#cff1ff;
    height:60px;
    padding:5px 0;
}

header h1 {
    color:#809dc6;
    display:inline;
    font-family:"Monotype Corsiva", sans-serif;
    font-size:45px;
    height:50px;
    padding:5px 15px;
}

/*Website Navigation */
.navMenu {
    display:inline;
    font-size:20px;
}

.navMenu .parentMenu {
    background-color:#cff1ff;
    display:inline-block;
    padding:5px 10px;
    position:relative;
    z-index:100000;
}

.navMenu .parentMenu:hover{
    background-color:#bfd3ee;
}

.navMenu .parentMenu a{
    color:#737597;
}

.navMenu .parentMenu:hover a:hover{
    color:#87a2be;
}

.navMenu .parentMenu .sub-menu{
    display:none;
    left:0;
    padding:0;
    position:absolute;
    top:33px;
    width:180px;
    z-index:10000;
}

.navMenu .parentMenu:hover .sub-menu{
    display:block;
    white-space:nowrap;
}

.navMenu .parentMenu:hover .sub-menu li{
    background-color:#bfd3ee;
    font-size:17px;
    padding:10px;
    text-align:left;
    white-space:nowrap;
    width:100%;
    z-index:10000;
}

.navMenu .parentMenu .sub-menu li:hover{
    background-color:#9ac9ed;
}

#handle{
    font-size: 20px;
    display: none;
    color: #87a2be;
    float: left;
    width: 100%;
    text-align: left;
}

#navSmall {
    display: none;
    text-align: center;
    background-color: #cff1ff;
    z-index: 10000000;
    height: 25px;
}

#handle:hover #navSmall {
    display: inline;
}

.sub-menu-small{
    display: none;
    background-color: #9ac9ed;
}

.sub-menu-small li {
    border-bottom: solid thin #809dc6;
    padding:1px 3px;
}

#navSmall .parentMenuSmall {
    background-color: inherit;
    text-align: left;
    padding: 15px;
    border-bottom: solid thin #809dc6;
    font-size: 18px;
}
#navSmall .parentMenuSmall:hover .sub-menu-small {
    display: inline-block;
    margin-left: 25px;
}
#construct {
    width: 100%;
    height: 100%;
    margin-top: 100px;
    border-radius: 20%;
}
/* Media Queries */
/*tablet*/
/*remove floats */
@media(max-width: 768px) {
    body{
        width: 100%;
    }
    header {
        float: none;
        text-align: center;
        width: 100%;
        height: 90px;
    }

    .section{
        width: 95%;
    }

    #about{
        display: none;
    }

    #handle{
        display: block;
    }

    .navMenu {
        display: none;
    }

}

I want my .sub-menu-small to show to the left outside of my .parentMenuSmall items. Right now it's inside the .parentMenuSmall list items and it pushes all of the other .parentMenuSmall items down. Do I need to pull it out of the list items, if so how do I make it work like it does?


问:
How to display message Toast when opening App Android
I am doing reverse engineering in an App to translate it to my local language I would like to display a Toast message to be displayed when you open the App on Android

Example Toast text "translated by Crypton" <<< I want to put this message on Toast

答:
XML file:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/custom_toast_container"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="8dp"
        android:background="#DAAA"
        >

    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
</code>```

Java file:

```<code>import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String str="Welcome TO MSIT";enter code here
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
    }
}
</code>```

Body:
XML file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/custom_toast_container"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="8dp"
        android:background="#DAAA"
        >

    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#FFF"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>

Java file:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String str="Welcome TO MSIT";enter code here
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
    }
}


问:
sumOfTwo Time Limit Exceeded CodeFights Interview Practice
I am attempting the sumOFTwo challenge on CodeFights.com but I unfortuantly cannot complete it to view the solution. All my tests suceedd until the 15th hidden test and it says it exceeds the time limit.

The challenge is - You have two integer arrays, a and b, and an integer target value v. Determine whether there is a pair of numbers, where one number is taken from a and the other from b, that can be added together to get a sum of v. Return true if such a pair exists, otherwise return false.

My code is -

```<code>def sumOfTwo(a,b,v):
    a.sort()
    b.sort()

    if(0 in a and v in b):
        return True
    elif(v in a and 0 in b):
        return True
    else:
        for i in a:
            for j in b:
                if(i + j == v):
                    return True
    return False
</code>```

I know it could be shrunken down to about 6 lines of code, but I kept adding in lines that could help the code possibly finish quicker. Are there any other optimizations I am missing.

答:
This is what I have. It passes all the tests, hidden included, but it takes too long on four of the hidden tests.

```<code>def sumOfTwo(a, b, v):
  for i in a:
    if((v-i) in b):
      return True
  return False
</code>```

@niemmi's answer passes the time limit portion. I didn't know sets were faster than arrays/lists. Thanks, good to know. If I add b=set(b) before the for loop, it passes.

Body:
I am attempting the sumOFTwo challenge on CodeFights.com but I unfortuantly cannot complete it to view the solution. All my tests suceedd until the 15th hidden test and it says it exceeds the time limit.

The challenge is - You have two integer arrays, a and b, and an integer target value v. Determine whether there is a pair of numbers, where one number is taken from a and the other from b, that can be added together to get a sum of v. Return true if such a pair exists, otherwise return false.

My code is -

def sumOfTwo(a,b,v):
    a.sort()
    b.sort()

    if(0 in a and v in b):
        return True
    elif(v in a and 0 in b):
        return True
    else:
        for i in a:
            for j in b:
                if(i + j == v):
                    return True
    return False

I know it could be shrunken down to about 6 lines of code, but I kept adding in lines that could help the code possibly finish quicker. Are there any other optimizations I am missing.

Body:
This is what I have. It passes all the tests, hidden included, but it takes too long on four of the hidden tests.

def sumOfTwo(a, b, v):
  for i in a:
    if((v-i) in b):
      return True
  return False

@niemmi's answer passes the time limit portion. I didn't know sets were faster than arrays/lists. Thanks, good to know. If I add b=set(b) before the for loop, it passes.


问:
Pointer static method that points to no static method
I've been trying to make a pointer function that points to a method doing something like this(visual C++):

```<code>struct test
{
  int tst(int a)
  {
    return a * 4;
  }
};
// ok, this the visual C++ compiler does not accept it... (mingw accept it)

int(*tstptr)(int) = (int(*)(int))&test::tst;
</code>```

Then I've done something like this:

```<code>struct Dx
{
    int SomeMethod()
    {
        return 4;
    }
};

struct Dy
{
    static int(*pSomeMethod)();
};

int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;
</code>```

So far so good, this compiles without problems, but if I try call her:

```<code>Dy::pSomeMethod();
</code>```

The compiler returns me:

Error 1 error LNK2001: external symbol "public: static int (__stdcall
  * Dy::pSomeMethod) (void)" (? PSomeMethod@Dy@@2P6GHXZA) unresolved

which I do not understand, because  it is not suppose pSomeMethod he is not pointing at SomeMethod ?

答:
```<code>int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;
</code>```

Type Checked, so no complain from compiler.

As for:

```<code>Dy::pSomeMethod();
</code>```

This a __cdecl.
But, SomeMethod is a __thiscall, which means it's really like this

```<code>int SomeMethod( Dx &this);
</code>```

So， linker can't find a match.

You simply can't call non-static method without object of class Dx.

Body:
I've been trying to make a pointer function that points to a method doing something like this(visual C++):

struct test
{
  int tst(int a)
  {
    return a * 4;
  }
};
// ok, this the visual C++ compiler does not accept it... (mingw accept it)

int(*tstptr)(int) = (int(*)(int))&test::tst;

Then I've done something like this:

struct Dx
{
    int SomeMethod()
    {
        return 4;
    }
};

struct Dy
{
    static int(*pSomeMethod)();
};

int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;

So far so good, this compiles without problems, but if I try call her:

Dy::pSomeMethod();

The compiler returns me:

Error 1 error LNK2001: external symbol "public: static int (__stdcall
  * Dy::pSomeMethod) (void)" (? PSomeMethod@Dy@@2P6GHXZA) unresolved

which I do not understand, because  it is not suppose pSomeMethod he is not pointing at SomeMethod ?

Body:
int(Dy::*pSomeMethod)() = (int( Dy::*)())&Dx::SomeMethod;

Type Checked, so no complain from compiler.

As for:

Dy::pSomeMethod();

This a __cdecl.
But, SomeMethod is a __thiscall, which means it's really like this

int SomeMethod( Dx &this);

So， linker can't find a match.

You simply can't call non-static method without object of class Dx.


问:
Is there a terminology for 'making a struct inaccessible directly' in C?
I've found a certain code in hostap. The below is a simplified one:

a.h

```<code>// it just declares 'there is a struct a'
struct a;

// it seems like an accessor to a private member b
int get_b(struct a);
</code>```

a.c

```<code>// definition is seprated from a header file
struct a {
    int b;
};

int get_b(struct a) {
    return a.b;
}
</code>```

An object file a.o is generated with these two files.

And if other source codes want to use struct a, it cannot directly access to a member b, with a compiler complaining dereferencing incomplete type. I only can access to a member b with get_b().

First time, I am very frustrated by such a pattern. But finally, I feel that it is very a well-designed pattern if someone wants to protect the integrity of struct a (e.g., values of memebers must be set in certain criteria, or members are dependent to each other so that change of one member will affect the others)

Is there a terminology for this kind of pattern?

答:
This is referred to as an opaque type.  You know that a particular struct exists, but nothing else.

Because you know nothing about the contents of an opaque struct, you can't create an instance if it.  You can however create a pointer to it.

The example you give won't work because you would need to pass an instance of struct a to get_b, and you can't create an instance of struct a.  But if the function takes a pointer, you can do this:

```<code>int get_b(struct a *sa)
{
    return sa->b;
}
</code>```

You'd also need a constructor-like function to create an instance, since an external module would be unable to do so:

```<code>struct a *create(int b)
{
    struct a *tmp = malloc(sizeof(struct a));
    tmp->b = b;
    return tmp;
}
</code>```

Then your header would contain:

```<code>struct a;

int get_b(struct a *);
struct a *create(int);
</code>```

Body:
I've found a certain code in hostap. The below is a simplified one:

a.h

// it just declares 'there is a struct a'
struct a;

// it seems like an accessor to a private member b
int get_b(struct a);

a.c

// definition is seprated from a header file
struct a {
    int b;
};

int get_b(struct a) {
    return a.b;
}

An object file a.o is generated with these two files.

And if other source codes want to use struct a, it cannot directly access to a member b, with a compiler complaining dereferencing incomplete type. I only can access to a member b with get_b().

First time, I am very frustrated by such a pattern. But finally, I feel that it is very a well-designed pattern if someone wants to protect the integrity of struct a (e.g., values of memebers must be set in certain criteria, or members are dependent to each other so that change of one member will affect the others)

Is there a terminology for this kind of pattern?

Body:
This is referred to as an opaque type.  You know that a particular struct exists, but nothing else.

Because you know nothing about the contents of an opaque struct, you can't create an instance if it.  You can however create a pointer to it.

The example you give won't work because you would need to pass an instance of struct a to get_b, and you can't create an instance of struct a.  But if the function takes a pointer, you can do this:

int get_b(struct a *sa)
{
    return sa->b;
}

You'd also need a constructor-like function to create an instance, since an external module would be unable to do so:

struct a *create(int b)
{
    struct a *tmp = malloc(sizeof(struct a));
    tmp->b = b;
    return tmp;
}

Then your header would contain:

struct a;

int get_b(struct a *);
struct a *create(int);


问:
Which Newsletter popup Component is best for joomla?
I am looking a Newsletter component for free but it should have Popup module please suggest me.</p>

答:
AcyMailing

Everyones needs are different but the answer to "Which Newsletter Component is best for Joomla?" is usually AcyMailing. AcyMailing Starter is free and basic features are included. The commercial versions add additional features such as spam testing, bounce back handling, additional third party integrations and so on.

The AcyMailing subscribe module can be popup enabled using a free or paid popup extension (see below).

Other Free Solutions

jNews and BwPostman are other free full newsletter solutions including newsletter subscription modules similar to AcyMailing but these solutions also need an additional module to implement the modules as popups (see below).

Newsletter Subscriber and SJ Newsletter Popup are simpler newsletter  subscription modules but Newsletter Subscriber needs an additional module to implement the module as popups (see below).

Paid Popup Extensions

aikon Magic Popup is not free but is inexpensive and has some excellent features such as load delay and exit triggers that aren't necessarily found in the free popup extensions.

Free Popup Extensions

Engage Box

Auto onPageLoad Popup

Other Ideas

For other ideas and the latest information, search the Joomla Extensions Directory.


问:
Substitute variable name in a dynamic json property
I would like to use the variable settingName for the dynamic json property. How can i accomplish that?

```<code>let settingName = 'LaunchNext';

DSEvents
| where  Timestamp > ago(1d) and Data contains (settingName)
| summarize count() by tostring(parsejson(tostring(Data.Settings)).LaunchNext.value)
</code>```

I want to substitute the variable instead of the actual property

parsejson(tostring(Data.Settings)).LaunchNext.value

答:
Enclosing the variable in [] worked for me

```<code>tostring(parsejson(tostring(Data.Settings)).[settingName].value)
</code>```

Body:
I would like to use the variable settingName for the dynamic json property. How can i accomplish that?

let settingName = 'LaunchNext';

DSEvents
| where  Timestamp > ago(1d) and Data contains (settingName)
| summarize count() by tostring(parsejson(tostring(Data.Settings)).LaunchNext.value)

I want to substitute the variable instead of the actual property

parsejson(tostring(Data.Settings)).LaunchNext.value

Body:
Enclosing the variable in [] worked for me

tostring(parsejson(tostring(Data.Settings)).[settingName].value)


问:
How to print string by awk in special format?
it's that able to convert following string

```
3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00
```

to format string like below

```
3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00
```

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

答:
awk to the rescue!

```<code>awk -F, -v OFS=, '{$1=sprintf("%.15f",$1)}1' file | sed 's/,/ /3g'

3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00
</code>```

sed (gnu) is to replace , with spaces, to do that in awk you have to specify all the fields with delimiters in place (e.g. not set OFS and print $1 "," $2 "," $3,$4,$5 etc).

Body:
it's that able to convert following string

3.840527449999989,6A3,06,67,07,DF,0D,63,81,AA
4.306243875,601,02,3E,80,00,00,00,00,00

to format string like below

3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00

Note that:

timestamps should postfix 0 if necessary

data bytes should remove , between them

Body:
awk to the rescue!

awk -F, -v OFS=, '{$1=sprintf("%.15f",$1)}1' file | sed 's/,/ /3g'

3.840527449999989,6A3,06 67 07 DF 0D 63 81 AA
4.306243875000000,601,02 3E 80 00 00 00 00 00

sed (gnu) is to replace , with spaces, to do that in awk you have to specify all the fields with delimiters in place (e.g. not set OFS and print $1 "," $2 "," $3,$4,$5 etc).


问:
Getting table name in a trigger in MySQL
is it possible to get table name in a MySQL trigger ? i use trigger to log insert actions on some tables in MySQl and i need the name of the table where the trigger is placed at.

Thanx before :)

答: I would recommend that you put triggers on all the tables that require logging.</p>

ContentLicense: CC BY-SA 2.5


问:
problems between database and website. I can't access my website
I uploaded online all my prestashop website files and database but when I try to open the website I get this error  "Link to database cannot be established: SQLSTATE[28000] [1045] Access denied for user 'lt27mhfc_dkddb'@'localhost' (using password: YES)".

I read somewhere on-line that when you upload the website files and the database the connection between those gets lost so I modified the setting.inc.php file changing db_name, db_user, db_password to match my new credentials.

I made a second new user and I choose a second new password and I even tried with those, the strange thing is that the message stays the same instead of saying “…for user newuser@’localhost’…”; like I never changed the user and password the second time.

I am working online with cpanel.

Can anyone help?

答:
Access denied error comes when the user do not have the access privileges set. If you are using cPanel then you can go to Database section and select Database Management and add a user to database and provide all privileges, and then try if it works.

Different websites provide different methods to provide access, try the below one if it could help

For example, if you have a user named “misty” and database named “snowcones”, you would grant misty privileges to the database by doing the following:

Login to cPanel and navigate to the “Databases” section

Click “MySQL Databases”

Scroll down to the section labeled “Add User to Database” Select the
user from the first dropdown menu and the database from the second (in this case, “misty” and “snowcones”)

Click “Add”

Select the privileges you want to grant to the user or select “All
Prvileges” to grant all of them.

Click “Make Changes” to finalize it.

If you ever need to modify privileges for a user already associated with a database, find the section labelled “Current Databases” and click on the username next to the database in question. It will then give you the same privileges page on which you can revoke or grant privileges simply by checking the boxes.

For reference click here


问:
c++ 12bit variable, how can I do this?
I'm building a voxel engine so I have concerns about memory usage, using 12bit instead of 16bit block ids could save a lot of memory. I have a 3D array of block ids, each id has a static configuration.

I'm not sure what a good way to achieve this would be. Is there a way to just get a block of raw memory and manage it myself and would this be a good idea; are there any problems I might run into? Is there a better way to do this?

I have some experience with c++, but most of my time was spent with Java and c#.

Thanks for reading!

答:
Here are some other ideas:

have an 8-bit blockID but have a sectorID for each section, and each section uses it's own "palette" of blockIDs. Basically you could have 128 "common" tiles that can be found anywhere, and 128 zone-specific tiles. This sort of solution can work for many games, especially for mobile platforms, as you can specify a full set of assets and only load in ones referenced in each particular level, according to the "palette" of assets for that level.

And/or an even better idea than scrimping on block types:

use an oct-tree for the blocks. An area that's not differentiated would then only have one BlockID for the entire node. Empty space that's been dug out won't have to have many nodes (whenever a block is changed you check it against the higher level to see if it can be merged), which will make up for extra nodes created as areas are opened up.

The theoretical maximum memory for the oct-tree is a little more than for the solid chunk of blockIDs, but actual usage will have large areas which are in fact solids block types (e.g. the air). And rendering an oct-tree is going to be much faster as you can skip any node of empty space much faster than stepping through all tiles to check whether they're empty.

You can make a wrapper so that the oct-tree is interchangeable with your completely defined 3D array of blockIDs to start with, e.g. you can extract a blockID for any node via a function call. Then add in functions to set blockIDs, do the splitting and merging of the nodes as needed.

Title: c++ 12bit variable, how can I do this?


问:
How to pass variables from client to Express api
I've completely new to node.js and express.
I've done some calculations with javascript on my client page and I want to send that generated array of numbers to my node.js server app.  When I had to send form data I just used form action to my route. Now I'm totally lost and don't know where to start at. What code should I write in my route and how to pass js variable or array to it from my client app?</p>

答:
to send an array of data to the Express app running on your server, the most simple way is to send it as an JSON object. A simple example using jQuery is shown below:

Client code:

```<code>    var your_calculated_array = []; // Set your calculated array here
    $.ajax({
      type: 'POST',
      url: 'YOUR_EXPRESS_ENDPOINT',
      data: { your_data: your_calculated_data },
      dataType: 'json',
      success: function (data) {
        // Handle the response here
      }
    });
</code>```

Server-side code (using body-parser middleware to parse json body):

```<code>.....

var bodyParser = require('body-parser')
app.use( bodyParser.json() );

app.post(YOUR_EXPRESS_ENDPOINT, function(req, res) {
    var calculated_data = req.body.your_data
    // ...
})

.....
</code>```

Body:
to send an array of data to the Express app running on your server, the most simple way is to send it as an JSON object. A simple example using jQuery is shown below:

Client code:

    var your_calculated_array = []; // Set your calculated array here
    $.ajax({
      type: 'POST',
      url: 'YOUR_EXPRESS_ENDPOINT',
      data: { your_data: your_calculated_data },
      dataType: 'json',
      success: function (data) {
        // Handle the response here
      }
    });

Server-side code (using body-parser middleware to parse json body):

.....

var bodyParser = require('body-parser')
app.use( bodyParser.json() );

app.post(YOUR_EXPRESS_ENDPOINT, function(req, res) {
    var calculated_data = req.body.your_data
    // ...
})

.....


问:
Yum install graphicsmagick on rhel server
Any idea how do i install graphicsmagick using yum on rhel 6?
I know the other method of installing i.e by downloading tar file and running make install and so on. However i was wondering if we can install it through package manager like yum, so that it will be easier to un-install if required in future.

Thanks

答:
You need to install the epel repository in order to do this.

Download the latest epel-release rpm from

```<code>http://dl.fedoraproject.org/pub/epel/6/x86_64/
</code>```

Install epel-release rpm:

```<code>rpm -Uvh epel-release*rpm
</code>```

Install GraphicsMagick rpm package:

```<code>yum install GraphicsMagick
</code>```

Body:
You need to install the epel repository in order to do this.

Download the latest epel-release rpm from

http://dl.fedoraproject.org/pub/epel/6/x86_64/

Install epel-release rpm:

rpm -Uvh epel-release*rpm

Install GraphicsMagick rpm package:

yum install GraphicsMagick


问:
Looking for Java wrapper for Windows DirectSound/WASAPI/? audio
After spending quite a bit of time trying to design my way around the existing javax.sound.sampled library for simple (but relatively time-accurate) capture/rendering of audio, I'm concluding that I really need to get to the native audio API. The problem I've found is that I need to be able to get frame position of sound (that I'm rendering by writing to a SourceDataLine) in increments of 20 or 50 milliseconds, accurate to 1 or 2 milliseconds. In other words, I want to synchronize some graphical events to audio that is playing, with a video frame rate of 20 to 50 fps, with jitter no greater than 1 or 2 millseconds. It seems that the JavaSound implementation is too far from the hardware (a price to pay for platform independence?) for this. After much "tinkering" with SDL/TDL buffer sizes, audio formats, size of SDL.write() and TDL.read() buffers, frequency of writing, etc, I can't find a way to avoid the variation in the frame position reported compared to the system clock (at 1 millisecond resolution, not microseconds).

[Further clarification: I could just let the graphical rendering run at a fixed rate based on the system clock, which would be accurate enough for my needs. However, if this is to be synchronized with an audio track, by the time a typical audio track (5 minutes long, for instance) neared the end even small time differences will acccumulate to a noticeable time difference between audio and graphics. I thought to just check for synchronization every second (or 2 or 5), but the "jitter" from the reported audio frame position would result in corrections that would then be noticeable.]

I've been researching what libraries might already be available. It seems many of the existing packages are targeted to support the game development community. However, I don't need 3D audio, hardware acceleration of effects, synthesis, processing - just a way to read the frame position of what is being heard with a consistent latency. If the latency was as much as 100 milliseconds, but consistent, I could design around that.

I would appreciate recommendations for Java libraries providing this type of capability. I presume it will be JNI wrappers of a native audio API. I only need to support Windows7 at this point. I've seen OpenAL (seems to be Creative's "open" way of supporting hardware acceleration of audio since now no longer supported in Vista - game-oriented and more than I need), JSyn (focusing on synthesis, MIDI, not a simple sampled interface) and JAsioHost (most promising so far).

If there are ways around the limitations I've noted with the JavaSound API, that would also be fine, but I've just about given up after a week of effort.

Thanks.

答:
I haven't tried either of these yet, but may be worth looking into:

http://xt-audio.com

And Jitsi has done some work to wrap WASAPI.


问:
How do you reuse the Statement in JDBC after reconnecting to the database?
My JDBC connection to the MySQL database expires after 10 seconds of inactivity. After I reconnect, I can't do any queries, it keeps on asking me if I wanna reconnect as if the connection is still closed.

I have:

 1. a global Statement called st,

 2. a global ResultSet called rs,

 3. a global connection called conn,

 4. a method setConnection that sets up the connection,

 5. a method checkConnection that checks if the connection is alive and if not it calls the setConnection method to establish a new one,

 6. a button that calls checkConnection and if the boolean returned is true, it executes a query

```<code>private Connection conn = null;
private Statement st=null;
private ResultSet rs=null;

    public void setConnection(){
             host="localhost";
             database="test";
             username="testtest";
             password="testtest";
             String url = "jdbc:mysql://" + host + "/" +database+ "";
             try {
                 Class.forName ("com.mysql.jdbc.Driver");
                 conn = DriverManager.getConnection (url, username, password);
                 System.out.println("Succesfuly connected to the database!");

             } catch(Exception e){
                 System.out.println("Failed to connect to the database.");
                 e.printStackTrace();
             }
        }

    private boolean checkConnection(){
            try {
                ResultSet cc = st.executeQuery("SELECT 1");
                return true;
            } catch (SQLException e) {
                int n = JOptionPane.showConfirmDialog(
                        frame,
                        "The connection was closed, reconnect?",
                        "Database security measure",
                        JOptionPane.YES_NO_OPTION);
                if(n == JOptionPane.YES_OPTION){
                    try {
                        conn.close();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                      setConnection();
                    } else if ( n == JOptionPane.NO_OPTION){
                        frame.setVisible(false);
                        new LoginWindowB();
                    }
                return false;
            }
        }
    btn1.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    if(checkConnection()){
                        try {
                            rs = st.executeQuery("SELECT * FROM " + selectedTable);
                            loadData(rs);

                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    } else {

                    }
                }
            });
</code>```

How can I handle this reconnect matter and why do the query not work after setting up a new connection?

答:
I don't see where you initialize st in your example, but it smells like the culprit. When you create a new connection, you have to create a new statement as well.

All the PreparedStatement are attached to a client and will be closed with the connection.

It may be easier to use a Connection Pool manager library.

Body:
My JDBC connection to the MySQL database expires after 10 seconds of inactivity. After I reconnect, I can't do any queries, it keeps on asking me if I wanna reconnect as if the connection is still closed.

I have:

 1. a global Statement called st,

 2. a global ResultSet called rs,

 3. a global connection called conn,

 4. a method setConnection that sets up the connection,

 5. a method checkConnection that checks if the connection is alive and if not it calls the setConnection method to establish a new one,

 6. a button that calls checkConnection and if the boolean returned is true, it executes a query

private Connection conn = null;
private Statement st=null;
private ResultSet rs=null;

    public void setConnection(){
             host="localhost";
             database="test";
             username="testtest";
             password="testtest";
             String url = "jdbc:mysql://" + host + "/" +database+ "";
             try {
                 Class.forName ("com.mysql.jdbc.Driver");
                 conn = DriverManager.getConnection (url, username, password);
                 System.out.println("Succesfuly connected to the database!");

             } catch(Exception e){
                 System.out.println("Failed to connect to the database.");
                 e.printStackTrace();
             }
        }

    private boolean checkConnection(){
            try {
                ResultSet cc = st.executeQuery("SELECT 1");
                return true;
            } catch (SQLException e) {
                int n = JOptionPane.showConfirmDialog(
                        frame,
                        "The connection was closed, reconnect?",
                        "Database security measure",
                        JOptionPane.YES_NO_OPTION);
                if(n == JOptionPane.YES_OPTION){
                    try {
                        conn.close();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                      setConnection();
                    } else if ( n == JOptionPane.NO_OPTION){
                        frame.setVisible(false);
                        new LoginWindowB();
                    }
                return false;
            }
        }
    btn1.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    if(checkConnection()){
                        try {
                            rs = st.executeQuery("SELECT * FROM " + selectedTable);
                            loadData(rs);

                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    } else {

                    }
                }
            });

How can I handle this reconnect matter and why do the query not work after setting up a new connection?


问:
Find the longest arithmetic progression inside a sequence
Suppose I have a sequence of increasing numbers, and I want to find the length of longest arithmetic progression within the sequence. Longest arithmetic progression means an increasing sequence with common difference, such as [2, 4, 6, 8] or [3, 6, 9, 12].

For example,
for [5, 10, 14, 15, 17], [5, 10, 15] is the longest arithmetic progression, with length 3;

for [10, 12, 13, 20, 22, 23, 30], [10, 20, 30] is the longest arithmetic progression with length 3;

for [7, 10, 12, 13, 15, 20, 21], [10, 15, 20] or [7, 10, 13] are the longest arithmetic progressions with length 3.

This site
https://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_22_-_Longest_arithmetic_progression.jsp
offers some insight into the problem, i.e. by looping around j and consider
every 3 elements. I intend to use this algorithm in Python, and my code is as follows:

```<code>def length_of_AP(L):
n = len(L)
Table = [[0 for _ in range(n)] for _ in range(n)]
length_of_AP = 2

# initialise the last column of the table as all i and (n-1) pairs have lenth 2
for i in range(n):
        Table[i][n-1] =2

# loop around the list and i, k such that L[i] + L[k] = 2 * L[j]
for j in range(n - 2, 0, -1):
        i = j - 1
        k = j + 1
        while i >= 0 and k < n:
                difference = (L[i] + L[k]) - 2 * L[j]
                if difference < 0:
                        k = k + 1
                else:
                        if difference > 0:
                                i = i - 1
                        else:
                                Table[i][j] = Table[j][k] + 1
                                length_of_AP = max(length_of_AP, Table[i][j])
                                k = k + 1
                                i = i - 1
return length_of_AP
</code>```

This function works fine with [1, 3, 4, 5, 7, 8, 9], but it doesn't work for [5, 10, 14, 15, 20, 25, 26, 27, 28, 30, 31], where I am supposed to get 6 but I got 4. I can see the reason being that 25, 26, 27, 28 inside the list may be a distracting factor for my function. How do I change my function so that it gives me the result desired.

Any help may be appreciated.

答:
Did you try it?

Here's a quick brute force implementation, for small datasets it should run fast enough:

```<code>def gen(seq):
    diff = ((b-a, a) for a, b in it.combinations(sorted(seq), 2))
    for d, n in diff:
        k = []
        while n in seq:
            k.append(n)
            n += d
        yield (d, k)

def arith(seq):
    return max(gen(seq), key=lambda x: len(x[1]))

In [1]: arith([7, 10, 12, 13, 15, 20, 21])
Out[1]: (3, [7, 10, 13])
In [2]: %timeit arith([7, 10, 12, 13, 15, 20, 21])
10000 loops, best of 3: 23.6 µs per loop
In [3]: seq = {random.randrange(1000) for _ in range(100)}
In [4]: arith(seq)
Out[4]: (171, [229, 400, 571, 742, 913])
In [5]: %timeit arith(seq)
100 loops, best of 3: 3.79 ms per loop
In [6]: seq = {random.randrange(1000000) for _ in range(1000)}
In [7]: arith(seq)
Out[7]: (81261, [821349, 902610, 983871])
In [8]: %timeit arith(seq)
1 loop, best of 3: 434 ms per loop
</code>```

Body:
Suppose I have a sequence of increasing numbers, and I want to find the length of longest arithmetic progression within the sequence. Longest arithmetic progression means an increasing sequence with common difference, such as [2, 4, 6, 8] or [3, 6, 9, 12].

For example,
for [5, 10, 14, 15, 17], [5, 10, 15] is the longest arithmetic progression, with length 3;

for [10, 12, 13, 20, 22, 23, 30], [10, 20, 30] is the longest arithmetic progression with length 3;

for [7, 10, 12, 13, 15, 20, 21], [10, 15, 20] or [7, 10, 13] are the longest arithmetic progressions with length 3.

This site
https://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_22_-_Longest_arithmetic_progression.jsp
offers some insight into the problem, i.e. by looping around j and consider
every 3 elements. I intend to use this algorithm in Python, and my code is as follows:

def length_of_AP(L):
n = len(L)
Table = [[0 for _ in range(n)] for _ in range(n)]
length_of_AP = 2

# initialise the last column of the table as all i and (n-1) pairs have lenth 2
for i in range(n):
        Table[i][n-1] =2

# loop around the list and i, k such that L[i] + L[k] = 2 * L[j]
for j in range(n - 2, 0, -1):
        i = j - 1
        k = j + 1
        while i >= 0 and k < n:
                difference = (L[i] + L[k]) - 2 * L[j]
                if difference < 0:
                        k = k + 1
                else:
                        if difference > 0:
                                i = i - 1
                        else:
                                Table[i][j] = Table[j][k] + 1
                                length_of_AP = max(length_of_AP, Table[i][j])
                                k = k + 1
                                i = i - 1
return length_of_AP

This function works fine with [1, 3, 4, 5, 7, 8, 9], but it doesn't work for [5, 10, 14, 15, 20, 25, 26, 27, 28, 30, 31], where I am supposed to get 6 but I got 4. I can see the reason being that 25, 26, 27, 28 inside the list may be a distracting factor for my function. How do I change my function so that it gives me the result desired.

Any help may be appreciated.

Body:
Did you try it?

Here's a quick brute force implementation, for small datasets it should run fast enough:

def gen(seq):
    diff = ((b-a, a) for a, b in it.combinations(sorted(seq), 2))
    for d, n in diff:
        k = []
        while n in seq:
            k.append(n)
            n += d
        yield (d, k)

def arith(seq):
    return max(gen(seq), key=lambda x: len(x[1]))

In [1]: arith([7, 10, 12, 13, 15, 20, 21])
Out[1]: (3, [7, 10, 13])
In [2]: %timeit arith([7, 10, 12, 13, 15, 20, 21])
10000 loops, best of 3: 23.6 µs per loop
In [3]: seq = {random.randrange(1000) for _ in range(100)}
In [4]: arith(seq)
Out[4]: (171, [229, 400, 571, 742, 913])
In [5]: %timeit arith(seq)
100 loops, best of 3: 3.79 ms per loop
In [6]: seq = {random.randrange(1000000) for _ in range(1000)}
In [7]: arith(seq)
Out[7]: (81261, [821349, 902610, 983871])
In [8]: %timeit arith(seq)
1 loop, best of 3: 434 ms per loop


问:
Is a View Engine necessary for Express/Node?
So i've dove into Node/Express head first (w/Learning Javascript Intermediate stuff) and im a bit confused at why a "view engine" like Jade or EJS is required?

I can't seem to find something that uses just normal HTML5? Or is it that I cannot pass values to normal HTML with express?

Lets pretend I had an index.html page that loads and when I "Login" it loads with the user name posted at the top (Just for example). Can I not pass values to a normal .html file within express?

答:
Is a View Engine necessary for Express/Node?

No, it is not required.  Express can happily serve static HTML5 files as you wish.  You don't need a view engine for that.  You can either create custom routes and use res.sendFile() for each page or you can use express.static() to automatically serve a whole directory of static HTML files or you can write your own code to construct whatever HTML5 content you want to send and use res.send() to send it.

Where a view engine is required is if you want a template-type of system where you can create an HTML template with placeholders for dynamic content and then have dynamic values inserted into the page on the server.

Can I not pass values to a normal .html file within express?

No, you can't do that with regular express.  Express has facilities for serving static HTML files, but not for inserting dynamic content into an HTML file.  That's what you use a view engine for.  Express did not build that capability in itself because there are dozens of different view engine philosophies and Express didn't want to mandate one style so instead it supports a view engine interface for rendering from a template and you can select which view engine you want to use.


问:
Javascript skips seconds
I'm a newbie to javascript and I am trying to create a 6 hours countdown timer before it executes a specified function but the time display is totally wrong

what am I doing wrong and how do I get this to properly display in Hours, Minutes and Seconds?

Here is the code

function startTimer(duration, display) {
  var start = Date.now(),
    diff,
    minutes,
    seconds;

  function timer() {
    // get the number of seconds that have elapsed since
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);

    // does the same job as parseInt truncates the float
    minutes = (diff / 60 * 360) | 0;
    seconds = (diff % 60) | 0;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (diff <= 0) {
      // add one second so that the count down starts at the full duration
      // example 05:00 not 04:59
      start = Date.now() + 1000;
    }
  };
  // we don't want to wait a full second before the timer starts
  timer();
  setInterval(timer, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 2,
    display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id="time" style="background:white;border:2px solid green;color:green;paddding:5px;"></span> To Delete Your Account</code>```

答:
<!DOCTYPE html>

```

Title: Javascript skips seconds

Body:
I'm a newbie to javascript and I am trying to create a 6 hours countdown timer before it executes a specified function but the time display is totally wrong

what am I doing wrong and how do I get this to properly display in Hours, Minutes and Seconds?

Here is the code

function startTimer(duration, display) {
  var start = Date.now(),
    diff,
    minutes,
    seconds;

  function timer() {
    // get the number of seconds that have elapsed since
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);

    // does the same job as parseInt truncates the float
    minutes = (diff / 60 * 360) | 0;
    seconds = (diff % 60) | 0;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds;

    if (diff <= 0) {
      // add one second so that the count down starts at the full duration
      // example 05:00 not 04:59
      start = Date.now() + 1000;
    }
  };
  // we don't want to wait a full second before the timer starts
  timer();
  setInterval(timer, 1000);
}

window.onload = function() {
  var fiveMinutes = 60 * 2,
    display = document.querySelector('#time');
  startTimer(fiveMinutes, display);
};

 To Delete Your Account

Body:
<!DOCTYPE html>
<html>

<head></head>

<body>
  <div id='time'></div>

  <script type="text/javascript">
    function startTimer(duration, display) {

      setInterval(function() {
        duration = duration - 1;
        if (duration == -1) {
          clearInterval(duration);
          return;
        }

        var seconds = duration % 60;
        var minutes = Math.floor(duration / 60);
        var hours = Math.floor(minutes / 60);
        minutes %= 60;
        hours %= 60;

        display.textContent = hours + ":" + minutes + ":" + seconds;

      }, 1000);
    }

    window.onload = function() {
      var sixhours = 60 * 60 * 6
      display = document.querySelector('#time');
      startTimer(sixhours, display);
    };
  </script>
</body>

</html>


问:
How to start a background process with nohup using Fabric?
Through Fabric, I am trying to start a celerycam process using the below nohup command. Unfortunately, nothing is happening. Manually using the same command, I could start the process but not through Fabric. Any advice on how can I solve this?

```<code>def start_celerycam():
    '''Start celerycam daemon'''
    with cd(env.project_dir):
        virtualenv('nohup bash -c "python manage.py celerycam --logfile=%scelerycam.log --pidfile=%scelerycam.pid &> %scelerycam.nohup &> %scelerycam.err" &' % (env.celery_log_dir,env.celery_log_dir,env.celery_log_dir,env.celery_log_dir))

</code>```

答:
you just need to run</p>

```<code>run("(nohup yourcommand >& /dev/null < /dev/null &) && sleep 1")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Through Fabric, I am trying to start a celerycam process using the below nohup command. Unfortunately, nothing is happening. Manually using the same command, I could start the process but not through Fabric. Any advice on how can I solve this?

def start_celerycam():
    '''Start celerycam daemon'''
    with cd(env.project_dir):
        virtualenv('nohup bash -c "python manage.py celerycam --logfile=%scelerycam.log --pidfile=%scelerycam.pid &> %scelerycam.nohup &> %scelerycam.err" &' % (env.celery_log_dir,env.celery_log_dir,env.celery_log_dir,env.celery_log_dir))

Body:
you just need to run

run("(nohup yourcommand >& /dev/null < /dev/null &) && sleep 1")


问:
Problems with C strings and atoi function
I'm working on a program that requires the user to enter a C string of numbers, my program will then convert the characters to ints and then sum them.

However, when I run it, my program is multiplying the number provided by the number of digits there, i.e: if I put 123 it returns 369 or 123*3 or 123+123+123. It is summing the whole C string , instead of adding one element of the string at a time like I am trying to get it too.

When I try to do sum+=atoi(numbers[i]); it tells me that it can't convert char to const char*, however with it just as sum+=atoi(numbers); it is doing the whole string.

Please explain how to do this properly for myself and others.

```<code>#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
    const int SIZE=9000;   //max size of c string
    char numbers[SIZE];    //declare an char array
    int sum=0;             //initialize at 0
    cout << "Enter a series of single digit numbers with nothing separating them.\n";
    cout << "And I will tell you sum of those single digits\n";

    //prompt user

    cin.getline(numbers,SIZE);
    //get input

    //for loop till the end of the string
    for (int i=0; i<strlen(numbers);i++)
    {
        sum+=atoi(numbers);
        //if i put "atoi(numbers[i]);" then it tells me I
        //can't convert char to const char*
    }

    cout << "The sum of these single digits is "<< sum <<endl;  //display result
    return 0;
}
</code>```

答:
You are calling

```<code>sum+=atoi(numbers);
</code>```

three times. Of course you get sum as 123+123+123.

What you need to do is convert each character to a number by subtracting '0' from the character.

```<code>for (int i=0; i < strlen(numbers); i++)
{
   char c = numbers[i];
   if ( isdigit(c) )
   {
      sum += (c - '0');
   }
   else
   {
      // Deal with the case when character is not a digit.
   }
}
</code>```

Body:
I'm working on a program that requires the user to enter a C string of numbers, my program will then convert the characters to ints and then sum them.

However, when I run it, my program is multiplying the number provided by the number of digits there, i.e: if I put 123 it returns 369 or 123*3 or 123+123+123. It is summing the whole C string , instead of adding one element of the string at a time like I am trying to get it too.

When I try to do sum+=atoi(numbers[i]); it tells me that it can't convert char to const char*, however with it just as sum+=atoi(numbers); it is doing the whole string.

Please explain how to do this properly for myself and others.

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
    const int SIZE=9000;   //max size of c string
    char numbers[SIZE];    //declare an char array
    int sum=0;             //initialize at 0
    cout << "Enter a series of single digit numbers with nothing separating them.\n";
    cout << "And I will tell you sum of those single digits\n";

    //prompt user

    cin.getline(numbers,SIZE);
    //get input

    //for loop till the end of the string
    for (int i=0; i<strlen(numbers);i++)
    {
        sum+=atoi(numbers);
        //if i put "atoi(numbers[i]);" then it tells me I
        //can't convert char to const char*
    }

    cout << "The sum of these single digits is "<< sum <<endl;  //display result
    return 0;
}

Body:
You are calling

sum+=atoi(numbers);

three times. Of course you get sum as 123+123+123.

What you need to do is convert each character to a number by subtracting '0' from the character.

for (int i=0; i < strlen(numbers); i++)
{
   char c = numbers[i];
   if ( isdigit(c) )
   {
      sum += (c - '0');
   }
   else
   {
      // Deal with the case when character is not a digit.
   }
}