text:
Q: How to create a video from an array of images in Android? I want to call a function and build a video out of list of images, and then save it locally on the device:
public void CreateAndSaveVideoFile(List<Bitmap> MyBitmapArray)
{
   // ..
}

Trials:

*

*Following java/xuggle - encode array of images into a movie, the link in the answer is a dead link

*Following How to encode images into a video file in Java through programming?, The suggested library in the accepted answer does not support Android.

*The next answer in the above has an approach for Android users however it is not clear for me the input and the output of that function (where did he give the images? and where did he get the video?) - I left a question comment

*The next answer in the above provides a whole class, however the required library to be included has a corrupted file (when I try and download it from the provided link) - I left a question comment

*Following Java: How do I create a movie from an array of images?, the suggested library in the top answer uses commands that I am not familiar with and I don't even know how to use them. Like:

Creating an MPEG-4 file from all the JPEG files in the current
  directory:
mencoder mf://*.jpg -mf w=800:h=600:fps=25:type=jpg -ovc lavc \
  -lavcopts vcodec=mpeg4:mbd=2:trell -oac copy -o output.avi

I don't know how can I use the above in a Java / Android project..
Can anyone help in guiding me or/and providing me with an approach to my task? Thanks in advance.

A: You can use Bitmp4 to convert sequence of images to MP4 file.
Sample code :
...
val encoder = MP4Encoder()
     encoder.setFrameDelay(50)
     encoder.setOutputFilePath(exportedFile.path)
     encoder.setOutputSize(width, width)

 startExport()

 stopExport()

 addFrame(bitmap) //called intervally

It's a java library so it's easy to import it into Android project, you don't have to use NDK unlike ffmpeg.
Refer https://github.com/dbof10/Bitmp4 for sample code & downloads.

A: You can use jcodec SequenceEncoder to convert sequence of images to MP4 file.
Sample code :
import org.jcodec.api.awt.SequenceEncoder;
...
SequenceEncoder enc = new SequenceEncoder(new File("filename"));
// GOP size will be supported in 0.2
// enc.getEncoder().setKeyInterval(25);
for(...) {
    BufferedImage image = ... // Obtain an image to encode
    enc.encodeImage(image);
}
enc.finish();

It's a java library so it's easy to import it into Android project, you don't have to use NDK unlike ffmpeg.
Refer http://jcodec.org/ for sample code & downloads.

A: I created a project that should be able to handle this.  The code is light and fairly straight forward.
https://github.com/dburckh/bitmap2video

A: Using JCodec as demonstrated by Stanislav Vitvitskyy  here.

public static void main(String[] args) throws IOException {
    SequenceEncoder encoder = new SequenceEncoder(new File("video.mp4"));
    for (int i = 1; i < 100; i++) {
        BufferedImage bi = ImageIO.read(new File(String.format("img%08d.png", i)));
        encoder.encodeImage(bi);
        }
    encoder.finish();}

Now to convert your Bitmap to BufferedImage you can use this class:
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.io.IOException;
import java.io.InputStream;

/**
  * Utility class for loading windows bitmap files
  * <p>
  * Based on code from author Abdul Bezrati and Pepijn Van Eeckhoudt
  */
public class BitmapLoader {

/**
 * Static method to load a bitmap file based on the filename passed in.
 * Based on the bit count, this method will either call the 8 or 24 bit
 * bitmap reader methods
 *
 * @param file The name of the bitmap file to read
 * @throws IOException
 * @return A BufferedImage of the bitmap
 */
public static BufferedImage loadBitmap(String file) throws IOException {
    BufferedImage image;
    InputStream input = null;
    try {
        input = ResourceRetriever.getResourceAsStream(file);

        int bitmapFileHeaderLength = 14;
        int bitmapInfoHeaderLength = 40;

        byte bitmapFileHeader[] = new byte[bitmapFileHeaderLength];
        byte bitmapInfoHeader[] = new byte[bitmapInfoHeaderLength];

        input.read(bitmapFileHeader, 0, bitmapFileHeaderLength);
        input.read(bitmapInfoHeader, 0, bitmapInfoHeaderLength);

        int nSize = bytesToInt(bitmapFileHeader, 2);
        int nWidth = bytesToInt(bitmapInfoHeader, 4);
        int nHeight = bytesToInt(bitmapInfoHeader, 8);
        int nBiSize = bytesToInt(bitmapInfoHeader, 0);
        int nPlanes = bytesToShort(bitmapInfoHeader, 12);
        int nBitCount = bytesToShort(bitmapInfoHeader, 14);
        int nSizeImage = bytesToInt(bitmapInfoHeader, 20);
        int nCompression = bytesToInt(bitmapInfoHeader, 16);
        int nColoursUsed = bytesToInt(bitmapInfoHeader, 32);
        int nXPixelsMeter = bytesToInt(bitmapInfoHeader, 24);
        int nYPixelsMeter = bytesToInt(bitmapInfoHeader, 28);
        int nImportantColours = bytesToInt(bitmapInfoHeader, 36);

        if (nBitCount == 24) {
            image = read24BitBitmap(nSizeImage, nHeight, nWidth, input);
        } else if (nBitCount == 8) {
            image = read8BitBitmap(nColoursUsed, nBitCount, nSizeImage, nWidth, nHeight, input);
        } else {
            System.out.println("Not a 24-bit or 8-bit Windows Bitmap, aborting...");
            image = null;
        }
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (IOException e) {
        }
    }
    return image;
}

/**
 * Static method to read a 8 bit bitmap
 *
 * @param nColoursUsed Number of colors used
 * @param nBitCount The bit count
 * @param nSizeImage The size of the image in bytes
 * @param nWidth The width of the image
 * @param input The input stream corresponding to the image
 * @throws IOException
 * @return A BufferedImage of the bitmap
 */
private static BufferedImage read8BitBitmap(int nColoursUsed, int nBitCount, int nSizeImage, int nWidth, int nHeight, InputStream input) throws IOException {
    int nNumColors = (nColoursUsed > 0) ? nColoursUsed : (1 & 0xff) << nBitCount;

    if (nSizeImage == 0) {
        nSizeImage = ((((nWidth * nBitCount) + 31) & ~31) >> 3);
        nSizeImage *= nHeight;
    }

    int npalette[] = new int[nNumColors];
    byte bpalette[] = new byte[nNumColors * 4];
    readBuffer(input, bpalette);
    int nindex8 = 0;

    for (int n = 0; n < nNumColors; n++) {
        npalette[n] = (255 & 0xff) << 24 |
                (bpalette[nindex8 + 2] & 0xff) << 16 |
                (bpalette[nindex8 + 1] & 0xff) << 8 |
                (bpalette[nindex8 + 0] & 0xff);

        nindex8 += 4;
    }

    int npad8 = (nSizeImage / nHeight) - nWidth;
    BufferedImage bufferedImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_INT_ARGB);
    DataBufferInt dataBufferByte = ((DataBufferInt) bufferedImage.getRaster().getDataBuffer());
    int[][] bankData = dataBufferByte.getBankData();
    byte bdata[] = new byte[(nWidth + npad8) * nHeight];

    readBuffer(input, bdata);
    nindex8 = 0;

    for (int j8 = nHeight - 1; j8 >= 0; j8--) {
        for (int i8 = 0; i8 < nWidth; i8++) {
            bankData[0][j8 * nWidth + i8] = npalette[((int) bdata[nindex8] & 0xff)];
            nindex8++;
        }
        nindex8 += npad8;
    }

    return bufferedImage;
}

/**
 * Static method to read a 24 bit bitmap
 *
 * @param nSizeImage size of the image  in bytes
 * @param nHeight The height of the image
 * @param nWidth The width of the image
 * @param input The input stream corresponding to the image
 * @throws IOException
 * @return A BufferedImage of the bitmap
 */
private static BufferedImage read24BitBitmap(int nSizeImage, int nHeight, int nWidth, InputStream input) throws IOException {
    int npad = (nSizeImage / nHeight) - nWidth * 3;
    if (npad == 4 || npad < 0)
        npad = 0;
    int nindex = 0;
    BufferedImage bufferedImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_4BYTE_ABGR);
    DataBufferByte dataBufferByte = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer());
    byte[][] bankData = dataBufferByte.getBankData();
    byte brgb[] = new byte[(nWidth + npad) * 3 * nHeight];

    readBuffer(input, brgb);

    for (int j = nHeight - 1; j >= 0; j--) {
        for (int i = 0; i < nWidth; i++) {
            int base = (j * nWidth + i) * 4;
            bankData[0][base] = (byte) 255;
            bankData[0][base + 1] = brgb[nindex];
            bankData[0][base + 2] = brgb[nindex + 1];
            bankData[0][base + 3] = brgb[nindex + 2];
            nindex += 3;
        }
        nindex += npad;
    }

    return bufferedImage;
}

/**
 * Converts bytes to an int
 *
 * @param bytes An array of bytes
 * @param index
 * @returns A int representation of the bytes
 */
private static int bytesToInt(byte[] bytes, int index) {
    return (bytes[index + 3] & 0xff) << 24 |
            (bytes[index + 2] & 0xff) << 16 |
            (bytes[index + 1] & 0xff) << 8 |
            bytes[index + 0] & 0xff;
}

/**
 * Converts bytes to a short
 *
 * @param bytes An array of bytes
 * @param index
 * @returns A short representation of the bytes
 */
private static short bytesToShort(byte[] bytes, int index) {
    return (short) (((bytes[index + 1] & 0xff) << 8) |
            (bytes[index + 0] & 0xff));
}

/**
 * Reads the buffer
 *
 * @param in An InputStream
 * @param buffer An array of bytes
 * @throws IOException
 */
private static void readBuffer(InputStream in, byte[] buffer) throws IOException {
    int bytesRead = 0;
    int bytesToRead = buffer.length;
    while (bytesToRead > 0) {
        int read = in.read(buffer, bytesRead, bytesToRead);
        bytesRead += read;
        bytesToRead -= read;
    }
}
}

A: If the minimum version of you application Android SDK is greater or equal to 16 (Android 4.1) the best way of video encoding is use Android Media Codec API.
From Android 4.3 APIs.

When encoding video, Android 4.1 (SDK 16) required that you provide
  the media with a ByteBuffer array, but Android 4.3 (SDK 18) now allows
  you to use a Surface as the input to an encoder. For instance, this
  allows you to encode input from an existing video file or using frames
  generated from OpenGL ES.

Media Muxer added in Android 4.3 (SDK 18) so for convenient way of writing mp4 file with Media Muxer you should have SDK>=18.
Using Media Codec API way you will get hardware accelerated encoding and you are easily encode up to 60 FPS.
You can start from 1) How to encode Bitmaps into a video using MediaCodec?
or use 2) Google Grafika or 3) Bigflake.
Starting from Grafika RecordFBOActivity.java. Replace Choreographer event with you own containing bitmap to encode, remove On Screen drawing, load you bitmap as Open GL Texture and draw it on Media Codec Input Surface.

A: jCodec has added Android support.
You need to add these to your gradle...
implementation 'org.jcodec:jcodec:0.2.3'
implementation 'org.jcodec:jcodec-android:0.2.3'

...and
android {
    ...
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.2'
    }
}

I can confirm this works as expected, but with caveats.  First being I tried some full size images and the file wrote, but gave an error on playback.  When I scaled down, I would get an error if the width or height of the image was not even because it requires a multiple of 2 for YUV420J colorspace.
Also worthy of note, this makes your package HEAVY, heavy.  My small project went over the dex limit by adding this and required enabling multidex.
FileChannelWrapper out = null;
File dir = what ever directory you use...
File file = new File(dir, "test.mp4");

try { out = NIOUtils.writableFileChannel(file.getAbsolutePath());
      AndroidSequenceEncoder encoder = new AndroidSequenceEncoder(out, Rational.R(15, 1));
      for (Bitmap bitmap : bitmaps) {
          encoder.encodeImage(bitmap);
      }
      encoder.finish();
} finally {
    NIOUtils.closeQuietly(out);
}

A: Abhishek V was right, more information about jcodec SequenceEncoder:
see Android make animated video from list of images
Recently I have built a real-time video system using raspberry pi and Android devices, met the same problem as yours. Instead of saving a list of image files, I used some real-time streaming protocols like RTP/RTCP to transfer data stream to user. If your requirement is something like this, maybe you could change your strategies.
Another suggestion is that you may explore some C/C++ libraries, using NDK/JNI to break the limitation of Java.
Hope the suggestions make sense to you :)


text:
Q: Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. I Used Laravel Authentication,And in Reset Password I Want to send Reset Link to email.
My .env is here:
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=MyPassword
MAIL_ENCRYPTION=null

And my mail.php:
<?php

 return [
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'smtp.gmail.com'),
'port' => env('MAIL_PORT', 587);
'from' => [
    'address' => env('MAIL_FROM_ADDRESS', 'hanieasemi76@gmail.com'),
    'name' => env('MAIL_FROM_NAME', 'hanie'),
],
'encryption' => env('MAIL_ENCRYPTION', 'ssl'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'sendmail' => '/usr/sbin/sendmail -bs',
'stream' => [
    'ssl' => [
        'allow_self_signed' => true,
        'verify_peer' => false,
        'verify_peer_name' => false,
    ],
],

'markdown' => [
    'theme' => 'default',

    'paths' => [
        resource_path('views/vendor/mail'),
    ],
],
];

And Turn on 2-step verification of my gmail,But Now When I Want to send email I give this Error Expected response code 250 but got code "530", with message "530 5.7.0 Must issue a STARTTLS command first. r7-v6sm5414781wrn.83 - gsmtp
How I can fixet it?where is my problem?

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Como utilizar variables de js en un ts de angular? Buen día.
Lo que necesito sabes es ¿Cómo puedo acceder al valor de la variable ejemplo que está en index.html para usarlo en button-bar.component.ts?
En este ejemplo tengo una variable y un método que le asigna un valor en index.html pero quiero llamar a un método dentro de button-bar.component.ts el cual lo que hará es imprimir el mensaje en la consola del navegador. Tengo el siguiente código de ejemplo.
En la aplicación real estoy usando la siguiente librebría
<script src="https://static.vidyo.io/4.1.8.1/javascript/VidyoClient/VidyoClient.js?onload=onVidyoClientLoaded"></script>

La librería anterior carga un callback llamado onVidyoClientLoaded como parámetro y despues de que la librería cargue es llamado el callback.
Gracias.
//index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Ejemplo</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
  </head>
  <body>
    <app-root></app-root>
    <script>

      let ejemplo;

      ejemploF();

      function ejemploF() {
        ejemplo = "Hola mundo";
      }
    </script>
  </body>
</html>

//button-bar.component.ts
import { Component } from '@angular/core';
declare var ejemplo:any;

@Component({
  selector: 'app-button-bar',
  templateUrl: './button-bar.component.html'
})
export class ButtonBarComponent {

  constructor() {
    this.getEjemploFValue();
  }

  getEjemploFValue() {
    console.log(ejemplo);
  }
}

A:

// SERVICIO
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class EjemploService {

  variableDelServicio: any;
}

// COMPONENTE
import { Component } from '@angular/core';
import { EjemploService } from 'src/app/services/ejemplo.service';

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

  variableDelComponente: any;

  constructor( public: miServicio: EjemploService ) {
    // Accedes a la variable así:
    this.variableDelComponente = miServicio.variableDelServicio;
  }
}


text:
Q: Pass a variable from the DOM to SCSS I am using angular with .scss and I would like to know how to do the below .less code in .scss instead.
HTML

CSS
.flag-icon-@{country} {
  //@country being the {{territoryId}} from above
}

Is this possible?

A: HTML

scss file
$country-collection: ('india', 'usa', 'germany', 'pakistan');

@for $country from 0 to length($country-collection) {
    .flag-icon-#{$country} {
        color: red;
    }
}

A: Thank you Sayooj V R: https://stackoverflow.com/users/10647431/sayooj-v-r
I tried your above, but it didn't seem to work, but it gave me more knowledge of what I can do with scss and I managed to figure it out (woohoo!) with the below code:
HTML

SCSS
$country-collection: ('india', 'usa', 'germany', 'pakistan');

@each $country in $country-collection {
    .flag-icon-#{$country} {
      color: red
    }
}

The @for didn't seem to be working for some reason (not sure why) so I tried a different loop technique using the @each method, and walaaaah it worked!
The documentation for @each is here: https://sass-lang.com/documentation/at-rules/control/each


text:
Q: How check difference between string and object string in Javascript? I have 2 strings like this:
var a = 'Mario';
var b = '{title: 'Luigi', age: 38}';

and I want the new variable:
 c = 'Mario';
 d = {title: 'Luigi', age: 38};

How can I check the difference between a and b in the if condition?
I tryed with JSON.parse(); but it doens't work with the variable a.
The code I write is:
if( typeof(JSON.parse(x)) != 'object'){
  //then I want simply x that is a string
}else{
 //then I want JSON.parse(x) that is an object
}

Let's say that I have a database where there are saved all strings like 'a'. Now I want also save strings like 'b' at the same voice of database. In other words, in the database there are all strings, but some of them are strings like 'b' and I need to write something like b.title
I hope is much clear
Thanks!

A: The question was not clear to me but what I got is you want to differentiate between a string and string-object.
If so, use JSON.parse with try - catch block.
const a = 'Mario';
const b = "{'title': 'Luigi', 'age': '38'}";
const [c,d] = [a, b].map((e) => {
    try {
        return (JSON.parse(e))
    } catch (error) {
        return e
    }
})

Hope this helps you!


text:
Q: Flutter Doctor not working on fresh install in my Mac Air M1 chip I've been trying to figure out the reason causing this error. I followed https://docs.flutter.dev/get-started/install/macos and search other possible solutions in the internet but no luck. A help would be appreciated. Thanks.
Device: Macbook Air M1
OS: BigSur
Tried switching from stable - beta - stable. Setting - re-setting path. Changing permissions
melchorlapinig@Melchors-MacBook-Air development % flutter doctor -v

The flutter tool cannot access the file or directory.
Please ensure that the SDK and/or project is installed in a location that has read/write permissions for the current user.

#0      throwToolExit (package:flutter_tools/src/base/common.dart:10:3)
#1      _throwFileSystemException (package:flutter_tools/src/base/error_handling_io.dart:820:3)
#2      _handlePosixException (package:flutter_tools/src/base/error_handling_io.dart:761:3)
#3      _runSync (package:flutter_tools/src/base/error_handling_io.dart:614:7)
#4      ErrorHandlingProcessManager.runSync (package:flutter_tools/src/base/error_handling_io.dart:711:12)
#5      _DefaultProcessUtils.runSync (package:flutter_tools/src/base/process.dart:373:51)
#6      AndroidStudio._init (package:flutter_tools/src/android/android_studio.dart:458:39)
#7      new AndroidStudio (package:flutter_tools/src/android/android_studio.dart:40:5)
#8      AndroidStudio.fromMacOSBundle (package:flutter_tools/src/android/android_studio.dart:90:12)
#9      AndroidStudio._allMacOS.<anonymous closure> (package:flutter_tools/src/android/android_studio.dart:316:68)
#10     MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#11     ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#12     WhereTypeIterator.moveNext (dart:_internal/iterable.dart:869:20)
#13     new _GrowableList._ofOther (dart:core-patch/growable_array.dart:198:26)
#14     new _GrowableList.of (dart:core-patch/growable_array.dart:152:26)
#15     new List.of (dart:core-patch/array_patch.dart:51:28)
#16     Iterable.toList (dart:core/iterable.dart:388:12)
#17     AndroidStudio._allMacOS (package:flutter_tools/src/android/android_studio.dart:318:10)
#18     AndroidStudio.allInstalled (package:flutter_tools/src/android/android_studio.dart:247:34)
#19     AndroidStudio.latestValid (package:flutter_tools/src/android/android_studio.dart:232:41)
#20     AppContext._generateIfNecessary.<anonymous closure> (package:flutter_tools/src/base/context.dart:104:42)
#21     _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:453:23)
#22     AppContext._generateIfNecessary (package:flutter_tools/src/base/context.dart:92:20)
#23     AppContext.get (package:flutter_tools/src/base/context.dart:121:32)
#24     AppContext.get (package:flutter_tools/src/base/context.dart:119:24)
#25     AppContext.get (package:flutter_tools/src/base/context.dart:119:24)
#26     androidStudio (package:flutter_tools/src/globals_null_migrated.dart:65:45)
#27     runInContext.<anonymous closure> (package:flutter_tools/src/context_runner.dart:104:32)
#28     AppContext._generateIfNecessary.<anonymous closure> (package:flutter_tools/src/base/context.dart:104:42)
#29     _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:453:23)
#30     AppContext._generateIfNecessary (package:flutter_tools/src/base/context.dart:92:20)
#31     AppContext.get (package:flutter_tools/src/base/context.dart:121:32)
#32     AppContext.get (package:flutter_tools/src/base/context.dart:119:24)
#33     AppContext.get (package:flutter_tools/src/base/context.dart:119:24)
#34     androidLicenseValidator (package:flutter_tools/src/android/android_workflow.dart:28:65)
#35     DoctorCommand.runCommand (package:flutter_tools/src/commands/doctor.dart:56:32)
#36     FlutterCommand.verifyThenRunCommand (package:flutter_tools/src/runner/flutter_command.dart:1290:12)
<asynchronous suspension>
#37     FlutterCommand.run.<anonymous closure> (package:flutter_tools/src/runner/flutter_command.dart:1140:27)
<asynchronous suspension>
#38     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
<asynchronous suspension>
#39     CommandRunner.runCommand (package:args/command_runner.dart:209:13)
<asynchronous suspension>
#40     FlutterCommandRunner.runCommand.<anonymous closure> (package:flutter_tools/src/runner/flutter_command_runner.dart:288:9)
<asynchronous suspension>
#41     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
<asynchronous suspension>
#42     FlutterCommandRunner.runCommand (package:flutter_tools/src/runner/flutter_command_runner.dart:236:5)
<asynchronous suspension>
#43     run.<anonymous closure>.<anonymous closure> (package:flutter_tools/runner.dart:62:9)
<asynchronous suspension>
#44     AppContext.run.<anonymous closure> (package:flutter_tools/src/base/context.dart:150:19)
<asynchronous suspension>
#45     main (package:flutter_tools/executable.dart:94:3)
<asynchronous suspension>```

A: Problem solve. You can see solution here: https://github.com/flutter/flutter/issues/96519

A: You must update your environment $PATH variable.

*

*Open the file $HOME/.zshrc $HOME is your home path

*add the following line in the opened file:
export PATH="$PATH:/YOUR_FLUTTER_DIR/flutter/bin"

*save the changes and restart your terminal session.
The process is also documented here


text:
Q: How does RAID detect a faulty HD? I have been looking over Raid levels over the past 3 days. And have been weighing up the pro/cons of raid controllers hardware/software. I understand that RAID is not a backup solution and I'm perfectly fine with it, though one question still remains.
How does a RAID controller, even Raid 1 to Raid 6 actually detect that a hard disk drive is failing. The research that I have done have showed that most common hard disk drive manufactures use ECC in their hard disk drive design that is suppose to protect against 1 bit failures to an extent 3 bits.
Though when thinking about this, lets say you have Raid (1) and two hard disk drives that are identical. Lets say, data is read from drive 0, and also at the same time from drive 1. Though drive 1 reports a ECC read failure to the Raid Controller.
Now this is the big question, with hardware raid what would the Raid controller do? Its got a signal from the hard disk that the read failed. It can report the hard disk drive as faulty and need replacing.
Does the Raid Controller Seeks to a different hard disk drive for the data until it gets a successfully read from the drive. (Yes, a drive can report read correct and the data can still be corrupted, and RAID does not check polarity or ECC on read)

A: The answer to the question is going to depend greatly on the RAID controller manufacturer and how they implemented error/failed drive detection.

A: I asked a NetApp engineer who was giving us a talk this very question.  His answer, more or less, was:

Nobody reads the checksums on reads.
  There's no point.  Reading a checksum
  means you have to read the entire
  slice plus checksum, then compute the
  checksum to verify you have the
  correct data.  Plus the orthoganal checksum if you are running RAID-6 or whatever.    It is a total performance killer because it breaks the ability to randomly seek to totally different sectors on different disks at the same time.  Similarly, almost
  nobody reads both sides of a mirror in
  RAID-1 because if you only read one side you can alternate which side of the mirror you read from so that you get faster throughput, and if you suddenly have a
  mismatch, which disk do you take as correct
  and which do you take as broken?  All
  modern RAID systems depend on the
  on-disk controllers to signal the RAID
  controller that they are in distress
  (through SMART or the like), at which
  point that disk is almost always
  kicked out of the array.  Checksums
  are used for rebuilding arrays, not
  for read-verification.

A: There are various methods that a RAID implementations can assess the "health" of a disk (SMART, SCSI "Check Condition" and "Sense Key" messages), but I'm not aware of any published "standard" as to how RAID implementations should act on these methods. The specific steps that each make and model of RAID controller firmware (or, for that matter, a software RAID implementation in an OS) uses are going to vary depending on the manufacturer's design.
All hard disk drives use error correcting codes (ECC) today. At the data densities we're working at bit errors are just a fact of life. Unrecoverable read errors are what matter to a RAID controller. At the level you're interested in, you'd have to have the design specs on both the RAID controller and the drive firmware to really understand how media errors would be reported up the device stack to the OS, and ultimately the user.

A: Implementation is entirely up to the manufacturer. They could use any mix of tools...
calculating parity of data as it's written to the drive and if it's wrong, it flags a possible issue, it could watch hard disk status if there's onboard SMART status, reading errors straight from the drive, see if there's issues through multiple errors to a particular drive, etc...
I've had a controller that didn't KNOW there was an issue with a drive. We had a three-drive RAID 5 where one disk completely failed. Installed a new drive, and in the process of rebuilding one of the good disks upchucked an unrecoverable read error, which is an issue more and more as drives get bigger and manufacturers allow a certain number of these in the manufacturing process. End result? Rebuild from bare metal backup. So when you ask how the controller "knows" the drive is bad, it doesn't necessarily know.
In other words, RAID controllers just do the best they can. They still fail.
The end result is that RAID controllers usually simplify your setup by abstracting the work from the software, they offload processing power to dedicated hardware, and they add (usually) some better support for telling the end user which drive is bad (through software tools and/or blinky lights) so you don't have to guess which one is bad.
Software RAID is integrated with the OS, it's far far cheaper, and it's just about as reliable now (if you're talking about Linux especially) and nearly as speedy (in some cases, faster). It also doesn't need special drivers unlike many controllers. If you use a high-end card it'll probably perform better but for most home-grade RAID they tend to be comparable in speed.
If you're talking about motherboard RAID, it's not really RAID. It is a crappy version of software RAID, and it makes it nigh impossible to recover data if your motherboard goes south because often they're vendor-specific in how they mess with data on the drive. I've had cases where a system failed and you couldn't take the drive from the array to another system to recover data from.
Overall, unless you're talking RAID for servers in a business or have really specialized needs, software RAID is probably on par with hardware RAID for %90 of what home users would use it for.


text:
Q: Compute class and instance hash I need to compute a "hash" which allows me to uniquely identify an object, both it's contents and the parent class.
By comparing these "hashes" i want to be able to tell if an object has changed since the last time it was scanned.
I have found plenty of examples on how to make an object hashable, however not so much about how to compute a hash of the parent class.
It is important to note comparisons are made during different executions. I say this because I think comparing the id() of the object since the id/address of the object might be different for different executions.
I thought of resorting to inspect but I fear it might not be very efficient, also I am not very sure how that would work if the object's parent class is inheriting from another class.
If I had access to the actual memory raw data where the instance and the class' code is stored, I could just compute the hash of that.
Any ideas?

A: General idea is to serialize object and then take a hash. Then, the only question is to find a good library. Let's try dill:
>>>import dill
>>>class a():
    pass
>>>b = a()
>>>b.x = lambda x:1
>>> hash(dill.dumps(b))
2997524124252182619
>>> b.x = lambda x:2
>>> hash(dill.dumps(b))
5848593976013553511
>>> a.y = lambda x: len(x)
>>> hash(dill.dumps(b))
-906228230367168187
>>> b.z = lambda x:2
>>> hash(dill.dumps(b))
5114647630235753811
>>>

Looks good?
dill: https://github.com/uqfoundation

A: To detect if an object has changed, you could generate a hash of its JSON representation and compare to the latest hash generated by the same method.
import json

instance.foo = 5
hash1 = hash(json.dumps(instance.__dict__, sort_keys=True))

instance.foo = 6
hash2 = hash(json.dumps(instance.__dict__, sort_keys=True))

hash1 == hash2
>> False

instance.foo = 5
hash3 = hash(json.dumps(instance.__dict__, sort_keys=True))

hash1 == hash3
>> True

Or, since json.dumps gives us a string, you can simply compare them instead of generating a hash.
import json

instance.foo = 5
str1 = json.dumps(instance.__dict__, sort_keys=True)

instance.foo = 6
str2 = json.dumps(instance.__dict__, sort_keys=True)

str1 == str2
>> False


text:
Q: Getting data if already exist I have a problem with SQL query. I have a history table, where orders have logged all changes of status. What I want to do is get order that have specific status.
I used this query:
SELECT TOP 1
    HistoryDate
FROM
    schema.History
WHERE
    OrderID = 123123
    AND OrderStatusID = 10
    AND OrderID IN (SELECT TOP 1 OrderID
                    FROM schema.History
                    WHERE OrderStatusId = 5
                      AND OrderID = 123123)

Query results satisfies, but I want to avoid referring to same table two times.
Any ideas?
EDIT:
What I didn't mention before is fact that when there are status 5 and 10 I want HistoryDate from status 10, if there is no status 10 I want NULL, and when there is only status 10 I want HistoryDate of status 10 also.

A: In general you have to use a subquery if you want to find another record in a second status and the same OrderID. But you could use EXISTS which is clearer in my opinion:
SELECT TOP 1 h1.HistoryDate
FROM schema.History h1
WHERE h1.OrderID = @OrderID
AND h1.OrderStatusID = 10
AND EXISTS
(
   SELECT 1 FROM schema.History h2
   WHERE h1.OrderID = h2.OrderID
   AND   h2.OrderStatusID = 5
)

A: I don't see any way to do this without using two tables.  Logically, you're defining an intersection of two sets, and that usually means two tables or a join.
@TimSchmelter's query with EXISTS is preferred, and may improve performance although keep in mind that TOP without ORDER BY is non-deterministic (i.e., not reliable) so you're not guaranteed to get the most recent or oldest HistoryDate.  You're just guaranteed to get a HistoryDate.
If you just don't want a subquery, you could do a self-join:
SELECT TOP 1 h1.HistoryDate
FROM schema.History h1
INNER JOIN schema.History h2
    ON h1.OrderID = h2.OrderID
WHERE h1.OrderID = 123123
    AND h1.OrderStatusID = 10
    AND h2.OrderStatusId = 5

Depending on your setup, that may perform better or may perform worse, although it should perform about the same.
Again, though, TOP without ORDER BY is non-deterministic.  I strongly encourage you to add an ORDER BY h1.HistoryDate or ORDER BY h1.HistoryDate DESC or you may very well get unexpected results if any Order has multiple history dates with OrderStatusID of 10.


text:
Q: How to Keep Track of the Index of a Non-Unique Element in a Vector? I'm most likely going about this the wrong way, but I was wondering if anyone has some advice for how to keep track of where a non-unique element is within a vector?
I'm using glDrawArraysInstanced and using a vector to store translations (i.e. the first element is the x translation, the second y, the third z, repeat) that offset the position of a particular instance. This vector is put into a buffer and the drawing works as expected with a good performance boost from using the instancing. I don't want to set the positions based on gl_InstanceID because the ID shifts depending on the number of instances drawn but I need the instances to stay consistent.
The problem comes in when trying to make the number of instances dynamic; I need to be able to add and remove elements in the vector efficiently without rebuilding the entire vector each time something changes. I'm not sure how to determine exactly where the translation is inside of the vector, however.

As an example:

*

*Instance 0 uses translations 0,1,2

*Instance 1 uses translations 3,4,5

*Instance 2 uses translations 6,7,8

Want to delete Instance 1:
I can store the index of the x component of the translation when the translations are first constructed, so I know I need to .erase 3 elements starting at 3.
Want to delete Instance 2:
How do I know what the starting index is for this instance? The indices stored during construction are no longer valid.

I know this case is trivial and I can just subtract from the initial stored index, but if I have say 40,000 instances is there an efficient way to always know where the specific translation for that instance is within the vector? After several additions/deletions of instances the indices can shift around a fair amount.
Note: I want to use the vector because OpenGL needs float* to fill the buffer. I could easily use a map between an instance and it's positions, but at some point I'd still need to get all of the positions together for rendering. If I'm missing something obvious on this point though please let me know. Swapping out the buffer doesn't seem to impact performance much, but rebuilding the entire positions vector when something changes is far too slow.
Hope this isn't too much of a wall of text.. any help would be appreciated.

A: Use "GLDrawElementsInstanced" instead so that there is no need to change the translation vector (just reorder the indices).
Update: (Real answer:)
Bind the transformation buffer (with ALL transformations including invisible instances) as TBO, then access it as a texture in a shader. Supply an index attribute per instance (glVertexAttribDivisor=1) to use as a coordinate to fetch from your translation texture.
This way you'll need to modify only the index buffer and append new translations to the translation buffer. At some points you can perform a cleanup procedure of the translation buffer by removing unused values.


text:
Q: AdMob banners cause high CPU usage I have the latest AdMob version (6.4.1), and when I show some banner its cause my CPU to start sweating (Not to mention the battery :S ).
I am destroying the AdView when I leave the activity, but when the activity is started it takes about 20% of CPU usage.
Is there any way to fix it? Why the CPU usage is so high when the ads are shown?

A:
Having test my app with 2 different implementations of AdMob I found
  that implementing it via java code and not XML is match lighter for
  the app.
Update No1:
You can also add custom listeners to destroy after some time and
  recreate in order to handle it even better. Serverside there is also a
  parameter telling the app ad how soon should ask for a new ad, I am
  not sure if it exist in all cases but it is there for DFP accounts.
A nice suggested way to implement the ad is that:
new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
  if (!isBeingDestroyed) {
      final AdRequest adRequest = new AdRequest();
      final AdView adView = (AdView) findViewById(R.id.ad);
      adView.loadAd(adRequest);
  }
}).sendEmptyMessageDelayed(0, 1000);

also do not forget to call adView.destroy() onDestroy()
  activity or when you do not want it any more!
The above way is mentioned here with many useful memory releases!

the complete answer is here: https://stackoverflow.com/a/14683378/1932105
please use the search next time. Good luck


text:
Q: Ошибка синтаксиса python Господа, помогите понять, в чем ошибка.
При попытке запуска скрипта получаю ошибку:
  File "./submit_script.py", line 10
    "timeout": (None, "600"),
             ^
SyntaxError: invalid syntax

Код скрипта:
#!/usr/bin/python
import requests

HEADERS = {"Authorization": "Bearer S4MPL3"}

# Submit one or more files.
r = requests.post("http://localhost:8090/tasks/create/submit", files=[
    ("files", open("/home/Downloads/downloader.js", "rb")),
#    ("files", open("2.exe", "rb")),
    "timeout": (None, "600"),
], headers=HEADERS)

# Add your code to error checking for r.status_code.

submit_id = r.json()["submit_id"]
task_ids = r.json()["task_ids"]
errors = r.json()["errors"]

Заранее благодарен.

A: "timeout": (None, "600") это семантика объявления значений в словаре, типа {"timeout": (None, "600")}, но у вас тот кусок кода находится внутри списка, поэтому и ругается интерпретатор
Попробуйте так:
# Submit one or more files.
r = requests.post(
    "http://localhost:8090/tasks/create/submit",
    files=[
        ("files", open("/home/Downloads/downloader.js", "rb")),
    ],
    headers=HEADERS,
    timeout=(None, 600)
)


text:
Q: Two sample test multivariate normal
Let $\bf{X_{1}}\sim N_p(\mu_1,\Sigma_1)$ and $\bf{X_2\sim
 N_p(\mu_2,\Sigma_2)}$. Find the likelihood ratio test for
   $$H_0:\mu_1=\mu_2\ vs\ \mu_1\neq \mu_2$$ with know $\bf{\Sigma_1}$ and
   $\bf{\Sigma_2}$.

I'm lost in how to do this in the multivariate case, most of the books I've seen found no examples just mention the method and distribution that you get.
I should find the joint likelihood
$$L=\prod f_{X_1}(X_1)f_{X_2}(X_2)$$
then find the estimators $\mu_1$, $\mu_2$, $\Sigma_1$, $\Sigma_2$ and then find
$$\Lambda=\frac{L(\theta_0)}{L(\theta_1)}$$
the ratio of maximum likelihood under $H_0$ and unrestricted?

A: I think that's right. I'm assuming $X_1, X_2$ are mutually independent.
Maximizing the unconstrained likelihood is easy. The only part you neglect to cover is that you need a clever way to maximize the constrained likelihood. Mathematically, constrained optimization is done with Lagrange multipliers. It would be easy to write down such a likelihood. Computationally you don't need to worry about it, just write down the null likelihood and optimize the parameters using a general optimization technique.


text:
Q: Hardware-accelerated scaling on iOS without OpenGL I'm currently writing an iOS backend for a cross-platform program whose platform-independent engine writes all of its graphics into 32-bit pixel buffers, in RGBA order. The alpha byte isn't used. The graphics are always opaque so I don't need alpha blending.
What is the most efficient option to draw and scale these pixel buffers to my CGContextRef inside my drawRect method? The pixel buffers are usually only 320x240 pixels and need to be scaled to completely fill my view's dimensions, e.g. 1024x768 on non-Retina iPads and 2048x1536 on Retina iPads. This is a whole lot of work so it's best done using the GPU. But how can I force iOS to draw and scale using the GPU without using OpenGL?
I've tried using CGContextDrawImage() but this is really slow, probably because everything is done using the CPU.
I've also had a look at the CIImage APIs because these are apparently GPU optimized but the problem is that CIImage objects are immutable so I'd have to constantly create new CIImage objects for each frame I need to draw which will probably kill the performance as well.
I could go with OpenGL of course but I'd like to get some feedback on whether there is an easier solution to get what I want here.
Thanks for any ideas!

A: To answer my own question, the easiest way to do this is to simply create a CGImageRef from the pixel buffer using CGDataProviderCreateWithData() and then CGImageCreate(). This CGImageRef can then be set as the view's layer, like so:
view.layer.contents = (id) myImage;

The image will then be automatically scaled (with GPU acceleration) to fit the UIView's frame if contentMode is set to UIViewContentModeScaleToFill (which is the default).
Thanks to David Duncan from the Cocoa mailing list for suggesting this solution!


text:
Q: RS232 (UART) on STM32F4-Discovery (STM32F429ZIT6) with HAL library? Background
Here is some of my background so that your guy could know what related knowledge I have or I don't have. I'm totally a newbie of this kind of embedded system. And I don't really know anything about electronics, I'm a pure software guy.
My only experience of embedded system is Raspberry Pi, which is quite different from STM32F4 Discovery.
I could implement a UART read / write programming by using standard Linux C library on Raspberry Pi, which is connected to a PC with an USB-to-RS232 adapter with a voltage converter IC.
My Device and development environment

*

*An STM32F429I-DISCO board with STM32F429ZIT6 MCU

*An USB-to-RS232 cable and a voltage converter IC which works quite well on Raspberry Pi.

*Keil uVision 5 IDE.

What I would like to achieve
I would like to implement a programming on STM32F429 Discovery board that could send / receive message to / from PC. (For example, send a string to PC. And when received an string from PC, light up the LED on board)
What I have done right now
Now I've setup my Keil uVision IDE, and could compile / run the blink LED example, I could also edit that example to control LED as the way I want it to be. (Ex, turn LED on when user button is pressed and turn it off when the button is released)
So the LED part is pretty much done, the missing piece it how to communicate with STM32F4 Discovery board using RS232 cable.
My Question

*

*First, I would like to know if I understand the PIN define of this board correctly. According to this datasheet, I should connect the TX pin on DB9 to PD2(UART5_RX), RX pin on DB9 to PC12(UART5_TX), VCC pin on DB9 to 3.3V, and GND on DB9 to GND. Is this connection correct?

*Is there any example code on how to use UART on new HAL library that come from the latest version of Keil uVision? I've searched on the web, but most sample code or tutorial are using a function called RCC_AHB1PeriphClockCmd which seems not exist in new HAL library that come from Keil uVision.
Update

*

*My USB-to-Serial adapter is 067b:2303 Prolific Technology, Inc. PL2303 Serial Port and attached with a level shifter IC. Looks like this:

*When connected to Raspberry Pi, I was following this instruction, so the VCC / GND on the IC is connected to 3.3V / GND on Raspberry Pi, I'm not sure if this is needed or not.

*By "HAL" library, I mean this stm32f4xx_hal_usart.c file, according to license declaration in the comments, it seems come from STMicroelectronics. Although there are some instruction in this file, it's still quite hard for me to figure out how to use this driver. For example, I can't tell the difference between Enable USARTx interface clock and Enable the clock for USART GPIOs, and I don't know how can I achieve these function. So if there is an example code, it would be a great help as I could compare it with these instructions.

A: I have pushed the Code for this answer to the following github address.
The code is trivial, answers the question, and have mainly been generated by STM-Cube. The .ioc file is also available for you to modify.
There are a number of other peripherals ready to be used, but untested including
USB VCport
Timers set for RC hobby servos, just change pulse width 500-1500
ADC  in DMA mode
SPI  for flash etc
I2C  for port expansion or whatever

I share the frustration of the OP having spent many days, weeks and months fighting to get this stuff working on both the old and new libraries. Finally in 2016 there appears to be some light from ST and I can go on to do real apps for these great boards.
In fact, in doing this task, I had to re-install my cube and all its libraries before it worked properly this may have caused anguish in others.
I'll be adding LCD and touchscreen to this 'template' to make a great little 'droidlet'.
I usually attach a bluetooth module to one of the UARTS and debug through there.
Andy Brown Andy Brown has some great C++ libraries for some of the STs. They seem to be based on the StdPeripheral libs and need to be updated so we can use them via Cube and HAL on new (and old) devices. As a community we could do this more efficiently. Any ideas and takers?
Have fun.

The canonical Solution
Update your Cube and HAL libraries to the latest
Generate a cube project
Setup all your peripherals in the dialogs
Generate code
Compile
Add your application
Test  & Debug
Optimise
Release

You need only to take care that similar peripherals on different families have inconsistencies e.g.
    ADC on F0 is different from F1 and F4.
    F3 potentially has 16 bit ADC.

You are probably doing everything correctly other than RTFM. (Read the Fineprint in the Manual)

Unless you want to fight the UART, you are better advised to implement the Virtual Comport demo which uses a standard USB cable. Let the ST be the device.
Get a copy of STCube, look in the projects/peripherals directory for USB and Virtual comport. The HAL library is the same and also has this code.
When doing work on any of the Discovery boards, fire up a copy of STM32 Cube (free from ST), and create your configuration there. It shows you what is used and what is free, a great tool and will set up USB as a bonus.
Then use the code generator to create a skeleton for KEIL project. Compile , run add your app code and :-)
you may want to look here Embitz.org they have a great IDE and even better F429iDisco examples or the ST AC6 IDE and ST page for more examples. These IDE do not have code size limits, something you will run into using the LCD, touch etc on this device.

The Rest of the Answer
Unfortunately STM have of necessity assigned most of the pins on this discovery to the LCD, touch and memory chips onboard. There is very little Async function left - they probably thought the USB would be Ok.
Q1) - The way these are normally marked you will need to 'crossover' by connecting Rx to TX and Vice versa.
Check your code by wiring 'loopback' on the UART pins and check the LEDS.
Q2) - STM Cube will generate a working Keil project for you.
There's demo code that will compile and run in
stm32cube_fw_f4_v130\STM32Cube_FW_F4_V1.3.0\Projects\STM32F429I-Discovery\Examples\UART with a Keil project (MDK-ARM). You will need to change to UART5 - it is configured for USART1 PA9(Tx) /PA10(RX), once working swap to UART5, or test locally USART1 -> UART5.
Test by connecting RX to Tx on the discovery, setup Rx then TX a string all should work and the Rxbuffer should reflect this.
Then connect to your adapter all should work., LEDS should flash.
If not, swap Tx and Rx.
Check loopback on the DB9.
If you have a modem or PC on the DB9, you will need to manage the modem control signals before any of this works. (RTC, CTS, DCD, DTR, DTE) See here. Raspberry does this for you.
Disconnect the STM from the adapter and check loopback  from the PC on the DB9 then on Tx Rx pins.
If you get this far, STM flashes one LED, remote the other, then you have a parity, baudrate or wordlength problem.

Below is for the 407 discovery ( original discovery) - apologies initially didn't see you have the 429   - we  tend to talk of F4Discovery vs F429i-Discovery. There are now other F4 based boards as well.
On F4-Discovery board - UART5 is not available, conflicts with I2S3D which is used CS43L422 (microphone) on PC12. Same pin overloading problem as the F429
The other UARTs and USART1 are also used.
Either - Configure for USART2 or USART3
The positive is USARTS 2 and 3 have built in RTS/CTS lines which you can use.
OR
You need to solder/ unsolder jumpers on the board to disable the Microphone.
I've generated many projects with USARTS on a few different STM32 boards and they all work flawlessly. The HAL programmers unfortunately only provide drivers for fixed length with or without a timeout, there is no Readline interface.


text:
Q: How to parse this comment block with PHP using a regular expression? I am having a problem in the preg_match_all() function. What would be a regular expression pattern for this type of string?
Consider this code:
$str="* Function do Something * @param String $variable1 * @param String $variable2 * @return String";

I want a pattern for preg_match to parse this string to this form of array... It separates @param and @return or @author, etc.
It should print the array like this:
array("param"=>[0]=>"String $variable1",[1]=>"String $variable2",
    "return"=>"String")

A: Have a try with this:
$str='* Function do Something * @param String $variable1 * @param String $variable2 * @return String';
$l = explode('*', $str);
$res = array();
foreach($l as $el) {
    if (preg_match("/@(\w+) (.*)$/", $el, $m)) {
        $res[$m[1]][] = $m[2];
    }
}
print_r($res);

Output:
Array
(
    [param] => Array
        (
            [0] => String $variable1
            [1] => String $variable2
        )

    [return] => Array
        (
            [0] => String
        )

)

A: Try this:
preg_match_all('/(?<=[\s])[$@\w\s]*(?=[\s"])/i', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];
// $result will be array of matches

This will match everything between those * in groups, so just kick out from array first match if you don't need function part and use the rest for parameters.
GL

A: Well, firstly the common splitting identifier is the *, so firstly I would explode by them:
$segments = explode('*', $text);

Then I see that there will be spaces because at the sides of the * we have spaces, so they need to be trimmed away, but firstly we need to set up a blank array to store the new cleaned data in.
$results = array();

Then loop through each segment, trimming and check for the @ symbol:
$first = true;
foreach($segments as $segment) {
    // Strip trailing/leading whitespace and line breaks
    $segment = trim(segment);

    if ($first === true) {
        // Name: The very first line would be the name.
        $results['name'] = $segment;
        $first = false;
    } else {
        // Params and return
        if ($segment[0] === "@") {
            // Find the first space, usually after @xxxx text
            $pos = strpos(' ', $segment);

            // Get the name of the var so param for @param
            $index = substr($segment, 1, $pos);
            // rest of the string
            $value = substr($segment, $pos+1);
            switch($index) {
                case 'param':
                case 'params':
                    $results['params'][] = $value;
                    break;
                case 'return':
                case 'returns':
                    $params['return'] = $value;
                    break;
                default:
                    $params[$index] = $value;
                    break;
            }
        }
    }
}

Hopefully you will be able to see what this code bock is doing, but if not a little explanation below.
After exploding the string into segments, we start looping through them. There's a small $first variable that is set to true as default so we know if it's the first iteration of the array, the reason being the first line is the function name and it does not have have an @ symbol to denote a named line.
After that, we check to see if the character at index 0 is equal to @. If so, then we cut out the string so that:
@param fun ...
0123456789 ...
^     ^

So that we cut from 1 to the index if the space (6) and this would give 'param'.
After creating a switch statement, we just use substr() to cut off only the part of the string after the param prefix (offset 6 in this case).
This code more than likely will not work as it's untested, but it's written to show you how to go about it. I hope it gets you going.
Some other resources:

*

*[Is there a good (standalone) PHPDoc parser class or function in PHP?][2]

*[How to parse a phpDoc style comment block with PHP?][3]
I really don't think a regular expression is the way to go, but if that's really what you want to do then [How to parse a phpDoc style comment block with PHP?][6] is the way to go.


text:
Q: Web Scraping with Selenium Python [Twitter + Instagram] I am trying to web scrape both Instagram and Twitter based on geolocation.
I can run a query search but I am having challenges in reloading the web page to to more and store the fields to data-frame.
I did find couple of examples for web scraping twitter and Instagram without API keys. But they are with respect to #tags keywords.
I am trying to scrape with respect to geo location and between old dates. so far I have come this far with writing code in python 3.X and all the latest versions of packages in anaconda.
'''
    Instagram - Components
    "id": "1478232643287060472",
     "dimensions": {"height": 1080, "width": 1080},
     "owner": {"id": "351633262"},
     "thumbnail_src": "https://instagram.fdel1-1.fna.fbcdn.net/t51.2885-15/s640x640/sh0.08/e35/17439262_973184322815940_668652714938335232_n.jpg",
     "is_video": false,
     "code": "BSDvMHOgw_4",
     "date": 1490439084,
     "taken-at=213385402"
     "display_src": "https://instagram.fdel1-1.fna.fbcdn.net/t51.2885-15/e35/17439262_973184322815940_668652714938335232_n.jpg",
     "caption": "Hakuna jambo zuri kama kumpa Mungu shukrani kwa kila jambo.. \ud83d\ude4f\ud83c\udffe\nIts weekend\n#lifeistooshorttobeunhappy\n#Godisgood \n#happysoul \ud83d\ude00",
     "comments": {"count": 42},
     "likes": {"count": 3813}},
'''

import selenium
from selenium import webdriver
#from selenium import selenium
from bs4 import BeautifulSoup
import pandas

#geotags = pd.read_csv("geocodes.csv")
#parmalink =
query = geocode%3A35.68501%2C139.7514%2C30km%20since:2016-03-01%20until:2016-03-02&f=tweets

twitterURL = 'https://twitter.com/search?q=' + query
#instaURL = "https://www.instagram.com/explore/locations/213385402/"

browser = webdriver.Firefox()
browser.get(twitterURL)
content = browser.page_source

soup = BeautifulSoup(content)
print (soup)

For Twitter Search Query I am getting syntax error
For Instagram I am not getting any error but I am not able to reload for more posts and write back to csv dataframe.
I am also trying to search with latitude and longitude search in both Twitter and Instagram.
I have a list of geo coordinates in csv I can use that input or can write a query for search.
Any way to complete the scraping with location will be appreciated.
Appreciate the help !!

A: I managed to make it work using requests. Your code would look something like this:
from bs4 import BeautifulSoup
import requests

query = "geocode%3A35.68501%2C139.7514%2C30km%20since:2016-03-01%20until:2016-03-02&f=tweets"

twitter = 'https://twitter.com/search?q=' + query

content = requests.get(twitter)
soup = BeautifulSoup(content.text)

print(soup)

Then you can use the soup object to parse what you need. The same thing should work for Instagram, if your query is correct.


text:
Q: Concatenating and sorting cols = [2,4,6,8,10,12,14,16,18] # selected the columns i want to work with
df = pd.read_csv('mywork.csv')
df1 = df.iloc[:, cols]
b= np.array(df1)
b

outcome
array([['WV5 6NY', 'RE4 9VU', 'BU4 N90', 'TU3 5RE', 'NE5 4F'],
       ['SA8 7TA', 'BA31 0PO', 'DE3 2FP', 'LR98 4TS', nan],
       ['MN0 4NU', 'RF5 5FG', 'WA3 0MN', 'EA15 8RE', 'BE1 4RE'],
       ['SB7 0ET', 'SA7 0SB', 'BT7 6NS', 'TA9 0LP' nan]], dtype=object)

a = np.concatenate(b) #concatenated to get a single array, this worked well

print(np.sort(a)) # to sort alphabetically
it gave me error **error AxisError: axis -1 is out of bounds for array of dimension 0*

I also tried using  a.sort() it is also giving me **TypeError: '<' not supported between instances of 'float' and 'str'**

The above is a CSV file containing list of postcodes of different persons which involves travelling from one postcode to another for different jobs, a person could travel to 5 postcoodes a day. using numpy array, I got list of list of postcodes.
I then concatenate the list of postcode to get one big list of postcode after which I want to sort it in an alphabetical order but it kept giving me errors.
Please, can someone help

A: As it was mentioned in the comments, this error is caused by the comparison of nan to string. To fix this, you cannot use a NumPy array (for sorting), but rather a list.

*

*Convert the array to a list

*Remove the nan values

*Sort

# Get the data (in your scenario, this would be achieved by reading from your file)
b = np.array([['WV5 6NY', 'RE4 9VU', 'BU4 N90', 'TU3 5RE', 'NE5 4F'],
       ['SA8 7TA', 'BA31 0PO', 'DE3 2FP', 'LR98 4TS', nan],
       ['MN0 4NU', 'RF5 5FG', 'WA3 0MN', 'EA15 8RE', 'BE1 4RE'],
       ['SB7 0ET', 'SA7 0SB', 'BT7 6NS', 'TA9 0LP', nan]], dtype=object)

# Flatten
a = np.concatenate(b)

# Remove nan values - they are converted to strings when concatenated
a = np.array([x for x in a if x != 'nan'])

# Finally, sort
a.sort()


text:
Q: Is it better to compress all data or compressed directories? I'm archiving some projects, let's say each of them has own directory:
projects
 |- project-1
 |- project-2
 |- project-3

I started compressing them as following:
==== SITUATION 1 ====

projects
 |- project-1.zip
 |- project-2.zip
 |- project-3.zip

and then I started wondering if wouldn't it be better to compress all data in one zip file:
==== SITUATION 2 ====

projects.zip
 |- project-1
 |- project-2
 |- project-3

or maybe compress already compressed files?:
==== SITUATION 3 ====

projects.zip
 |- project-1.zip
 |- project-2.zip
 |- project-3.zip

Which situation is the best (occupies the least space)? Why? Does it depend on compression algorithm? I know that compressing one compressed file cannot help much, but let's say 20 of them? For me situation 1 doesn't look like a good idea.

A: I doubt that the different schemes would make a lot of difference to be honest since the compression algorithms typically only look forward a limited amount in order to control memory use.
The exception is S3 which would end up larger most likely since compressing a compressed file adds overheads but cannot compress.
If you want better compression, look for newer archiving tools that have better algorithms. 7-zip for example is generally better than zip.
In terms of the difference between s1 and s2, I would say that it depends on how you are most likely to use the archive in the future and how big they end up.
Really big archives are a pain to handle (moving, opening, etc) and this is likely to be more important than saving a few kB.
Additionally, when thinking of long-term storage, don't ignore "bit-rot". A small error in a large archive can be devastating. Loosing one project is probably much better than loosing them all.
You might however look at something like RAR which allows redundancy and split archives. This is a bit like RAID5. You create multiple archive files each of which has built in redundancy so that you can loose a file and still recreate the original data.

A: First of all, keep the excellent arguments of @Julian Knight in mind. Even the best compression is useless if your archive is either too big to handle or gets corrupted by some flipped bits.
If space is your main concern, it might be worthwhile to do some experiments with your particular data and different compression algorithms.
Also, your 3rd approach can indeed lead to another reduction in size. I remember some discussion (see here) about compressing files multiple times using different algorithms. The author was compressing highly redundant text files and could go from 100GB to a few MB after experimenting enough. Note that his case was a bit special, but the general idea is that iterated compression can actually be worthwhile in some cases.
If you are willing to try different compression algorithms, here are some benchmarks that compare speed and compression ratio:

*

*http://catchchallenger.first-world.info//wiki/Quick_Benchmark:_Gzip_vs_Bzip2_vs_LZMA_vs_XZ_vs_LZ4_vs_LZO

*http://binfalse.de/2011/04/04/comparison-of-compression

A: Situation 3 is out because it's pointless re-compressing archives with the same algorithm.
Between Situations 1 and 2 the latter definitely has more chance of resulting in a smaller archive, especially when you use larger dictionary sizes (the dictionary in simple words is the memory area used to find and compress repeated patterns in data). Plain old ZIP can only use a tiny 32KB dictionary, which given the hardware these days is way too small.
The RAR 5.0 format by comparison can use a 1GB dictionary on 64-bit systems. It also supports saving identical files as references:

If this option is enabled, WinRAR analyzes the file contents before
  starting archiving. If several identical files larger than 64 KB are
  found, the first file in the set is saved as usual file and all
  following files are saved as references to this first file. It allows
  to reduce the archive size, but applies some restrictions to resulting
  archive. You must not delete or rename the first identical file in
  archive after the archive was created, because it will make extraction
  of following files using it as a reference impossible. If you modify
  the first file, following files will also have the modified contents
  after extracting. Extraction command must involve the first file to
  create following files successfully.

Thus if you have many duplicate files among your projects, a large dictionary size combined with solid archiving and the feature above is very likely to lead to significant size reduction with Situation 2. Of course all the general caveats about large archives apply, so including a recovery record would also be recommended.

A: As other said, Situation 3 is the worst of all. The first two options are roughly the same, but Situation 2 is slightly better because of some metadata (and possibly dictionary) reuse
However for archiving purposes all the above are not good because zip format doesn't support solid archives. 7z and rar do use solid archives by default (Do 7z archives compress each file individually or compress everything together as one?) so the compression ratio is much better (because you most definitely have the same byte patterns repeated in many files). It's the same way you tar (i.e. making a solid uncompressed archive) then pass to gz or bz2 to compress. OTOH zip compresses each file separately so it'll be easier to extract separate files but the compressed output would be much larger
So you should use Situation 2 but change to 7z or rar


text:
Q: What should be the input type for a UDF taking in columns of type - Array of StructType or "null"? Schema of my DataFrame is as follows:
root
 |-- col1: string (nullable = true)
 |-- col2: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- unit1: string (nullable = true)
 |    |    |-- sum(unit2): string (nullable = true)
 |    |    |-- max(unit3): string (nullable = true)
 |-- col3: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- unit1: string (nullable = true)
 |    |    |-- sum(unit2): string (nullable = true)
 |    |    |-- max(unit3): string (nullable = true)

I'm writing a UDF in scala which takes in cols - col2 and col3.
What should be my input type for each of the columns i'm passing to the UDF considering the value of col2 can be "null"
val process_stuff = udf((col2: ???, col3: ??? ) => {

So far i've tried this and my other things
val process_stuff = udf((col2:ArrayType[StructType[StructField]], col3:ArrayType[StructType[StructField]]) => {

but it gives me warnings here and there
Please help!

A: Your UDF should have the following signature :
val process_stuff = udf((col2: Seq[Row], col3: Seq[Row]) => {...})


text:
Q: How much delay does two linux commands have in between? If the first one is run with & Basically I am writing a report to convince the audience that the following Linux commands
$ a.sh &
$ b.sh &
$ c.sh &

are all started almost at the same time. I couldn't find a good explanation or reliable source to convince the audience. Is there any books or articles that specifically discussed about this? Thanks.

A: From the Bash docs

If a command is terminated by the control operator '&', the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. The shell does not wait for the command to finish, and the return status is 0 (true). When job control is not active (see Job Control), the standard input for asynchronous commands, in the absence of any explicit redirections, is redirected from /dev/null.

For more details take a look at the Bash tutorial


text:
Q: Using Jitterbit for cooperative work Our team started to work on integration Jitterbit with other our systems and we faced with such issue - how better to organize cooperative work in Jitterbit Studio on the same project for few developers? We saw that pretty often we got problems due to conflicts when we worked together on interrelated components.
Are there any approaches how we can maximally to distantiate job of our teammates in Jitterbit working on the one project? Are there any integrated abilities to fork and merge Jitterbit projects (or part of them)? Maybe, there are exists some other approaches or features?

A: I spent some time for investigating this question and designed such workflow:

*

*The team have one common project where we store all project's elements (scripts, operations, transformations etc)

*Each member has his own copy of common project where he works on his part of functionality (I didn't find how easily clone projects, so I used for this "Export/Import as Jitterpack" functionality)

*When developer want to merge his work with other's or take something from common project to his copy he use "Import Project Data" functionality.

In such case we can be sure that teammates don't affect each other and common project contains all completely implemented features together. But I see here some minuses:

*

*There is no easy way for versioning and backups of components (we can export project periodically, but IMHO its sucks).

*When we import Project data, items with same names is not updated, but each time it's created with new name, if such name already exists.

It's not critical minuses, but it may be the cause of potential errors. If someone know how better to deal with it please share your experience!


text:
Q: osmdroid and dynamic permissions in marshmallow I'm using osmdroid 5.4.1 lib in android 6.0. I'm asking WRITE_EXTERNAL_STORAGE and ACCESS_COARSE / FINE_LOCATION permissions on realtime.
But map not working:
Unable to decode stream: java.io.FileNotFoundException: ... open failed: EACCES (Permission denied)
onRequestPermissionsResult() of the my main Activity calls the following after the user has granted the storage write permission:
public void initTileSources() {
    mMapnikTileSource = new XYTileSource(MAPDIR_MAPNIK, 1, MAXZOOMLEVEL, 256, ".png", new String[]{"http://tile.openstreetmap.de/",
            "http://tile.openstreetmap.org/"});
    mMapView.setTileSource(mMapnikTileSource);

    mSeamarksTileSource = new XYTileSource(MAPDIR_SEAMARK, 1, MAXZOOMLEVEL, 256, ".png", new String[]{
            "http://t1.openseamap.org/seamark/", "http://tiles.openseamap.org/seamark/"});
    TilesOverlay SeamarksOverlay = new TilesOverlay(new MapTileProviderBasic(getActivity(), mSeamarksTileSource), getActivity());
    SeamarksOverlay.setLoadingBackgroundColor(Color.TRANSPARENT);
    mMapView.getOverlays().add(SeamarksOverlay);
    // mMapView.invalidate();
}

The mapview only displays the SeamarksOverlay (openseamap) but not the main mMapnikTileSource (openstreetmap). I have to restart the app in order for the mapview to display everything correctly.
I have seen a similar question on stackoverflow but it hasn't been answered.
Can anyone help me? Thanks in advance.

A: I'll give you the same answer as the other linked issue. You have to ask for the permissions before the mapview is loaded and displayed.
Either that, or the path for the tile storage cache is read only. On some android devices Environment.getExternalStorageDir returns a read only partition. No clue why, but that will definitely cause issues. It can be overridden with the class OpenStreetMapTileProviderConstants


text:
Q: Looping through stream data I'm writing a program that uses a fingerprint reader. I have stored the fingerprint data in an array [arr]. Unfortunately, only the first value is read i.e [0]. So only one finger is detected and the rest are ignored but if I place a specific number in the array e.g 2. It works fine for that value alone:
Here's my code:
for (int x = 0; x < (arr.Length - 1); x++)
        {
            byte[] fpbyte = GetStringToBytes(arr[x]);
            Stream stream = new MemoryStream(fpbyte);
            Data.Templates[x] = new DPFP.Template(stream);
        }
        foreach (DPFP.Template template in Data.Templates)
        {
            // Get template from storage.
            if (template != null)
            {
                // Compare feature set with particular template.
                ver.Verify(FeatureSet, template, ref res);
                Data.IsFeatureSetMatched = res.Verified;
                Data.FalseAcceptRate = res.FARAchieved;
                if (res.Verified)
                    MessageBox.Show("Yes");
                break; // success
            }
        }

        if (!res.Verified)
            Status = DPFP.Gui.EventHandlerStatus.Failure;
        MessageBox.Show("No");

        Data.Update();

A: You unconditionally break from your loop, whether verified or not.
Your code should read :
  if (res.Verified) {
     MessageBox.Show("Yes");
     break; // success
  }

This is a good example why good coding practice suggests always having the brackets, even for a one line conditional effect, as the error would have been much more obvious.
Similarly you should have written
 if (!res.Verified) {
     Status = DPFP.Gui.EventHandlerStatus.Failure;
     MessageBox.Show("No");
 }

at the end of your snippet.

A: Thanks to Dragonthoughts, I made the following changes and the code works just fine:
for (int x = 0; x < (arr.Length - 1); x++)
        {
            byte[] fpbyte = GetStringToBytes(arr[x]);
            using (Stream stream = new MemoryStream(fpbyte))
            {
                Data.Templates[x] = new DPFP.Template(stream);
                // Get template from storage.
                if (Data.Templates[x] != null)
                {
                    // Compare feature set with particular template.
                    ver.Verify(FeatureSet, Data.Templates[x], ref res);
                    Data.IsFeatureSetMatched = res.Verified;
                    Data.FalseAcceptRate = res.FARAchieved;
                    if (res.Verified)
                    {
                        status.Text = "Verified";
                        break; // success
                    }

                }

            }
        }
        if (!res.Verified)
        {
            Status = DPFP.Gui.EventHandlerStatus.Failure;
            status.Text = "Unverified";
        }
        Data.Update();


text:
Q: Is there a way i can reuse this code in C# Is there a way i can reuse this codes in executing SQL transaction, i want to make it a method so i can put parameters to execute other stored procedures,
can you guys help me to design a good coding structure?
 try {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand("InsertUser2Sp", con) {
                    CommandType = CommandType.StoredProcedure
                }) {
                    cmd.Parameters.AddWithValue("@UserID", useridStr);
                    cmd.Parameters.AddWithValue("@Firstname", firstnStr);
                    cmd.Parameters.AddWithValue("@Middlename", middleNstr);
                    cmd.Parameters.AddWithValue("@Lastname", lastnStr);
                    cmd.Parameters.AddWithValue("@UserAge", ageInt);
                    cmd.Parameters.AddWithValue("@HomeAddress", homeaddStr);

                    con.Open();
                    cmd.ExecuteNonQuery();
                }
            }
        } catch (Exception ex) {
            MessageBox.Show("Could not connect to database. Check settings. " + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            MessageBox.Show(ex.Message);
        }
    }

A: I will share a generic method here . All you need to do is to build an object with the same property names (including cases) same with the parameters in your SP.
protected internal string GetSingleValue_String(String spname, Object entity)
        {
            Object res = new Object();
            String conString = String.Empty;
            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                con.Open();
                SqlCommand cmd = new SqlCommand(spname, con);
                cmd.CommandType = CommandType.StoredProcedure;
                if (entity != null)
                {
                    SqlCommandBuilder.DeriveParameters(cmd);
                    PropertyInfo entitymember = default(PropertyInfo);
                    foreach (SqlParameter _param in cmd.Parameters)
                    {
                        if (_param.Direction == ParameterDirection.Input)
                        {
                            entitymember = entity.GetType().GetProperty(_param.ParameterName.Replace("@", ""));
                            var entityValue = entitymember.GetValue(entity, null);
                            String _paramvalue = entityValue != null ? entityValue.ToString() : null;
                            _param.Value = (string.IsNullOrEmpty(_paramvalue) || _paramvalue == string.Empty ? null : _paramvalue);
                        }
                    }
                }
                res = cmd.ExecuteScalar();
                cmd.Connection.Close();
                entity = null;
                cmd = null;
                if(res==null)
                    res = "";
                else if (String.IsNullOrEmpty(res.ToString()))
                    res = "";
                return res.ToString();
            }
        }

So in your example, create a new class that have the same definition as your SP parameters.
class NewClass()
{
    public string UserID { get; set; }
    public string Firstname { get; set; }
    public string Middlename { get; set; }
    public string Lastname { get; set; }
    public string UserAge { get; set; }
    public string HomeAddress { get; set; }
}

And will call the method like this.
var newClass = new NewClass
{
    UserID = "UserId",
    Firstname = "Firstname",
    Middlename = "Middlename",
    Lastname = "Lastname",
    UserAge = "UserAge",
    HomeAddress = "HomeAddress"
}

var res = GetSingleValue_String("InsertUser2Sp", newClass);

Don'd mind the return type.


text:
Q: How to multiply value's occurence time by the key to get the new value? The goal:
I want to coune the letters in a sentence, and pprint it as a dictionary, where the value is the occurence of the letters in the sentence, not just its time.

import pprint
from collections import Counter

get_the_sentence = input()

# Now scatter the sentence into different letters.

# First remove the period.

get_the_sentence = get_the_sentence.replace(".","")

# Second make all the letters its lower case.

get_the_sentence.lower()

# Third scatter the sentence.

get_the_sentence = list(get_the_sentence)

# Now Counter it, then make the Counter a dict.

Counter_the_letter = Counter(get_the_sentence)

Counter_the_letter = dict(Counter_the_letter)

# Then make the final result.

for letter , time in Counter_the_letter:
time = letter*time

pprint(Counter_the_letter)

However I get the Error:

python -u "d:\\新建文件夹 (3)\\python_module\\poor_man_bar_chart.py"
Traceback (most recent call last):
File "d:\\新建文件夹 (3)\\python_module\\poor_man_bar_chart.py", line 28, in \<module\>
for letter , time in Counter_the_letter:
ValueError: not enough values to unpack (expected 2, got 1)
PS C:\\Users\\Babe\>

And if I change the

for letter , time in Counter_the_letter

to

for letter , time in Counter_the_letter():

Which is Add one more brackets。
then the Error would become:

Traceback (most recent call last):
File "d:\\新建文件夹 (3)\\python_module\\poor_man_bar_chart.py", line 28, in \<module\>
for letter , time in Counter_the_letter():
TypeError: 'dict' object is not callable
PS C:\\Users\\Babe\>

by the way I didn't name other variables as dict before.
I wonder what the Error means, an how I can fix it.
My python version is Python 3.10.5.

A:
ValueError: not enough values to unpack (expected 2, got 1)

If you want to iterate over key-value pairs of a dictionay, you should use
for key, value in some_dict.items():
   print(key, value)

In your case, you are trying to iterate over only keys, which cannot be unpacked to two variables (letter and time).

TypeError: 'dict' object is not callable

This means you are trying to call a dict object, which is not callable.

You can further simplify your code.

*

*Omit the type conversion from str to list.

*Omit the type conversion from Counter to dict.
How to do this without using extra modules:
input_string = "absdav"
unique_chars = set(input_string)  # keys of the expected dict
expected_dict = { ch: input_string.count(ch) for ch in unique_chars }

Here, str.count is used to count each unique char in the input string and dict comprehension is used to construct a dictionary.


text:
Q: Running ms sql local db express I installed Microsoft SQL Server Express localDB. Now I want to run it, and according to this tutorial:
https://www.mssqltips.com/sqlservertip/2694/getting-started-with-sql-server-2012-express-localdb/
I run (in cmd line):
SqlLocalDb info

then I get in cmd line: SqlLocalDb is not recognized as an internal or external command
How to fix it? Probbaly I have to add somethink to PATH variable?

A: It's strange that the installer didn't add it to your PATH already, but ignoring that - can you go to your C:\Program Files (might be in the x86 folder as well), find where the program was installed, and look for "SqlLocalDb.exe"? This is what would be executed when you run SqlLocalDb from the command line.
If you find it, open the command line at that location and try to run that command. (Tip: You can hold Shift and right click in the empty space in that window, and the right-click menu will contain "Open command window here".)
If that works, you can add that location to your PATH so that you don't have to be in that folder or specify the location.

A: I had the same problem, and the reason was I had SQL Server Management Studio, but I didn´t have installed the SQL Server.
I downloaded it from the Microsoft website and worked just fine. This is the Spanish version: https://www.microsoft.com/es-mx/sql-server/sql-server-downloads

A: I had this issue and installing Microsoft SQL Server Express Localdb seemed to have fixed it.
Tutorial here: https://www.mssqltips.com/sqlservertip/5612/getting-started-with-sql-server-2017-express-localdb/

A: restart your computer, it worked like that for me.


text:
Q: Using Empty function in mocha.js Am new to Javascript ,node.js and mocha. as i was looking to basic example i encountered an empty function "function()". What's the ppurpose of using empty function.
var assert = require('assert'),
var test = require('selenium-webdriver/testing'),
var webdriver = require('selenium-webdriver');

test.describe('Google Search', function() {
  test.it('should work', function() {
    var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.chrome()).
    build();

    driver.get('http://www.google.com');
    var searchBox = driver.findElement(webdriver.By.name('q'));
    searchBox.sendKeys('simple programmer');
    searchBox.getAttribute('value').then(function(value) {
      assert.equal(value, 'simple programmer');
    });
    driver.quit();
    done();
  });
});

when i run this sample code  i got below error , can u please help me resolving this issue please .
error :
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
as i see am able to launch browser and open google.com as writted in program  but i see fail still
Google Search
   1) should work
0 passing (2s)
 1 failing
1) Google Search should work:
    Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
     at null. (C:\Users\kashyap\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:170:19)
     at Timer.listOnTimeout (timers.js:110:15)
can you please also suggest me some links to know and try mocha+nodejs with selenium

A: Your function are not empty. In fact, in javascript, there are 2 ways to define a function :
function myFunction (arg1, arg2){
    //Do some stuff
}

or
var myFunction = function(arg1, arg2){
    //Do some stuff
}

In both cases, the function is stored in the variable called "my function" (with different scopes, though).
So basically, in javascript, a function is a value. You may draw a parallel with functional pointers in c, to understand the way it works.
Now, what mocha does, is getting the test process as a parameter of the function describe, and the test itself as a parameter of the function it (you can set initiliazing/cleaning processes with before/afer functions as well).
We can now see what the "done" function is. The done function (you can give it the name you want, done is just the most common name) is the function you should call when your test is over. It's given as a parameter of the function that defines the process you're in. Quick example :
it('should work', function(done){
    //do some testing
    done();
});

does the same thing as :
it('should work', function(){
    //do some testing
});

But where that parameter is useful is when you're testing asynchronous functions. For example, I want to test a query in a database, which is not instant.
it("should work", function(){
    dbDriver.get('key1', function(data){
        assert(data == goodValue);
    });
});

The previous example will not work properly, cause the db request is not instantaneous and is an asynchronous call, which mean that my test will keep running, and my assertion will happen after we left the test section. So mocha will think that everything was ok, and then will ignore my assertion afterwards.
To allow asynchronous function testing, mocha designed the done parameter, which makes the test to keep on running while the parameter function is not called, so, if I want my test to run correctly, I have to do it like this :
it("should work", function(done){
    dbDriver.get('key1', function(data){
        assert(data == goodValue);
        done();
    });
});

Now, mocha will be stuck in this test while the done function is not called. And, it will be called once the callback of the get function is called and the assertion is made.
Now, let's look at the code. First of all, your call to done is uncalled (...) for. Done is not given as a parameter of any of your callbacks, so it should be undefined, and, if that line was executed, you would simply get a syntax error.
Now, basically, what's happening in your code is that a function doesn't respond fast enough, so mocha considers that the test has timed out (default value is 2000 ms).
Basically, you should start testing adding the function one by one in your process to check which one is timing out, to then be able to reduce your problem to the timed out function only.
If you want to learn mocha, the official website of the framework is pretty good : http://mochajs.org/, and presents some good practice (like using before and after).
I hope I wasn't too long and that I could help you understanding mocha and javascript better.


text:
Q: Good shared hosting for sending newsletter? I am running a phplist on Joyent (TextDrive).
They announced that they sold that service to another company.
As I am not sure about the new company, I need to move my account to some other hosting company.
Can you recommend a shared hosting company that I can use?
I need to send newsletter to subscribers (they are not spams. about 500 members).
Most shared hosting servers have limit in sending mail (100 per hour or so).
Thanks.
Sam

A: You might look into MailChimp if your hosting needs are limited to sending e-mail newsletters.  They have a plan for $10/mo for up to 500 subscribers (next level up from that is $30/mo).  They've been around for a long time and are very reputable and maintain relationships with ISPs and major e-mail providers to help your messages get delivered better than most people can from a leased virtual server or shared hosting account.


text:
Q: Limit Spring Boot WebMvcConfigurer to specified paths only I would like to configure asynchronous processing support for a subset of request mappings in my Spring Boot application which match /async/*. Examples:

*

*localhost:8080/async/downloadLargeFile

*localhost:8080/async/longRunningRask
Taking the first example, I have implemented my method as follows using StreamingResponseBody:
@GetMapping
public ResponseEntity<StreamingResponseBody> downloadLargeFile() throws IOException {
    long size = Files.size(path);
    InputStream inputStream = Files.newInputStream(path);
    return ResponseEntity.ok()
        .contentLength(size)
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=large_file.txt")
        .body(inputStream::transferTo);
}

In the documentation for StreamingResponseBody, it states I should be configuring an AsyncTaskExecutor, so I have this @Configuration class which implements WebMvcConfigurer as well:
@Configuration
public class AsyncConfigurer implements WebMvcConfigurer {

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(-1);
        configurer.setTaskExecutor(asyncTaskExecutor());
    }

    @Bean
    public AsyncTaskExecutor asyncTaskExecutor() {
        return new SimpleAsyncTaskExecutor("async");
    }
}

However, I cannot find a way to use this task executor only with requests that match a given pattern.
As a more general question - how do I restrict the WebMvcConfigurer to apply only to a subset of requests matching a pattern?
If this is not possible or not recommended, what is the proper way to accomplish the same behaviour?

A: The TaskExecutor when configured for/with the WebMvcConfigurer on the AsyncSupportConfigurer will solely be used for async processing of web requests. All other requests are handled by the default request handling threads as available on your servlet container.
The async nature is defined by the return type of your method. The async types are described in the MVC Async part of the Spring Reference guide.


text:
Q: How to persist from multiple forms with one button? I have two forms, an one button.
<h:form>
    <h:outputLabel value="Form Name: *" />
    <p:inputText required="true" value="#{currentTemplate.name}" />
</h:form>

and one button in another form.
<h:form id="orderListForm">
    <p:commandButton value="Submit"
    action="#{orderListBean.callPersist}" style="margin-top:5px"
    id="btnCitySubmit" />
</h:form>

I want to save the value from the first form with the second.
I really appreciate your answer!

A: Do you want to execute all inputs in both forms? Then process="@all" attribute of <p:commandButton> is for you. It will process all inputs within a page.
Alternatively, you can specify ids of components to be processed, like process="@form :another-form", if to-be-updated form has id="another-form" specified.


text:
Q: the footer is not displaying correctly on the page I have a problem with my footer. I made one and is not staying on the bottom of the page.
You can see below that is staying somewhere on the middle of the page..
The footer must stay at the bottom of the page and the content "test" as in this example must stay on top.
I've tried using  and same thing happend.
How can I fix this problem?

@import url(https://fonts.googleapis.com/css2?family=Cairo:wght@200;300;400;600;700;900&display=swap);
@import url(https://fonts.googleapis.com/css2?family=Signika:wght@300&display=swap);
@import url(https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap);

:root {
    --main-color: #4D6275;
    --second-color: #3F5060;

    --body-bg: #2E3841;
    --box-bg: #272F37;

    --text-color: #D5D5D5;
    --grey-color: #B2B2B2;
    --simple-color: #C3C3C3;

    --content-height: 92px;
    --space-top: 30px;
}

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body {
    background-color: var(--body-bg);
    color: var(--text-color);
}

a {
    text-decoration: none !important;
}

button:focus {
    outline: none;
}

.wrapper {
    position: relative;
    width: auto;
    height: 100vh;
    padding: 15px;
    font-size: 1.1em;
    top: 0;
}

.content-wrapper {
    margin-top: 20px;
    margin-bottom: 10px;
    margin-left: 20px;
}

.main-footer {
    position: relative;
    padding: 10px 10px 0px 10px;
    bottom: 0;
    width: 100%;
    background-color: red;
}

.copyright {
    float: right;
}

        test

        test

        test
test
test

        test

        test

        test

        test

        test

        test
test

        test

        test

        test

        test

        test

        test

        test

        test

        test

        test

        test

        test
test

        test

        test

        test

        test

        test

        test

        test

          DMCA | Contact

      © netview.com 2019-2021 - all rights reserved.

A: change the height of the .wrapper class

@import url(https://fonts.googleapis.com/css2?family=Cairo:wght@200;300;400;600;700;900&display=swap);
@import url(https://fonts.googleapis.com/css2?family=Signika:wght@300&display=swap);
@import url(https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap);

:root {
    --main-color: #4D6275;
    --second-color: #3F5060;

    --body-bg: #2E3841;
    --box-bg: #272F37;

    --text-color: #D5D5D5;
    --grey-color: #B2B2B2;
    --simple-color: #C3C3C3;

    --content-height: 92px;
    --space-top: 30px;
}

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

body {
    background-color: var(--body-bg);
    color: var(--text-color);
}

a {
    text-decoration: none !important;
}

button:focus {
    outline: none;
}

.wrapper {
    position: relative;
    width: auto;
    height: 100%;
    padding: 15px;
    font-size: 1.1em;
    top: 0;
}

.content-wrapper {
    margin-top: 20px;
    margin-bottom: 10px;
    margin-left: 20px;
}

.main-footer {
    position: relative;
    padding: 10px 10px 0px 10px;
    bottom: 0;
    width: 100%;
    background-color: red;
}

.copyright {
    float: right;
}

        test

        test

        test
test
test

        test

        test

        test

        test

        test

        test
test

        test

        test

        test

        test

        test

        test

        test

        test

        test

        test

        test

        test
test

        test

        test

        test

        test

        test

        test

        test

          DMCA | Contact

      © netview.com 2019-2021 - all rights reserved.


text:
Q: Accessing another activity's layout Android Well my question may be a bit immature but I'm really wandering about it.
How can I access the layout of activity A from the class of activity B. i.e I want to change the image in xml file of Activity A from activity B.
Is it possible? Kindly help.

A: You don't need to do it in such a way. I suggest you to look at the startActivityForResult. Start Activity B, do all the needed work there and once you are done, you'll be returned to the Activity A and considering the data you get at the onActivityResult, you can change the image at the content view of Activity A

A: No you can't access views of one Activity in another. You can Navigate to another Activity and change the image there.
You set a layout for each Activity and Each Activity has a life cycle.

A: You Can't modify A's Image at a running time becasuse A will be in pause mode when B is in front. You need to startActivityForResult();(A ----> B); And in ActivityForResult() method you need to right your Handler logic  to change the Image.
In B activity finished you need to set the Result.


text:
Q: Is there a way to test if a variable in Go is a natural number using only the main package? I am trying to detect if a variable y is a natural number without resorting to extra packages. Is this possible? For example, I am trying to print a message if it is a non-natural number but do not know what to put in EXPRESSION below. Is there a simple solution for this? Thanks.
package main
import "fmt"

var y = -2.3

func main() {
  if (EXPRESSION){
    fmt.Println("non-natural number!")
  }
}

A: as @voker mentions, y <= 0 || float64(int(y)) != y should do the job.

A: Following condition should work fine

 1. y * -1 >= 0
 2. y <= 0


text:
Q: In discord.py, How do I make a profanity filter This is what I have at the moment
and when I test it by typing a bad word in the list nothing happens. Why is this and what can code I use to fix it?
infractions = {}
limit = 5
blacklist = ['bad words go here']
@bot.event
async def on_message(message):
    content = message.content.lower()
    if any(word in content for word in blacklist):
        id = message.author.id
        infractions[id] = infractions.get(id, 0) + 1
        if infractions[id] >= limit:
            await bot.kick(message.author)
        else:
            warning = f"{message.author.mention} this is your {infractions[id]} warning"
            await bot.send_message(message.channel, warning)
    await bot.process_commands(message)

A: your problem is that you are using an old version/tutorial of discord.py. Things like bot.send_message are out of date and things like bot.kick don't even exist.
The ideal code would be™:
infractions = {}
limit = 5
blacklist = ['old', 'version', 'of', 'discord', '.', 'py']

@bot.event
async def on_message(message):
    content = message.content.replace(' ', '')

    if any(word in content.lower() for word in blacklist):
        id = message.author.id
        infractions[id] = infractions.get(id, 0) + 1

        if infractions[id] >= limit:
            await message.author.kick()
        else:
            warning = f"{message.author.mention} this is your {infractions[id]} warning"
            await message.channel.send(warning)
    await bot.process_commands(message)


text:
Q: compare td value and set rank dynamically Values in td are generated from PHP, now requirement is to compare these values and set rank such as ('1,2,3...') based on value, dynamically using jquery. For example I have set static rank 1 for highest values in following snippet. But I can't figure it out - how to loop dynamically and set rank through jquery

$(document).ready(function(){
  var high = Math.max.apply(Math, $('.rank').map(function(){
    return $(this).text()
  }))
  $('.rank').each(function(){
    var mark = $(this).text();
    if(mark == high){
      $(this).find('span#rank').text(' (1)');
    }
  });
})

        Student
        Total

        John
        20

        Jack
        40

A: First of all id needs to be unique in the document. To get the rank:

*

*Get all the ranks and store them in an array

*Sort this array in ascending order

*Re-iterate on .rank and get the index of the current rank in the previous array

*This will be your absolute rank.

let allRanks = [];
$('.rank').each(function(){
    allRanks.push( +$(this).text() );
})
allRanks.sort();

$(".rank").each(function(){
  let rankVal = +$(this).text();
  let rank = allRanks.indexOf(rankVal)+1;
  $(this).find(".innerrank").html(" ("+rank+")")

})

        Student
        Total

        John
        20

        Jack
        40

        Jack
        30

PS: You might need to handle the case when multiple rank values are same.

A: You can create an array with numbers in rank divs, then sort it and iterate. while iterating, find rank divs containing number and put rank as index + 1.
See below code

$(document).ready(function(){
  var arr = new Array();
  $('.rank').each(function(){
    arr.push($(this).text());
  });
  arr.sort();
  $.each(arr, function( index, value ) {
    $('.rank:contains(' + value + ')').find('span.rankNumber').html(index+1);
  });
})

        Student
        Total

        John
        20

        Jack
        40