text:
Q: My Bubble Sort won't work I had a programming assignment given to me to recreate sorting algorithms, well they all seem to do just fine except my Bubble Sort. I have been looking at this code and I just cannot seem to figure it out. I'm hoping you guys can see where I am going wrong. In the book I'm given the psuedocode:
BubbleSort(list,N)
//list is the elements to be put in order
// N is the number of elements in the list
numberOfPairs = N
swappedElements = true
while(swappedElements) do
  numberOfPairs = numberOfPairs-1
  swappedElements = false
  for(i = 1 to numberOfPairs) then
    if(list[i] >list[i+1])then
      swap(list[i], list[i+1]
      swappedElements = true
    end if
  end for
end while

ok so thats what I'm given. So then I create this class:
public class Bubble_Sort {

    private int[] unsorted;
    private int number;
    private int compareCount = 0;
    private int swapCount = 0;
    private boolean swap = true;

    public void sort(int[] unsorted) {
        this.unsorted = unsorted;
        while (swap) {
            swap = false;

            for (int j = 1; j <= unsorted.length - 1; j++) {
                if (unsorted[j - 1] < unsorted[j]) {
                    compareCount++;
                    swap(j - 1, j);

                    swap = true;
                }
            }
        }
    }

    private void swap(int i, int j) {
        swapCount++;
        int num = unsorted[i];
        unsorted[i] = unsorted[j];
        unsorted[j] = num;
    }

}

This is what it outputs for some random array from 0 to 600:
Unsorted List: [217, 207, 169, 124, 409, 304, 370, 232, 179, 409, 447, 134, 579, 228, 216, 452, 171, 55, 544, 518, 197, 10, 44, 416, 394, 161, 573, 399, 5, 394, 424, 303, 368, 508, 9, 178, 372, 296, 289, 391, 255, 386, 50, 491, 450, 329, 114, 405, 113, 512, 175, 206, 341, 586, 255, 216, 539, 258, 325, 94, 520, 412, 278, 550, 508, 147, 517, 416, 73, 275, 431, 77, 350, 457, 5, 551, 292, 573, 582, 421, 575, 178, 108, 598, 493, 171, 484, 160, 597, 73, 516, 200, 95, 30, 577, 475, 360, 586, 86, 198, 128, 598, 305, 203, 208, 442, 49, 280, 502, 433, 48, 254, 526, 185, 540, 324, 319, 47, 346, 251, 374, 10, 65, 105, 240, 105, 19, 449, 538, 13, 521, 562, 100, 93, 361, 500, 341, 333, 85, 398, 98, 92, 504, 5, 521, 7, 281, 509, 224, 54, 444, 537, 26, 102, 250, 105, 566, 126, 109, 566, 521, 58, 29, 335, 467, 320, 470, 70, 182, 300, 557, 169, 66, 379, 181, 567, 443, 347, 321, 50, 85, 223, 30, 251, 390, 390, 66, 173, 112, 336, 9, 265, 373, 57, 165, 197, 533, 376, 368, 494, 596, 235, 586, 154, 266, 466, 171, 15, 400, 174, 352, 58, 548, 156, 217, 84, 475, 244, 128, 80, 22, 400, 535, 491, 210, 461, 321, 284, 93, 251, 234, 80, 540, 56, 445, 303, 84, 515, 403, 345, 575, 515, 231, 38, 263, 358, 137, 411, 486, 245, 127, 269, 373, 23, 508, 14, 427, 404, 173, 355, 49, 137, 233, 268, 467, 160, 593, 7, 432, 268, 563, 566, 17, 588, 398, 227, 474, 122, 457, 279, 215, 2, 36, 479, 152, 323, 453, 294, 264, 214, 471, 97, 175, 484, 200, 188, 489, 218, 255, 96, 502, 196, 576, 145, 389, 96, 49, 479, 161, 355, 440, 124, 569, 336, 262, 314, 381, 545, 445, 299, 131, 474, 383, 187, 28, 404, 76, 358, 481, 528, 351, 181, 68, 389, 23, 191, 261, 457, 247, 496, 329, 566, 554, 460, 458, 201, 156, 568, 197, 335, 515, 470, 474, 38, 386, 502, 18, 432, 497, 542, 343, 519, 575, 357, 136, 203, 114, 5, 364, 201, 593, 218, 45, 192, 434, 102, 423, 360, 266, 499, 279, 358, 589, 236, 200, 195, 510, 278, 219, 31, 527, 151, 407, 396, 228, 46, 150, 452, 421, 363, 575, 102, 247, 357, 430, 86, 596, 544, 427, 11, 542, 45, 421, 65, 596, 482, 47, 576, 533, 220, 534, 50, 347, 597, 195, 544, 398, 0, 139, 355, 542, 362, 70, 68, 288, 78, 399, 542, 96, 295, 179, 164, 490, 404, 266, 415, 113, 165, 105, 26, 319, 566, 412, 527, 492, 599, 329, 477, 288, 242, 27, 31, 130, 410, 20, 380, 239, 239, 350, 85, 343, 146, 226, 564, 81, 553, 177, 146, 563, 280, 483, 8, 315, 488, 509, 451, 36, 34, 386, 342, 299, 570, 275, 137, 267, 568, 432, 78, 132, 172, 1, 394, 59, 210, 181, 368, 204, 519, 468, 588, 367, 175, 338, 375, 392, 63, 306, 65, 327, 343, 511, 163, 458, 597, 291, 472, 187, 239, 151, 302, 325, 21, 587, 590, 593, 94, 108, 171, 269, 5, 178, 439, 440, 19, 37, 74, 36, 574, 71, 326, 477, 281, 173, 448, 201, 557, 580, 512, 151, 412, 599, 576, 270, 225, 589, 67, 579, 431, 256, 581, 168, 158, 202, 281, 244, 419, 484, 417, 496, 173, 576, 109, 198, 227, 70, 537, 99, 445, 245, 110, 269, 51, 79, 50, 431, 554, 34, 270, 351, 354]

BUBBLESORT TEST at 600:
sorted List: [173, 341, 299, 439, 237, 67, 411, 592, 468, 286, 272, 404, 490, 52, 353, 317, 101, 299, 517, 571, 468, 226, 423, 153, 195, 416, 93, 432, 536, 536, 313, 292, 361, 578, 596, 275, 462, 472, 410, 227, 129, 560, 316, 11, 138, 27, 465, 575, 516, 184, 450, 454, 45, 34, 594, 247, 352, 294, 507, 552, 77, 331, 88, 234, 121, 323, 333, 378, 245, 394, 470, 207, 464, 473, 598, 73, 380, 583, 185, 79, 590, 412, 272, 57, 266, 520, 252, 236, 228, 400, 21, 195, 6, 273, 162, 292, 494, 80, 172, 532, 565, 547, 64, 559, 387, 516, 56, 395, 388, 62, 206, 397, 188, 230, 289, 567, 333, 416, 180, 343, 381, 118, 99, 224, 528, 109, 52, 62, 472, 486, 564, 262, 481, 350, 198, 536, 422, 4, 150, 183, 155, 384, 449, 438, 373, 505, 336, 476, 439, 491, 462, 184, 468, 135, 212, 366, 429, 289, 411, 338, 371, 71, 516, 158, 448, 578, 26, 342, 567, 427, 520, 158, 108, 277, 168, 152, 547, 56, 127, 292, 68, 578, 465, 265, 483, 165, 474, 502, 65, 370, 507, 594, 561, 362, 119, 354, 386, 165, 219, 594, 107, 540, 201, 22, 263, 71, 4, 194, 562, 531, 347, 183, 34, 347, 190, 24, 342, 415, 227, 307, 287, 584, 54, 217, 335, 336, 217, 355, 304, 347, 476, 154, 577, 6, 176, 268, 129, 27, 588, 530, 564, 38, 304, 183, 480, 228, 555, 234, 229, 200, 377, 239, 328, 547, 588, 494, 542, 27, 431, 213, 464, 568, 198, 91, 477, 187, 94, 553, 569, 30, 93, 399, 395, 128, 525, 545, 218, 87, 243, 143, 474, 317, 476, 278, 32, 519, 398, 138, 355, 84, 331, 55, 503, 521, 497, 4, 333, 288, 522, 6, 404, 20, 343, 214, 345, 320, 102, 440, 427, 447, 489, 171, 400, 154, 162, 18, 438, 419, 403, 580, 205, 271, 156, 362, 501, 554, 364, 498, 108, 253, 560, 94, 372, 584, 461, 28, 249, 588, 194, 414, 95, 266, 422, 559, 306, 367, 137, 103, 308, 183, 581, 597, 47, 524, 493, 592, 403, 415, 191, 397, 372, 202, 402, 438, 33, 86, 274, 538, 543, 385, 467, 183, 13, 259, 357, 160, 7, 291, 310, 223, 12, 278, 151, 97, 196, 360, 292, 360, 183, 553, 27, 121, 8, 27, 439, 177, 225, 361, 272, 47, 460, 227, 500, 192, 322, 370, 437, 190, 521, 311, 475, 245, 161, 563, 294, 451, 492, 227, 444, 165, 172, 565, 404, 405, 77, 336, 527, 82, 274, 544, 502, 566, 584, 422, 126, 314, 4, 399, 21, 319, 507, 180, 550, 309, 386, 500, 440, 179, 235, 13, 298, 467, 316, 198, 296, 568, 34, 541, 593, 21, 150, 64, 231, 280, 147, 550, 530, 502, 131, 175, 229, 322, 55, 483, 360, 466, 70, 115, 93, 381, 55, 100, 341, 313, 208, 494, 39, 535, 89, 108, 194, 175, 371, 574, 145, 553, 482, 296, 103, 392, 53, 482, 29, 70, 421, 60, 174, 467, 431, 511, 209, 122, 337, 167, 213, 317, 444, 294, 197, 12, 118, 543, 31, 2, 262, 241, 503, 483, 224, 426, 30, 256, 348, 528, 284, 278, 321, 171, 187, 304, 153, 328, 526, 364, 402, 550, 484, 382, 555, 83, 577, 200, 530, 337, 4, 348, 563, 182, 40, 17, 258, 319, 445, 301, 513, 373, 138, 404, 159, 413, 158, 298, 171, 157, 41, 252, 226, 143, 373, 584, 68, 589, 595, 271, 277, 262, 425, 318, 184, 250, 425, 206, 422, 449, 324, 123, 410, 504, 159, 288]

So then I run through different sized arrays, my original problem was fixed thanks to @Mihnea DB but now It won't sort passed the first iteration.
  Bubble_Sort reBubble = new Bubble_Sort();
  int[] bubbleArray;
 for(int N = 100; N<1100; N+=100)
      {
     bubbleArray = new int[N];
        for(int i = 0; i<N; i++)
        {
        bubbleArray[i] = (int)(Math.random()*N);
        }
        System.out.println("BUBBLESORT TEST at " + N);
        reBubble.sort(bubbleArray);
        System.out.println("sorted List: "+ Arrays.toString(bubbleArray));
         }

thanks for all your help!

A: Since you are using the smaller than (<) comparison operator, you want to walk the array from the end towards the beginning.
I suggest you run your code step by step on this array:
[3, 2, 4, 5, 1, 0, 2]

After every for iteration you have:
[3, 4, 5, 2, 1, 0, 2]
[4, 5, 3, 2, 1, 0, 2]
[5, 4, 3, 2, 1, 0, 2]
[5, 4, 3, 2, 1, 0, 2]

As you can see, the last 2 is misplaced because your assertion (a[i-1] < a[i]) still holds.
Later edit: If you plan on reusing an instance of the class you should perform the initialisation of swap = true inside the sort function.

A: public void sort(int[] unsorted)
{
    for(int i=0; i < unsorted.length, i++) {
        for(int j=0; j<unsorted.length-1; j++)
        {
            if(unsorted[j+1]<unsorted[j]) {
                swap(j-1,j);
            }
        }
     }
}

A: change this :
if(unsorted[j-1]<unsorted[j])

to
if(unsorted[j-1] > unsorted[j])


text:
Q: Empty email data when I send an AJAX contact form from Wordpress I'm a noob with AJAX and PHP development.
I have made this HTML contact form in Wordpress custom theme:

        <form class="footer-form-contact"
              name="contact">

Contacta con nosotros

            <input type="text"
                   placeholder="Nombre"
                   name="nombre"
                   id="nombre"
                   required/>
            <input type="email"
                   name="email"
                   id="email"
                   placeholder="Email"/>
            <input type="text"
                   placeholder="Teléfono"
                   name="telefono"
                   id="telefono"
                   required/>
            <textarea
                   name="mensaje"
                   id="mensaje"
                   placeholder="Escribe tu mensaje"
                   required>
            </textarea>
            <input type="checkbox"
                   required
                   name="privacidad"
                   value="privacidad"/>
            <input type="button"
                   id="enviar"
                   value="Enviar"
                   onclick="cargaSendMail()"/>
        </form>

Then I followed this question File path for AJAX script (in Wordpress) to get url path from admin-ajax.php like RRikesh do.
And this is functions.js:
function cargaSendMail(){

$("#enviar").attr("disabled", true);

$(".c_error").remove();

var filter=/^[A-Za-z][A-Za-z0-9_]*@[A-Za-z0-9_]+.[A-Za-z0-9_.]+[A-za-z]$/;
var s_email = $('#email').val();
var s_name = $('#nombre').val();
var s_telefono = $('#telefono').val();
var s_msg = $('#mensaje').val();

if (filter.test(s_email)){
    sendMail = "true";
} else{
    $('#email').after("Ingrese e-mail válido.");
    //aplicamos color de borde si el se encontro algun error en el envio
    $('.footer-form').css("border-color","#e74c3c");
    sendMail = "false";
}
if (s_name.length == 0 ){
    $('#nombre').after( "Ingrese su nombre." );
    var sendMail = "false";
}
if (s_telefono.length == 0 ){
    $('#telefono').after( "Ingrese su telefono." );
    var sendMail = "false";
}
if (s_msg.length == 0 ){
    $('#mensaje').after( "Ingrese mensaje." );
    var sendMail = "false";
}

if(sendMail == "true"){

    var datos = {
        "nombre" : $('#nombre').val(),
        "email" : $('#email').val(),
        "telefono" : $('#telefono').val(),
        "mensaje" : $('#mensaje').val()
    };

    $.ajax({
        url: ajaxurl,
        type: 'POST',
        data: datos + '&action=sendcontacto',

    beforeSend: function () {
        //aplicamos color de borde si el envio es exitoso
        $('.footer-form').css("border-color","#25A25A");
        $("#enviar").val("Enviando…");
    },

    success: function (response) {

        $('.footer-form-contact')[0].reset();
        $("#enviar").val("Enviar");
        $("#c_information p").html(response);
        $("#c_information").fadeIn('slow');
        $("#enviar").removeAttr("disabled");

    }
});

} else{
    $("#enviar").removeAttr("disabled");
}
}

and my function.php:
function send_my_contact(){
$mensaje = $_POST['mensaje'];
$mensaje.= "\n----------------------\n";
$mensaje.= "\nDe: ". $_POST['nombre'];
$mensaje.= "\nEmail: ". $_POST['email'];
$mensaje.= "\nTelefono: ". $_POST['telefono'];

$destino = "hola@fiuuu.es";
$remitente = $_POST['email'];
$asunto = "Mensaje enviado desde Talent Institut por ".$_POST['nombre'];
mail($destino,$asunto,$mensaje,"FROM: $remitente");

echo "Mensaje enviado. Gracias por conectarse con nosotros";
}

add_action('wp_ajax_sendcontacto', 'send_my_contact');
add_action('wp_ajax_nopriv_sendcontacto', 'send_my_contact');

It is every thing ok, and the system send me the email correctly, but the data are empty:
----------------------

De:
Email:
Telefono:

What am I doing wrong?

A: I would modify your data to the following, so that the action is explicitly set in datos:
var datos = {
    "nombre" : $('#nombre').val(),
    "email" : $('#email').val(),
    "telefono" : $('#telefono').val(),
    "mensaje" : $('#mensaje').val(),
    "action": 'sendcontacto'
};

$.ajax({
    url: ajaxurl,
    type: 'POST',
    data: datos,

redpajama_set_name: RedPajamaStackExchange


text:
Q: cast of Objective-C pointer type 'NSString *' to C pointer type 'CFStringRef' (aka 'const struct __CFString *') requires a bridged cast When converting an Objective-C program to a Objective-C ARC, I get the error:
"cast of Objective-C pointer type 'NSString *' to C pointer type 'CFStringRef' (aka 'const struct __CFString *') requires a bridged cast "

The code is as follows:
- (NSString *)_encodeString:(NSString *)string
{
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                   (CFStringRef)string, // this is line in error
                                   NULL,
                                   (CFStringRef)@";/?:@&=$+{}<>,",
                                   kCFStringEncodingUTF8);
    return [result autorelease];
}

What is a bridged cast?

A: Have a look at the ARC documentation on the LLVM website. You'll have to use __bridge or one of the other keywords.
This is because Core Foundation objects (CF*Refs) are not controlled by ARC, only Obj-C objects are. So when you convert between them, you have to tell ARC about the object's ownership so it can properly clean them up. The simplest case is a __bridge cast, for which ARC will not do any extra work (it assumes you handle the object's memory yourself).

A: I know this is an old thread, I came across this issue while I need to use
- (NSString *)URLEncodedString
{
    NSString *result = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                       (CFStringRef)self,
                                                                       NULL, CFSTR("!*'();:@&=+$,/?%#[]"),
                                                                       kCFStringEncodingUTF8);
[result autorelease];
return result;
}

So what I did is go to Target > Build phase > Compile sources.
There is your file listed, double click on that and add following lines next to your file.
-fno-objc-arc


text:
Q: Visual studio: Debug C++ application started as external process from C# Sorry for noob question.
I have 2 projects in VS solution: c# gui and unmanaged c++ console application. C++ application is started as external process from C# with some arguments. Is there any way to start debugging c++ app directly after starting process in C#?
I know about Command Arguments in c++ debugging, but sometimes it's uncomfortably.


text:
Q: PG:InsufficientPrivilege: ERROR when trying to make an INSERT on stage database Im using heroku and postgres. Local is working fine but whenever the user (any user) performs an INSERT on stage it crashes. This is the message i get:
PG:InsufficientPrivilege: ERROR: permission denied for relation .. INSERT INTO..

I granted privileges to public on the required tables but it doesn´t make a difference. Any insight would be useful. Thanks.

A: I know it's waaaaay late, but I just ran into this issue and I believe the problem is that you have exceeded the number of rows allowed for your DB. In my case, I was using a Hobby-dev plan and the limit is 10k rows. If you run heroku pg:info you will see something like:
=== HEROKU_POSTGRESQL_BRONZE_URL (DATABASE_URL)
Plan:        Hobby-dev
Status:      Available
Connections: 4/20
PG Version:  9.3.3
Created:     2014-05-27 15:07 UTC
Data Size:   175.5 MB
Tables:      47
Rows:        409300/10000 (Write access revoked)
Fork/Follow: Unsupported
Rollback:    Unsupported

With the Write access revoked being the key piece of information. Upgrading your DB (or deleting some data) should solve this.

A: I had this problem caused by over 10000 rows, I was using Hobby Dev (free until November 2022), I upgraded to Basic (paid), I understand this might not be solution for everyone
Hobby Dev 10,000 row limit
Mini 10,000 row limit
Basic 10,000,000 row limit
https://elements.heroku.com/addons/heroku-postgresql
Once I upgraded


text:
Q: jquery ui sortable, drag and drop for data assignment I'm searching an example using jquery ui sortable, drag and drop for the following scenario
I have 2 columns one contains different number of rows and the other column should act as place holder for data assignment.
What I mean:
Column with items to be assigned          the desired item should be dragged here
    ------------------                     ---------------------
    - item1
    ------------------                     ---------------------
    - item2
    ------------------                     ---------------------
    - item3                                 - item4
    ------------------                     ---------------------

A: You can use the jQuery UI's sortable's connected lists feature to do this,
Sortable 1 represents Column 1 and Column 2 is represented by Sortable 2. connect both the lists and set the second list as empty so that users can drag their items onto the list. Also, add a background to the second list so that user knows where to drag the item.

Item 1

Item 2

Item 3

Item 4

Item 5

The Fiddle for this: http://jsfiddle.net/pxtLj/1/
Source: http://jqueryui.com/sortable/#connect-lists


text:
Q: How to use ffmpeg api to make a filter overlay water mark? OS: Ubuntu 20.04
FFmpeg : 4.4.0
Test video :
Input #0, hevc, from './videos/akiyo_352x288p25.265':
Duration: N/A, bitrate: N/A
Stream #0:0: Video: hevc (Main), yuv420p(tv), 352x288, 25 fps, 25 tbr, 1200k tbn, 25 tbc
Test watermark:
200*200.png
I copy ffmpeg official example.
Compiler no error, run no error , but i can't see add watermark
Here is my code
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/opt.h>
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
int open_input_file(AVFormatContext *fmt, AVCodecContext **codecctx, AVCodec *codec, const char *filename, int index)
{
    int ret = 0;
    char msg[500];
    *codecctx = avcodec_alloc_context3(codec);
    ret = avcodec_parameters_to_context(*codecctx, fmt->streams[index]->codecpar);
    if (ret < 0)
    {
        printf("avcodec_parameters_to_context error,ret:%d\n", ret);

        return -1;
    }

    // open 解码器
    ret = avcodec_open2(*codecctx, codec, NULL);
    if (ret < 0)
    {
        printf("avcodec_open2 error,ret:%d\n", ret);

        return -2;
    }
    printf("pix:%d\n", (*codecctx)->pix_fmt);
    return ret;
}

int init_filter(AVFilterContext **buffersrc_ctx, AVFilterContext **buffersink_ctx, AVFilterGraph **filter_graph, AVStream *stream, AVCodecContext *codecctx, const char *filter_desc)
{
    int ret = -1;
    char args[512];
    char msg[500];
    const AVFilter *buffersrc = avfilter_get_by_name("buffer");
    const AVFilter *buffersink = avfilter_get_by_name("buffersink");

    AVFilterInOut *input = avfilter_inout_alloc();
    AVFilterInOut *output = avfilter_inout_alloc();

    AVRational time_base = stream->time_base;
    enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_YUV420P, AV_PIX_FMT_NONE};

    if (!output || !input || !filter_graph)
    {
        ret = -1;
        printf("avfilter_graph_alloc/avfilter_inout_alloc error,ret:%d\n", ret);

        goto end;
    }
    snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", codecctx->width, codecctx->height, codecctx->pix_fmt, stream->time_base.num, stream->time_base.den, codecctx->sample_aspect_ratio.num, codecctx->sample_aspect_ratio.den);
    ret = avfilter_graph_create_filter(buffersrc_ctx, buffersrc, "in", args, NULL, *filter_graph);
    if (ret < 0)
    {
        printf("avfilter_graph_create_filter buffersrc error,ret:%d\n", ret);

        goto end;
    }

    ret = avfilter_graph_create_filter(buffersink_ctx, buffersink, "out", NULL, NULL, *filter_graph);
    if (ret < 0)
    {
        printf("avfilter_graph_create_filter buffersink error,ret:%d\n", ret);

        goto end;
    }
    ret = av_opt_set_int_list(*buffersink_ctx, "pix_fmts", pix_fmts, AV_PIX_FMT_NONE, AV_OPT_SEARCH_CHILDREN);
    if (ret < 0)
    {
        printf("av_opt_set_int_list error,ret:%d\n", ret);

        goto end;
    }
    /*
 * The buffer source output must be connected to the input pad of
 * the first filter described by filters_descr; since the first
 * filter input label is not specified, it is set to "in" by
 * default.
 */
    output->name = av_strdup("in");
    output->filter_ctx = *buffersrc_ctx;
    output->pad_idx = 0;
    output->next = NULL;

    /*
 * The buffer sink input must be connected to the output pad of
 * the last filter described by filters_descr; since the last
 * filter output label is not specified, it is set to "out" by
 * default.
 */
    input->name = av_strdup("out");
    input->filter_ctx = *buffersink_ctx;
    input->pad_idx = 0;
    input->next = NULL;

    if ((ret = avfilter_graph_parse_ptr(*filter_graph, filter_desc, &input, &output, NULL)) < 0)
    {
        printf("avfilter_graph_parse_ptr error,ret:%d\n", ret);

        goto end;
    }

    if ((ret = avfilter_graph_config(*filter_graph, NULL)) < 0)
    {
        printf("avfilter_graph_config error,ret:%d\n", ret);

        goto end;
    }
    end:
    avfilter_inout_free(&input);
    avfilter_inout_free(&output);
    return ret;
}

int main(int argc, char **argv)
{
    int ret;
    char msg[500];
    const char *filter_descr = "drawbox=x=100:y=100:w=100:h=100:color=pink@0.5"; // OK
    //const char *filter_descr = "movie=200.png[wm];[in][wm]overlay=10:10[out]"; //Test
    // const char *filter_descr = "scale=640:360,transpose=cclock";
    AVFormatContext *pFormatCtx = NULL;
    AVCodecContext *pCodecCtx;
    AVFilterContext *buffersink_ctx;
    AVFilterContext *buffersrc_ctx;
    AVFilterGraph *filter_graph;
    AVCodec *codec;
    int video_stream_index = -1;

    AVPacket packet;
    AVFrame *pFrame;
    AVFrame *pFrame_out;
    filter_graph = avfilter_graph_alloc();
    FILE *fp_yuv = fopen("test.yuv", "wb+");
    ret = avformat_open_input(&pFormatCtx, argv[1], NULL, NULL);
    if (ret < 0)
    {
        printf("avformat_open_input error,ret:%d\n", ret);

        return -1;
    }

    ret = avformat_find_stream_info(pFormatCtx, NULL);
    if (ret < 0)
    {
        printf("avformat_find_stream_info error,ret:%d\n", ret);

        return -2;
    }

    ret = av_find_best_stream(pFormatCtx, AVMEDIA_TYPE_VIDEO, -1, -1, &codec, 0);
    if (ret < 0)
    {
        printf("av_find_best_stream error,ret:%d\n", ret);

        return -3;
    }
    // 获取到视频流索引
    video_stream_index = ret;

    av_dump_format(pFormatCtx, 0, argv[1], 0);
    if ((ret = open_input_file(pFormatCtx, &pCodecCtx, codec, argv[1], video_stream_index)) < 0)
    {
        ret = -1;
        printf("open_input_file error,ret:%d\n", ret);

        goto end;
    }

    if ((ret = init_filter(&buffersrc_ctx, &buffersink_ctx, &filter_graph, pFormatCtx->streams[video_stream_index], pCodecCtx, filter_descr)) < 0)
    {
        ret = -2;
        printf("init_filter error,ret:%d\n", ret);

        goto end;
    }
    pFrame = av_frame_alloc();
    pFrame_out = av_frame_alloc();
    while (1)
    {
        if ((ret = av_read_frame(pFormatCtx, &packet)) < 0)
            break;

        if (packet.stream_index == video_stream_index)
        {
            ret = avcodec_send_packet(pCodecCtx, &packet);
            if (ret < 0)
            {
                printf("avcodec_send_packet error,ret:%d\n", ret);

                break;
            }

            while (ret >= 0)
            {
                ret = avcodec_receive_frame(pCodecCtx, pFrame);
                if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                {
                    break;
                }
                else if (ret < 0)
                {
                    printf("avcodec_receive_frame error,ret:%d\n", ret);

                    goto end;
                }

                pFrame->pts = pFrame->best_effort_timestamp;

                /* push the decoded frame into the filtergraph */
                ret = av_buffersrc_add_frame_flags(buffersrc_ctx, pFrame, AV_BUFFERSRC_FLAG_KEEP_REF);
                if (ret < 0)
                {
                    printf("av_buffersrc_add_frame_flags error,ret:%d\n", ret);

                    break;
                }

                /* pull filtered frames from the filtergraph */
                while (1)
                {
                    ret = av_buffersink_get_frame(buffersink_ctx, pFrame_out);
                    if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
                        break;
                    if (ret < 0)
                        goto end;
                    if (pFrame_out->format == AV_PIX_FMT_YUV420P)
                    {
                        //Y, U, V
                        for (int i = 0; i < pFrame_out->height; i++)
                        {
                            fwrite(pFrame_out->data[0] + pFrame_out->linesize[0] * i, 1, pFrame_out->width, fp_yuv);
                        }
                        for (int i = 0; i < pFrame_out->height / 2; i++)
                        {
                            fwrite(pFrame_out->data[1] + pFrame_out->linesize[1] * i, 1, pFrame_out->width / 2, fp_yuv);
                        }
                        for (int i = 0; i < pFrame_out->height / 2; i++)
                        {
                            fwrite(pFrame_out->data[2] + pFrame_out->linesize[2] * i, 1, pFrame_out->width / 2, fp_yuv);
                        }
                    }
                    av_frame_unref(pFrame_out);
                }
                av_frame_unref(pFrame);
            }
        }
        av_packet_unref(&packet);
    }
    end:
    avcodec_free_context(&pCodecCtx);
    fclose(fp_yuv);
}

A: Try to keep the same pts of the frame and the overlay, set the pFrame->pts = 0 may be work


text:
Q: What does this one liner means in lambda function in Python? I'm stuck in this lambda one-liner. This one-liner is for sorting the string in a list but don't know how this actually functions? Kindly help me to understand this.
This is the motive of the below function:
sort_item_list_by_author(): Accepts the new list of books and returns it sorted in the alphabetical order of their author names. Note: While sorting the author names in alphabetical order, ignore the special characters including space, if there are any.
    def sort_item_list_by_author(self,new_item_list):
       new_item_list.sort(key=lambda x:''.join(e for e in x.get_author_name() if e.isalnum())) #problem causing line

    item11=Item("Broken Wing","Sarojini Naidu",2012)
    item12=Item("Guide","R.K.Narayanan",2001)
    item13=Item("Indian Summers","John Mathews",2001)
    item14=Item("Innocent in Death","J.D.Robb",2010)
    item15=Item("Life of Pi","Yann Martel",2010 )
    item16=Item("Sustainability","Johny",2016)
    item17=Item("Look Ahead","E.M.Freddy",2012 )

    new_item_list=[item11,item12,item13,item14,item15,item16,item17]
    new_item_list_sorted=library.sort_item_list_by_author(new_item_list)

A: lambda you are talking about is the key to the sort function, which means that it is being you used to compare the values in the list.

lambda x:''.join(e for e in x.get_author_name() if e.isalnum()

So for every element of the list, this lambda function is called. Here x represents the parameter of the lambda function(in this case, it is list item).
Now the body of the lambda function is pretty simple in itself, we get the author name, and loop over it character by character, and select only those characters which are alpha-numeric(means we are ignoring spaces and all), then we join all the obtained chars in one string.
Using the lambda function, for all the items in the list, such strings(alpha-num part of author's name) are created, which is used for sorting out the list.
The lambda translates to something like this:
x = item() #fill the fields here
s = ''
for e in x.get_author_name():
    if e.isalnum():
       s += e

A: In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions.Let's see an example.
>>> addition=lambda x1,x2:x1+x2
>>> subtraction=lambda x1,x2:x1-x2
>>> addition(10,20)
30
>>> subtraction(10,20)
-10
>>> #there is another way also
>>>(lambda num1, num2: num1+num2)(10,20)
30

Now Suppose we have a list of items(integers and strings with numeric contents)
numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]

Now I am using sorted function to sort it, You can use sort also but as we know sort function alters the original data but the sorted returns a new sorted list
>>> numbers = [1,"2", "5", 3, 4, "8", "-1", "-11"]
>>> sorted(numbers)
[1, 3, 4, '-1', '-11', '2', '5', '8']
>>>

But this is not expected answer
['-11', '-1', 1, '2', 3, 4, '5', '8']

so here we've to used to key keyword as a argument
>>> sorted(numbers, key=int)
['-11', '-1', 1, '2', 3, 4, '5', '8']
>>> sorted(['There', 'are','some', 'sort', 'words'], key=lambda word: word.lower())
['are', 'some', 'sort', 'There', 'words']

Which is same as
sorted(['There', 'are','some', 'sort', 'words'],key=str.lower)

According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element
key=str.lower The default value is None (compare the elements directly)


text:
Q: How can we set dynamic "redirect_uri" parameter value in dropbox-api integration? I need to set URL(s) into dropbox for redirect_uri parameters.
Our application support dynamic domain URL(s).
URL prefix define by user and suffix will be constant. And prefix will change at any time.
e.g. Format(https://{prefix-testapplication.com})
1 : Application URL : https://abc-testapplication.com
2 : Application URL : https://def-testapplication.com
In an above example, we need to mentioned redirect_uri into DropBox for navigation.
Mention redirect_uri as below image.

As per above image, we can configure url value at a time only.
So problem is that, how we can support dynamic URL?
Thanks in an advance.

A: As a security feature, Dropbox OAuth 2 redirect URIs must be pre-registered exactly. Wildcard and dynamic registrations are not supported.
One thing you may be able to do instead is to use one static redirect URI but encode the necessary information in the state parameter, and decode it after the redirect back to your app, to handle it as necessary (e.g., redirect to the relevant domain):
https://www.dropbox.com/developers/documentation/http/documentation#oauth2-authorize
Alternatively, you could forgo using a redirect URI entirely. With the "code" flow, you can omit redirect_uri and have the user copy and paste the code manually.


text:
Q: Inner Join and show value I have two tables in my MySQL database:
table_bookings:
id - bookings
1  - 1
2  - 1,2,3
3  - 2,3

table_services:
id - name
1  - Facial
2  - Corporal
3  - Others

I need to make a query to get the following result:
id - services_id - services_name
1  - 1           - Facial
2  - 1,2,3       - Facial, Corporal, Others
3  - 2,3         - Corporal, Others

A: First Change your table layout to something like this:
table_bookings:
id    | booking
1     | 1
2     | 1
2     | 2
2     | 3
3     | 2
3     | 2

After that you can join this table by booking-id to the Translation:
SELECT * FROM table_bookings AS a JOIN table_services AS b ON a.booking = b.id

If you Play around with GROUP_CONCAT after that you should get your desired result.

A: It looks like you need to join table table_bookings to table table_services to combine information from both tables in the result.
To join the two tables, you need to join them on a matching column. In other words, there needs to be a column in both tables which essentially represents the same thing -- then you can join using this column.
It looks like column bookings in table_bookings corresponds to id in table_services so you should join on these columns.

A: Consider normalize data. This can be done with these queries from existing data:
CREATE TABLE booking_services AS
  SELECT DISTINCT b.id AS booking_id, s.id AS service_id
  FROM table_bookings b
  INNER JOIN table_services s ON FIND_IN_SET(s.id, b.bookings) > 0;

ALTER TABLE booking_services
  ADD PRIMARY KEY (booking_id, service_id);

After normalization your query can be this:
SELECT
  bs.booking_id,
  GROUP_CONCAT(bs.service_id ORDER BY bs.service_id) AS services_id,
  GROUP_CONCAT(s.name ORDER BY bs.service_id SEPARATOR ', ') AS services_name
FROM
  booking_services bs
INNER JOIN
  table_services s ON s.id = bs.service_id
GROUP BY bs.booking_id

Yes, you can write query on non normalized data:
SELECT
  b.id,
  b.bookings AS services_id,
  GROUP_CONCAT(s.name ORDER BY s.id SEPARATOR ', ') AS services_name
FROM
  table_bookings b
INNER JOIN
  table_services s ON FIND_IN_SET(s.id, b.bookings) > 0
GROUP BY b.id, b.bookings

But on large data sets query on normalized data performs faster - see execution plans (See EXPLAIN syntax).
Test both queries on SQL Fiddle
Documentation:

*

*Database normalization

*CREATE TABLE ... SELECT Syntax

*ALTER TABLE Syntax

*FIND_IN_SET(str,strlist)

*GROUP_CONCAT(expr)


text:
Q: My application will not automatically start with windows - what is wrong here? I am using the following code to manage the automatic startup of my application. The application has been set up to require admin privileges, and indeed, does ask for them.
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (checkRunOnStartup.Checked)
{
    rkApp.SetValue("MyApp", Application.ExecutablePath.ToString());
}
else
{
    rkApp.DeleteValue("MyApp", false);
}

This does not work on any system I have tested on, except from my development machine. What am I doing wrong here?

A: Instead of writing reg keys you could create/delete a shortcut to your app in the windows startup folder.  Environment.SpecialFolder.Startup will return you that path.  If you dead set on the reg key option here is a snippet of code per DotnetThoughts .  Seems the main difference is he dropped the .ToString().
private void RegisterInStartup(bool isChecked)
{
   RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
        ("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
   if (isChecked)
   {
       registryKey.SetValue("ApplicationName", Application.ExecutablePath);
   }
   else
   {
     registryKey.DeleteValue("ApplicationName");
   }
}


text:
Q: How to merge two images and save in php at Run Time? i want to make a picture upload in frame and save  both image and frame as a single image ,main thing is whatever the size of image in frame,it should be appear exactly  same in a final resulting image after merging.
Here is part of my code:
$imgframe = $_GET['imgframe'];
$imgphoto = $_GET['imgphoto'];

$imgwidth = $_GET['imgwidth'];
$imgheight = $_GET['imgheight'];

$imgleft = substr($_GET['imgleft'],0,-2);
$imgtop = substr($_GET['imgtop'],0, -2);

$src = imagecreatefromjpeg($imgphoto);//'image.jpg'
$dest = imagecreatefrompng($imgframe);//clip_image002.png

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagecopyresampled(
     $dest, $src, $imgleft, $imgtop, $imgleft, $imgtop,
     $imgwidth, $imgheight, $imgwidth, $imgheight
);

A: As per your comment below the question, you are using the wrong function.
The PHP manual page for imagecopymerge states that it copies a part of an image onto another.  It states that you can specify the origin coordinates, width and height of the region to copy from the source, and the coordinates in the destination in which to place that region.
In other words, it takes a rectangular area of a given size from the source image and puts it on top of the destination, at the given location.  It does NOT ask for the size of the region into which you are copying it, only the location.  Therefore, it does not resize the copied region, but copies it pixel-for-pixel.
The function you actually need is imagecopyresampled, which allows you to specify the size of the destination region, and will smoothly scale the source region to fit.
EDIT
You are still having a problem because you are using the same coordinates and the same dimensions in the source and the destination parameters.  Same dimensions == no resizing.
$imgframe = $_GET['imgframe'];
$imgphoto = $_GET['imgphoto'];

// I am assuming these specify the area of the imgphoto which
// should be placed in the frame?
$imgwidth = $_GET['imgwidth'];
$imgheight = $_GET['imgheight'];
$imgleft = substr($_GET['imgleft'],0,-2);
$imgtop = substr($_GET['imgtop'],0, -2);

// now you also need to get the size of the frame so that
// you can resize the photo correctly:
$frameSize = getimagesize($imgframe);

$src = imagecreatefromjpeg($imgphoto);//'image.jpg'
$dest = imagecreatefrompng($imgframe);//clip_image002.png

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagecopyresampled(
     $dest, $src,
     0, 0, // these two specify where in the DESTINATION you want to place the source.  You might want these to be offset by the width of the frame
     $imgleft, $imgtop, // the origin of area of the source you want to copy
     $frameSize[0], $frameSize[1], // These specify the size of the area that you want to copy IN TO (i.e., the size in the destination), again you might want to reduce these to take into account the width of the frame
     $imgwidth, $imgheight // the size of the area to copy FROM
);


text:
Q: how to integrate facebook(like),twitter,google plus(bubble button) android app I want to integrate facebook(like),twitter,google plus(bubble button) into my android app, which is developed using Android, so that I can post my application URL to there status. I referred a lot of links and nothing is working for me.

A: You can't inject social plugins that you expect. When you are in a native app, assume that you run an html file in your local, because of that reason, this plugins will not run too.
You have to use their SDK'


text:
Q: Count of elements on kibana visualization I have inserted below JSON records on my elastic index. How do I get count of all the elements present in the "devices" array so that count can be visualized on Kibana Dashboard ?
Filter condition - Devices count needs to be displayed as "4" for SAMPLE application and "2" for SAMPLE2 application on Kibana.
Without Filter condition - Device count to be displayed as "6" devices.
{
    "status" : "SUCCESS",
    "request" : ["ABC"],
    "applicationName" : "SAMPLE",
    "endTime" : 1478772517736,
    "devices" : ["d1","d2","d3","d4"]
}
,
{
    "status" : "FAILED",
    "request" : ["EDF"],
    "applicationName" : "SAMPLE2",
    "endTime" : 1478772517736,
    "devices" : ["d5","d12"]
}

A: You should create a scripted field in Kibana in order to get the length of an array element. So your script could look something like this:
doc['devices'].values.size()

OR
doc['devices'].values.length

And then you can have a Data Table visualization, where having the array count in respective to the applicationName by using the terms aggregation. Or you could apply filters saying:
applicationName:"SAMPLE"
applicationName:"SAMPLE2"

which will display the array count for the given filter criteria. This SO could be helpful.


text:
Q: Data Dump Accepted Answer with wrong ParentId I'm working on the data dump of Stack Overflow  and I might have found a bug in it.
The post (link1) has been merged with the post (link2) but in the data dump there is this:
Id post1 = 1406604 with AcceptedAnswersId = 1406611
Id post2 = 784929 with AcceptedAnswersId = 784946
And Id answer = 1406611 have ParentId = 784929
The problem is that the AcceptedAnswerId of the post1 is still here.
In an other post I remark that the post for which its AcceptedAnswer has been removed keep a value for its AcceptedAnswerId. link3
Maybe a modification can be made.

A: Yes, there are a couple of those inconsistencies. I've created the following query to find those cases where the acceptedanswerid on the question links to an answer that has a different parentid.
select q.id as [Post Link]
     , q.creationdate
     , (select count(*)
        from posthistory
        where postid = q.id and posthistorytypeid = 37) as [Source migrated]
     , a.id as [Post Link]
     , a.creationdate
     , (select count(*)
        from posthistory
        where postid = a.id and posthistorytypeid = 38) as [Dest migrated]
     , case
       when a.deletiondate is not null
       then a.deletiondate
       else null
       end [deleted]
from posts q
inner join postswithdeleted a on a.id = q.acceptedanswerid
where q.id <> a.parentid

The query outputs the following columns:

*

*Question Link

*Question Creationdate

*# Merge Source events in Posthistory

*Answer Link

*Answer CreationDate

*# Merge Destination events in Posthistory.

When you glance over the results you see the following patterns:

*

*Merge source present and Merge Destination present.

*Merge source present and deleted answer

*Merge source absent and deleted answer

*Merge source absent and active answer, Merge destination absent

For the cases where the merge source is present it always means the question was merged into another question. In those cases I tend to disagree that the record for the question should be fixed. It kind of keeps track of what the original OP choose as the accepted answer, which is valuable info in some sense.
For the cases where the merge source is absent we see the left overs of a race condition that once existed. It becomes manifest when one Q/A has multiple accepted questions or where answers have an accept vote in their history but isn't shown.
Here are the bug reports that describe the issue:
Answer accepted twice
Accepted answer reward +15 awarded twice!
Bug: Awarded double rep for accepted answer
Multiple accepted answers to a question?
For the above cases where I was sure a moderator could rectify the issue I've flagged or will be flagging the question or answer.  I delete voted one question because it was about PHP.
tl;dr; The merge stubs shouldn't be fixed, the remaining errors can be rectified with flags and a moderator action.


text:
Q: Is there any adjectival form of "Audit"? I just made the mistake of using "Auditory" in the context of auditing. For example:
"We need to include that information, for auditory purposes."
After I sent my e-mail, I was embarrassed to find out that "auditory" refers to hearing.

A: Auditing
As a Native North American English speaker I would say, "We need to include that information, for auditing purposes."
Source http://www.chompchomp.com/terms/participle.htm
Source -https://en.m.wikipedia.org/wiki/Participle
Source - https://www.englishgrammar.org/participles/
Source - https://www.grammar-monster.com/glossary/present_participle.htm
"Auditing" in this case is used as a present participle. "Audited" can be used as the past participle.
For example, "Our data is stored in audited databases." And, "E & Y reviewed the auditing logs."
In my experience this usage is common in the Eastern United States.

A: I'm not recommending the phrasing when I say 'auditorial' works in your example sentence:

We need to include that information, for auditorial purposes.

I'm sure there are better ways to put it, depending on context and intention. For example:

*

*We need to audit that information.

*That information must be included for the audit.

*Etc.

From OED:

auditorial, adj.
  ...
2. Of or pertaining to auditors of accounts; connected with an audit.

In your example, the purposes are connected with an audit.


text:
Q: Item name in array 2d / multidimensional How to assign a name to element in multidimensional array in Actionscript 3.
In 1d array working:
tab[0].name = "name";

In multidimensional array dont working:
tab[0][0] = "name";

A: First you need to make sure you are adding your object properly to the multidimensional array, something like:
// Declare a single dimension array
var tab:Array = new Array();

// Add another array at each of your indexes, starting at zero
tab[0] = new Array();
tab[0].add(objectThatHasANameProperty);
//OR
tab[0] = new Array(objectThatHasANameProperty)

//Then reference it properly (with the .name, your example code above does not have ".name")
tab[0][0].name = "name";

Optionally you can have additional properties defined as follows, if for example you have objects that do not have a name property (not my first choice, but do-able):
tab[0] = new Array(someObject, "name", "description");
tab[0][1] = "a new name";
trace(tab[0][1]); //traces: "a new name"
trace(tab[0][2]); //traces: "description"

A: var arr:Array =[];
arr[0]=[];
arr[0][0] = "benny";
arr[0][1] = "geo";
trace(arr[0][0]);

try this way...


text:
Q: Best way to compare nested dictionaries in a list, Python I'm querying a public endpoint to get an exchange rate of varies exchanges that returns a list with nested dictionaries.  I'm most interesting in is the key "amount" field in the nested dictionaries.  I'm struggling to come up with a solution to store the nested dictionary that has the most "amount" value in a variable.  Any ideas would be extremely helpful.  I'm banging my head against the wall on this one.
Here is the list:
list_with_nested_dicts = [{"partner":"simpleswap","amount":0,"currency":"cel","supportRate":3,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"simpleswap","amount":0,"currency":"cel","supportRate":3,"duration":0,"fixed":false,"min":0,"max":0,"exists":false,"id":""},{"partner":"stealthex","amount":37.90346104,"currency":"cel","supportRate":2,"duration":66.62083333333334,"fixed":true,"min":39.91443225,"max":2550.215226,"exists":true,"id":""},{"partner":"stealthex","amount":37.20972396,"currency":"cel","supportRate":2,"duration":23.158333333333335,"fixed":false,"min":77.82938688,"max":25209.49720665,"exists":true,"id":""},{"partner":"godex","amount":0,"currency":"cel","supportRate":0,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"changenow","amount":37.2077365,"currency":"cel","supportRate":2,"duration":11.08859649122807,"fixed":false,"min":56.60646516,"max":25259.88795509,"exists":true,"id":""},{"partner":"changelly","amount":0,"currency":"cel","supportRate":1,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"changelly","amount":0,"currency":"cel","supportRate":1,"duration":0,"fixed":false,"min":0,"max":0,"exists":false,"id":""},{"partner":"instaswap","amount":0,"currency":"cel","supportRate":2,"duration":0,"fixed":false,"min":0,"max":0,"exists":false,"id":""},{"partner":"exolix","amount":0,"currency":"cel","supportRate":0,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"fixedfloat","amount":0,"currency":"cel","supportRate":3,"duration":0,"fixed":false,"min":0,"max":0,"exists":false,"id":""},{"partner":"switchain","amount":0,"currency":"cel","supportRate":2,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"changehero","amount":0,"currency":"cel","supportRate":3,"duration":56.41111111111111,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"changehero","amount":0,"currency":"cel","supportRate":3,"duration":2.4833333333333334,"fixed":false,"min":0,"max":0,"exists":false,"id":""},{"partner":"binance","amount":0,"currency":"cel","supportRate":2,"duration":0,"fixed":false,"min":0,"max":0,"exists":false,"id":""},{"partner":"nexchange","amount":0,"currency":"cel","supportRate":3,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"letsexchange","amount":0,"currency":"cel","supportRate":2,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""},{"partner":"letsexchange","amount":0,"currency":"cel","supportRate":2,"duration":0,"fixed":false,"min":0,"max":0,"exists":false,"id":""},{"partner":"alfacash","amount":0,"currency":"cel","supportRate":3,"duration":0,"fixed":true,"min":0,"max":0,"exists":false,"id":""}]

The dictionary that has the most amount is:
{"partner":"stealthex","amount":37.90346104,"currency":"cel","supportRate":2,"duration":66.62083333333334,"fixed":true,"min":39.91443225,"max":2550.215226,"exists":true,"id":""}

A: Use the key parameter of max:
from operator import  itemgetter
res = max(list_with_nested_dicts, key=itemgetter("amount"))
print(res)

Output
{'partner': 'stealthex', 'amount': 37.90346104, 'currency': 'cel', 'supportRate': 2, 'duration': 66.62083333333334, 'fixed': True, 'min': 39.91443225, 'max': 2550.215226, 'exists': True, 'id': ''}

From the documentation:

The key argument specifies a one-argument ordering function like that
used for list.sort()

Note there is no need to use operator.itemgetter, you could simply use a lambda function as the value of key:
max(list_with_nested_dicts, key=lambda x: x["amount"])

Additionally, in case some of the dictionaries have no item "amount", I suggest you use .get as follows:
default = 0
res = max(list_with_nested_dicts, key=lambda x: x.get("amount", default))

where default should be a value that best suits your needs.

A: Try this:
Bu you will need to replace 'true' with True and 'false' with 'False' for this code to work.
list_with_nested_dicts.sort(key=lambda a: a['amount'])
print(list_with_nested_dicts[-1])


text:
Q: How to access previous stage results in CompletableFuture I am trying to chain tasks in CompletableFuture to execute them in parallel and get the best performance and resource utilization.
The workflow I am writing has five stages and each stage depends on the result of the previous stages.
The workflow execution is as follows:
* Stage-1: Create CustomerContext -> This will call downstream services and return Context object.

* Stage-2: Generate Candidates for the customer -> This stage generate candidates and returns a List<Candidate> object. This stage requires CustomerContext as a parameter to generate the candidates.

* Stage-3: Process Candidate -> In this stage I process the candidates and returns processed List<Candidate>. This stage requires CustomerContext and List<Candidate> object from stage-1 and stage-2

* Stage-4: Rank candidates -> In this stage I perform candidate ranking and returns ranked List<Candidate> object. This stage requires CustomerContext and List<Candidate> object from stage-1 and **stage-3**

* Stage-5: Generate Result -> In this stage I generate the final result and returns Result object by making downstream API calls., This stage requires CustomerContext and List<Candidate> object from **stage-1** and **stage-4**

I can create a result holder object to hold each stage's results. However, I am not sure if that is the best solution.
Is CompletableFuture the best solution for this use case? What would be the optimal way to chain these stages?

A: Use thenCompose to compose the results from different futures which depend on each other:
CompletableFuture<String> result =
    CompletableFuture.supplyAsync(() -> "result 1")
        .thenCompose(result1 ->
    CompletableFuture.supplyAsync(result1::length)
        .thenCompose(strLen ->
    CompletableFuture.supplyAsync(strLen::toString)));

Note though, since each future depend on the result of the previous one, there is no way in executing them in parallel. Each future will still execute after the previous has completed.
If the futures do not depend on each other, you can run them in parallel by "unearthing the hidden applicative".
Also note, CompletableFuture only has supplyAsync and runAsync taking a Supplier and a Runnable, respectively and there is no direct way of dealing with asynchronous actions that might throw an exception (e.g. running Callable). If you need to do that, you have to delegate to a  helper future as described in this answer.


text:
Q: Checking any screen session active on linux I'm trying discover if any linux screen session is running. Currently, I have the code for only a specific screen by name, but I want discover if any screen session is running. Can you help me?
screen -list | grep "SESSİON NAME" && echo "Active Program" || echo "Passive Program"

How can I update this code above to match all screens running?

A: Just grep for the proper string:
screen -list | grep "No active:" && echo "No active Program" || echo "There is an active Program"


text:
Q: Apache 2.4 LDAP lookup sllow Server is running RHEL 7 and Apache 2.4.6; this is a pretty new (about a week old) problem. My department Intranet uses authentication against the university's Active Directory environment, and authentication for end-users takes over 30 seconds. Subsequent page loads are nearly-instant, and after some time (timeout, I assume), the problem is back.
<Directory /var/www/html/intranet>
  AuthType Basic
  AuthName "Restricted files"
  AuthBasicProvider ldap
  AuthLDAPBindDN CN=dept-binder,OU=Generic-Logon,OU=Generic,DC=example,DC=edu
  AuthLDAPBindPassword lamepassword
  AuthLDAPURL ldaps://ldap-ad.example.edu:636/dc=example,dc=edu?sAMAccountName?sub

  <RequireAny>
    require ldap-group CN=ug-dept-intranet,OU=Deoartment,OU=Dept-Groups,DC=example,DC=edu
  </RequireAny>
</Directory>

Here are some relevant lines from error_log:
AH02034: Initial (No.1) HTTPS request received for child 36 (server dept.example.edu:443)
AH01626: authorization result of Require ldap-group CN=ug-psy-employees,OU=Dynamic,OU=Psychology,OU=FSU-Dept-Groups,DC=fsu,DC=edu: denied (no authenticated user yet)
AH01626: authorization result of Require ldap-group CN=ug-dept-intranet,OU=Dept,OU=Dept-Groups,DC=example,DC=edu: denied (no authenticated user yet)
AH01691: auth_ldap authenticate: using URL ldaps://ldap-ad.example.edu:636/dc=example,dc=edu?sAMAccountName?sub
AH02001: Connection closed to child 11 with standard shutdown (server dept.example.edu:443)

# 37 seconds pass

AH01697: auth_ldap authenticate: accepting jsmith
AH01713: auth_ldap authorize: require group: testing for group membership in "CN=ug-dept-intranet,OU=Department,OU=Dept-Groups,DC=example,DC=edu"
AH01714: auth_ldap authorize: require group: testing for member: CN=jsmith,OU=PEOPLE,DC=example,DC=edu (CN=ug-dept-intranet,OU=Department,OU=Dept-Groups,DC=example,DC=edu)
AH01715: auth_ldap authorize: require group: authorization successful (attribute member) [Comparison true (adding to cache)][6 - Compare True]

A: I've had exactly the same problem on Fedora 33 with Apache 2.4 and I've solved it by adding:
LDAPConnectionTimeout 1
to the Apache global configuration:
https://httpd.apache.org/docs/2.4/mod/mod_ldap.html
The above parameter sets LDAP connection timeout to 1 second.
I'm using LDAPS with TLS and I suspect that delay was caused by Apache trying to resolve names or verify Active Directory/DC non-qualified (self enrolled) certificate.

A: if your directory is large (university, so it could be), queries could be slow out of the box. You need to tweak them. No silver bullet, but some pointers:

*

*filter on indexed attributes

*try using the global catalog port if the attributes are listed as global catalog replicated

*avoid (if at allo possible) sub scoped searches. This is obviously not always possible, but it often is

There are more listed in this Microsoft document.
You can try debugging mod_ldap, maybe you can find some obvious problem that way, beware credentials could appear in the debug log.


text:
Q: Git is ignoring .git directories in subdirectories I'm using git as a backup tool and 'roaming profile' for my $HOME directory between laptop and desktop.
My problem is that under my $HOME I have a Development directory with multiple git projects I'm working on. Git will not allow me to add the subdirectories .git folders. So to commit to these projects I have to push the changes into my $HOME git repo, pull on laptop (where they were created and .git dir exsits) and commit.
I've read about submodules, but it's not really what I want. I just want the children .git folders to be treated like any old directory so I can move them around and back them up.
Has anyone done this or have an idea how I would?

A: Don't do it. It's a bad idea because you are creating a versioned backup of a versioned repository. Just create a backup by rsync (you can still version the parent using git)

A: I'm personally using git to sync some dot-files like .profile or .vimrc. To avoid problems like yours my git is located in $HOME/dot and the single files are symlinked in $HOME.

A: I would recommend a script which would first backup every .git projects you have under your $HOME: it will produce one backup file (still under your $HOME)
See git bundle for more.
And then, you can add/update those backup (or "bundle") files to your main git repo (which contains all of your $HOME except the .git projects)
Finally, you can export all of your $HOME as one file with the same Git backup technique (git bundle).

A: In the past I have used gibak, a Git backup tool. Besides taking care of file attributes it also takes care of Git repositories inside your home directory.
One disclaimer though. I have used it for a while, but sometimes the backup became corrupt. I haven't investigated this, but I suspect it has to do with the fact that running applications constantly write data to your home directory. At some point the hashes mismatch and you have to do some smart things in order to get it fixed (or start a new backup).
At least give it a try, it may work for you. The problem I mentioned might also be caused by Git. Since I tried this 1.5 years ago, it might be fixed in the meantime.


text:
Q: How to Debugger in VSCode? I added new extension in VSCode. I've added syntax and snippets. It's time for debugging. I searched a lot and couldn't get exactly what I wanted. I want to debug without using tasks.json.
My json files:
launch.json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Run",
            "request": "attach",
            "windows": {
                "preLaunchTask": "windows"
            },
            "linux": {
                "preLaunchTask": "linux"
            },
            "osx": {
                "preLaunchTask": "osx"
            }
        }
    ]
}

tasks.json
{
    "version": "2.0.0",
    "tasks": [
    {
        "label": "windows",
        "command": "echo",
        "args": ["hello windows"],
        "type": "shell"
    },
    {
        "label": "linux",
        "command": "echo",
        "args": ["hello linux"],
        "type": "shell"
    },
    {
        "label": "osx",
        "command": "echo",
        "args": ["hello macOS"],
        "type": "shell"
    }
]
}

Thanks for all your answers.


text:
Q: How to test Xcode Source Editor Extension? I am writing XCode Source Editor Extension and I would like to add some tests so I can develop faster.
My setup is
MyContainerApplication
  - SourceEditorExtension
    - SourceEditorCommand.swift
    - MyClass.swift

I would like to test MyClass.swift. MyContainerApplication has target dependency to SourceEditorExtension.
So I create Unit test with MyContainerApplication set as a host application.
In my test I can then call:
@testable import MyContainerApplication

class Test: XCTestCase {

    func testSomething() {

         let c = MyClass()
    }
}

But XCode says MyClass can't be found, which makes sense because it is not included in the HostApplication but in the SourceEditorExtension. I also can't call
@testable import SourceEditorExtension

because it's not a module.
And I can't add MyClass.swift directly to my test target or host application target because it uses XcodeKit framework. I will get an error:
XcodeKit module not found

It looks like XcodeKit can't be imported anywhere else than in the SourceEditorExtension, not even in tests.
So my question is - is there some another way to test the Source Editor Extension?

A: You can check how Unit Tests done here SwiftInitializerGenerator. Testable code is shared between two targets. And no @testable inside tests. Try to get rid of any dependence of XcodeKit inside your class. Probably now it is the one way for extension tests

A: Make sure your MyClass.swift is set to both SourceEditorExtension and MyContainerApplicationTests.


text:
Q: Different function behavior based on params I'm new to jQuery/Javascript, so I'm not sure if this is possible.
I've got a simple function that removes elements, adds a class and disables an input button:
function removeElements() {
  $("#dragAndDropFiles, placeHolderImage").remove();
  $(".dragDropTag, .dragDrop, .dragDropIcon, #multiUpload").addClass("dropped");
  $("#multiUpload").prop('disabled', true);
}

Later on I will need to essentially reverse this function (ie. add all the elements back in, remove the class, and enable the input button. I could do this by adding another function:
function addElements() {
  $("#dragAndDropFiles, placeHolderImage").append('
markup here
');
  $(".dragDropTag, .dragDrop, .dragDropIcon, #multiUpload").removeClass("dropped");
  $("#multiUpload").prop('disabled', false);
}

My question is, can this be optimized somehow, so I won't have to write two functions? For example could I wrap it into one function with less duplication? (e.g. instead of rewriting the same lines for adding/removing classes or enabling/disabling input fields, to have one line of code that does different things based on parameters that get passed in?)

A: Basicaly, you can do something like that :
function setElements(remove) {
  var dropIds = $("#dragAndDropFiles, placeHolderImage");
  var dropClasses = $(".dragDropTag, .dragDrop, .dragDropIcon, #multiUpload");

  if (remove) {
    dropIds.remove();
    dropClasses.addClass("dropped");
  } else {
    dropIds.append('
markup here
');
    dropClasses.removeClass("dropped");
  }

  $("#multiUpload").prop('disabled', remove);
}


text:
Q: Auth0 Login in Xamarin Hello I am trying to add Auth0 Login to my Xamarin forms Mobile Application,
I was following the Quick start and And came into a problem. where do i add this code
var client = new Auth0Client(new Auth0ClientOptions
{
    Domain = "******.auth0.com",
    ClientId = "******"
}, this);

I am new to Xamarin and cannot figure out where to add it. I tried to add  it in a seperact file in  Service Folder But Auth0.OidcClient.Android is only installed to my android Project,i Tried to install on main project but it alwasys fails

A: Auth0.OidcClient.Android latest version did not work for me So i used 3.0.1
So the steps i followed
Install Auth0.OidcClient.Android 3.0.1 in Android project
In Mainproject create a IAuthService file(Interface)
 public interface IAuthService
{
    Task<LoginResult> Login();
    Task Logout();
}

Create a AuthenticationService class in Android project
Implement IAuthService,Making a Depandancy injunction
using Xamarin.Forms;
using Auth0.OidcClient;
[assembly: Dependency(typeof(AuthenticationService))]
namespace XamarinAuth02.Droid
{

    public class AuthenticationService
        : IAuthService
    {
        private Auth0Client _auth0Client;

        public AuthenticationService()
        {
            _auth0Client = new Auth0Client(new Auth0ClientOptions
            {
                Domain = AuthConfig.Domain,
                ClientId = AuthConfig.ClientId
            });
        }
        public async Task<LoginResult> Login(new
{ audience = AuthConfig.Audience })
        {
            LoginResult result = await _auth0Client.LoginAsync();
            return result;
        }

        public async Task Logout()
        {
            _ = await _auth0Client.LogoutAsync();
        }
    }
}

In Main Activity in android project
LaunchMode = LaunchMode.SingleTask is importent
[Activity(LaunchMode = LaunchMode.SingleTask, Label = "XamarinAuth02", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]

[IntentFilter(
    new[] { Intent.ActionView },
    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable },
    DataScheme = "com.companyname.xamarinauth02",//package name
    DataHost = "Domain",
    DataPathPrefix = "/android/com.companyname.xamarinauth02ThisMyPackageName/callback")]

protected override void OnNewIntent(Intent intent)
    {
        base.OnNewIntent(intent);
        ActivityMediator.Instance.Send(intent.DataString);
    }

Now u can create a obj of IAuthService and call login / logout
private readonly
IAuthService _authenticationService;

_authenticationService = DependencyService.Get<IAuthService>();
private async void Button_Clicked(object sender, EventArgs e)
        {
            loginresult = await _authenticationService.Login();
            if (loginresult.IsError)
            {
                await DisplayAlert("Error", "Login Failed", "Okay");
            }
            else
            {
                await SecureStorage.SetAsync("accessToken", loginresult.AccessToken);
                await SecureStorage.SetAsync("UserName", loginresult.User.FindFirst(c => c.Type == "name")?.Value);
                IsLoggedIn = true;
                await Navigation.PushAsync(new HomePage(loginresult.User.FindFirst(c => c.Type == "name")?.Value));
            }

        }

Sorry For my Typing Hope this helps someone


text:
Q: Reclassifying a Curvature raster I am trying to reclassify a profile curvature raster generated by the Curvature tool available in ArcGIS into three classes following the tool help where it is reported that;

...a negative value indicates the surface is upwardly convex at that
cell. A positive profile indicates the surface is upwardly concave at
that cell. A value of 0 indicates the surface is flat.

My Curvature raster' values range between -4.726 to 0.543. By supplying class breaks (-4.726, 0, 0.543) in the Reclassify tool yield spurious results where pixels having values == 0, as separately identified by raster calculator, are more in numbers (pixel count) than it should be!
What are optimal class break values to get accurate reclassified Curvature raster?

A: It sounds like you want a Sign function, which I don't think exists in the Raster Calculator.  Instead, you could nest Con functions, like this:
Con("ras"==0,0, Con("ras"<0,-1, 1))

From the help on the Reclassify tool, "the higher end of the lower input range is inclusive, and the lower end of the higher input range is exclusive."


text:
Q: I want to return the length of the longest mirror sub section in an array We'll say that a "mirror" section in an array is a group of contiguous elements such that somewhere in the array, the same group appears in reverse order. For example, the largest mirror section in [1, 2, 3, 8, 9, 3, 2, 1] is length 3 (the [1, 2, 3] part). Return the size of the largest mirror section found in the given array.
maxMirror([1, 2, 3, 8, 9, 3, 2, 1]) → 3
maxMirror([1, 2, 1, 4]) → 3
maxMirror([7, 1, 2, 9, 7, 2, 1]) → 2

A:

const test1 = [1, 2, 3, 8, 9, 3, 2, 1];
const test2 = [1, 2, 1, 4];
const test3 = [7, 1, 2, 9, 7, 2, 1];
const test4 = [21, 22, 9, 8, 7, 6, 23, 24, 6, 7, 8, 9, 25, 7, 8, 9];
const test5 = [1,2,3,2,1];

function maxMirror(arr){

  //set output variable
  let max = 1;

  //test each number
  //for each number, i represents index
  arr.forEach((num, i) => {
      //set default count
      let count = 0;
      //see how many times current num can go up
      //and match the selected end number as it goes down
      //j represents current end starting at array end
      //k iterates up from current num; h iterates down from current end
      //stop loop when current num and current end are the same element
      for(let j = arr.length - 1, k = i, h = j; j > i; k++, h-- ){
        //if values match
        if(arr[k] === arr[h] && k < arr.length && h > -1){
           //keep increasing count
           count ++
        //otherwise
        } else {
          //check if count beats max before updating max
          if(count > max) max = count;
          //reset count for next current num/current end cycle
          count = 0;
          //cycle backwards by 1 to get new current end
          j --;
          //k resets to i (-1 to offset loop ++);
          k = i - 1;
          //h resets to j (+1 to offset loop --)
          h = j + 1;
        }
      }
  });

  return max;
}

console.log(maxMirror(test1));
console.log(maxMirror(test2));
console.log(maxMirror(test3));
console.log(maxMirror(test4));
console.log(maxMirror(test5));


text:
Q: Offset value before grouping I have a couple of items of which one field is a UTC-based unix timestamp multiplied by 1000 in order to include milliseconds while keeping it a long (integer) value.
{
    "title" : "Merkel 'explains' refugee convention to Trump in phone call",
    "iso" : "2017-01-31T04:03:53.807+0000",
    "id" : NumberLong(1485835433807)
}
{
    "title" : "NASA to Explore an Asteroid Containing Enough Mineral Wealth to Collapse the World Economy",
    "iso" : "2017-01-30T23:20:27.327+0000",
    "id" : NumberLong(1485818427327)
}
{
    "title" : "IMGKit: Python library of HTML to IMG wrapper",
    "iso" : "2017-01-30T23:15:39.488+0000",
    "id" : NumberLong(1485818139488)
}

the iso field is just a text string to ease debugging, it has no other purpose.
I intend to use the method described in https://stackoverflow.com/a/26550803/277267 to resample the items, to create a summary of items per day, initially just a count if items per day.
The problem is that the timestamp (the "id" field) can't really be used to archieve this, because of the UTC offset. Depending on the location of the user (or the local insertion time, ie 00:30 monday local time vs 23:30 sunday UTC time, if the timezone is +1h) an item would belong either to one day or the other, so the field lacks this information.
Assuming I just want to add an offset to the "id" field, ie by 3600000, which is one hour expressed in milliseconds, before starting to resample the data based on the "id" field, how can I archieve this in the aggregation pipeline?
Is there a way to have a first stage which takes the "id" field value, add 3600000 to that value and store it into an "id_offsetted" field, on which I can then execute the next stages?

A: Version before 3.4
   {$project: {
        "title" :  1,
        "iso" : 1
        "id" : 1,
        "id_offsetted" : {$add: ["$id", 3600000]}
    } }

Version 3.4 onwards
 {$addFields: {
        "id_offsetted" : {$add: ["$id", 3600000]}
    } }


text:
Q: AngularJS ng-modal do not return latest value from form input I am still new towards AngularJS, I made a simple textarea to handle user input using angular model binding like below code (noted that my ng-app and ng-controller are being injected somewhere else but it is within the entire

):
HTML:

//some other HTML

        <tabset>
            <tab heading="Status">

                    <form class="statusPost" enctype="multipart/form-data">

                                <textarea type="text" ng-model="inputStatus" class="statusPostBox" placeholder="what's new on your mind?"></textarea>

                                <button style="width: 12%;" ng-click="postStatus()" class="btn btn-primary btn-sm" type="button">Share</button>

                    </form>

            </tab>

            <tab heading="Image">Image</tab>
        </tabset>

JS:
'use strict';
var Status = angular.module('Status',['ui.bootstrap','ngResource','ngSanitize'])
Status.controller('StatusCtrl', ['StatusService','$resource','$scope','$http', '$timeout', '$sce',
    function StatusCtrl(StatusService, $resource, $scope, $http, $timeout, $sce) {
        //Usable models
        $scope.inputStatus;

        //Html-bind
        $scope.makeTrust = function(html){
        return $sce.trustAsHtml(html);
        }

        $scope.postStatus = function(){
            if ($scope.inputStatus == null){
                console.log('Blank post alert');
                alert('You cannot post with blank statuses!');
            }else{
                console.log($scope.inputStatus);
            }
        }
}]);

My problem is whenever I click on the submit button angular will always pop me with the empty input error even though I have input in the textarea. At first I thought that I made a mistake in my model binding so I have tried out to echo the value in html using {{inputStatus}}, things appeared as it was typed and also when I try to define a default value in $scope.inputStatus = 'default value', the console does indeed echoed 'default value', but the problem is it doesn't store anything that is being typed in the form. What have i done wrong in my code?
Noted that I am not so familiar on how to setup AngularJS in JSFiddle. I apologize in advance if you would like to see the working demo.
**Update 1 - I have narrow down the problem, apparently the problem only occur when I am using angular tabs by Angular Bootstrap. So what happen is if you revise the HTML code, there is this <tabset> section. When declaring the ng-controller after the <tabset> section and everything works like a charm but if you declare it before the <tabset> section, that is where everything mess up.

A: You should initialize $scope.inputStatus in your controller, otherwise it will pop out an alert windows if you haven't input anything in the textarea (which will initialize or update $scope.inputStatus).
So you change your controller to
$scope.inputStatus = "";

Then everything will work, here is a working demo.
update
If you are using <tabset>, then you are facing child scope problem. <tabset> will create a child scope inside your controller, which means, the scope bind to tabset is the child of scope bind to StatusCtrl.
There are two ways to fix this problem. The first one is accessing the parent scope directly by changing your ngModel to below
<textarea type="text" ng-model="$parent.inputStatus" class="statusPostBox" placeholder="what's new on your mind?"></textarea>

The second one is easier but may looks like a trick, use Dot notation like @lcycook mentioned. In your controller StatusCtrl, declare a dictionary called data
$scope.data = {
    inputStatus: ""
};

Then you can access the inputStatus by data.inputStatus anywhere inside the controller scope and you don't need to care about the child scope.

A: While there is no direct evidence, I suspect your text area is masked inside a child scope. This is common for new AngularJS developers.
While you are learning which directive creates a child scope (e.g. ng-if, ng-repeat), you can avoid this problem with "Dot notation". Which is, wrapping the model inside an object.
You can do this by initializing your ng-model or at least the wrapper object in your controller.
$scope.data = {};
// OR
$scope.data = {inputStatus=''};

Then in your template
<textarea type="text" ng-model="data.inputStatus" class="statusPostBox" placeholder="what's new on your mind?"></textarea>

Process it in your controller by referring it as $scope.data.inputStatus.
Some people even argue you are doing it wrong if you don't do this for any ng-model, but I find thinking wrapper object name is hard so I still use "dotless" one if I know the there is no child scope.


text:
Q: How many different ways can 2 groups of 10 be divided into 10 groups of 2? You'll have to forgive me. Math is definitely not my specialty, but my curiosity got the best of me.
My wife watches the show "Are You The One". Doesn't interest me in the least, but it made me wonder about the odds.
The premise, to my understanding, is this:
20 people--10 male and 10 female have to collectively figure out who their 'perfect matches' are.
Each person has one other person who is supposed to be their perfect match.
I was just wondering what the odds are, or how many combinations can be made of groups of 2 from 2 groups of 10.
At first I thought it was 10 factorial (3628800), but then that didn't seem quite right. Question one: Am I correct in assuming this is the number of permutations of 2 groups of 10 divided into 10 groups of 2 with one from each group?
Then, I thought that it was actually 10 * 10 + 9 * 9 + 8 * 8 ... + 1 * 1, or 385.
Question 2: Is this the number of  combinations of 2 groups of 10 divided into 10 groups of 2, and if so, what is this mathematical operation called (as opposed to factorial)?
Thanks in advance for the help!

A: This answer is assuming that men can only be paired with women and vice-versa.
Line the men in a line side-by-side and do the same for the women in such a way that the men and women are facing one another and that each couple facing one another is considered a match. Notice that if we leave the men fixed, we can achieve any combination of matchings by simply re-ordering the women of which there are $10!$ ways of doing so in which case your original guess is correct.

A: You were close with your guess of $10!$. Assuming anyone can match with anyone else, then the answer is $19!!$, i.e., the double factorial of $19$. This is defined to be:
$$19!! = 19 \cdot 17 \cdot 15 \cdots 3 \cdot 1 = 654,729,075.$$
The reasoning is as follows: let's order the people alphabetically. The first person has a choice of $19$ people; now remove that pair, and $18$ people remain. Repeat the process: take the first person from those $18$, and he or she has a choice of $17$ partners. Remove that pair, and so on.
Note that the value above is also the product of $10$ numbers, just like $10!$, but is substantially larger than $10!$. Since each term in $19!!$ is roughly twice as big as the corresponding term in $10!$, the result is (very roughly) on the order of $2^{10}$ times as big. (It turns out to be $180$ times as big.)

Edit: It wasn't specified in the problem, but if the goal is to match men to women, then yes, your calculation of $10!$ is correct. The first woman has a choice of $10$ men, the next woman has a choice of $9$ men, and so on.


text:
Q: Xamarin.Forms: items text alignment on a picker Is there a way to set right alignment on items text for a Picker? Like this: [1]: https://i.stack.imgur.com/hxf8P.png
I created the following custom renderer, but it doesn't align the items:
[assembly: ExportRenderer(typeof(PickerExtended), typeof(PickerCustomRenderer))]
namespace Vendo.Droid.Renderers
{
 public class PickerCustomRenderer : Xamarin.Forms.Platform.Android.AppCompat.PickerRenderer
 {
     public PickerCustomRenderer(Context context) : base(context) { }

     protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
     {
         base.OnElementChanged(e);

         if (Control != null && e.NewElement != null)
         {
             switch (e.NewElement.HorizontalTextAlignment)
             {
                 case Xamarin.Forms.TextAlignment.Center:
                     Control.Gravity = GravityFlags.CenterHorizontal;
                     break;
                 case Xamarin.Forms.TextAlignment.End:
                     Control.Gravity = GravityFlags.End;
                     break;
             }
         }
     }
 }
} ```

A: You could create your own picker dialog and set the gravity for the item.
Xaml:
   <Picker x:Name="picker"
    Title="Select"
    TitleColor="Red">
        <Picker.ItemsSource>
            <x:Array Type="{x:Type x:String}">
                <x:String>10,38</x:String>
                <x:String>12,535</x:String>
                <x:String>11,67</x:String>
                <x:String>10,665</x:String>

            </x:Array>
        </Picker.ItemsSource>
    </Picker>

Custom Renderer:
[assembly: ExportRenderer(typeof(Picker), typeof(CustomPickerRenderer))]
namespace App1.Droid
{

public class CustomPickerRenderer : PickerRenderer
{
    AlertDialog listDialog;
    string[] items;
    public CustomPickerRenderer(Context context) : base(context)
    {

    }
    protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)
    {
        base.OnElementChanged(e);

        if (Control != null)
        {
            Control.Click += Control_Click; ;
        }

    }

    private void Control_Click(object sender, EventArgs e)
    {
        Picker model = Element;
        items = model.Items.ToArray();
        AlertDialog.Builder builder = new AlertDialog.Builder(this.Context);
        builder.SetTitle(model.Title ?? "");
        builder.SetNegativeButton("Cancel", (s, a) =>
        {
            Control?.ClearFocus();
            builder = null;
        });

        Android.Views.View view = LayoutInflater.From(this.Context).Inflate(Resource.Layout.listview, null);
        Android.Widget.ListView listView = view.FindViewById<Android.Widget.ListView>(Resource.Id.listView1);

        MyAdapter myAdapter = new MyAdapter(items, Element.SelectedIndex);
        listView.Adapter = myAdapter;
        listView.ItemClick += ListView_ItemClick;
        builder.SetView(view);
        listDialog = builder.Create();

        listDialog.Show();

    }

    private void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
    {
        Control.Text = items[e.Position];
        Element.SelectedIndex = e.Position;
        Console.WriteLine(items[e.Position]);
        listDialog.Dismiss();
        listDialog = null;
    }
}

class MyAdapter : BaseAdapter
{
    private string[] items;
    private int selectedIndex;

    public MyAdapter(string[] items)
    {
        this.items = items;
    }

    public MyAdapter(string[] items, int selectedIndex) : this(items)
    {
        this.selectedIndex = selectedIndex;
    }

    public override int Count => items.Length;

    public override Java.Lang.Object GetItem(int position)
    {
        return items[position];
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override Android.Views.View GetView(int position, Android.Views.View convertView, ViewGroup parent)
    {
        if (convertView == null)
        {
            convertView = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.listview_item, null);
        }
        TextView textView = convertView.FindViewById<TextView>(Resource.Id.textView1);
        textView.Text = items[position];
        return convertView;
    }
}
}

listview.xml: You could creat in your Resources/layout in android project.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ListView
       android:id="@+id/listView1"
        android:dividerHeight="2dp"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"/>
</LinearLayout>

listview_item.xml : You could creat in your Resources/layout in android project.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
   <TextView
      android:id="@+id/textView1"
       android:gravity="right"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>
</LinearLayout>


text:
Q: Shared local storage to use in my android application I am a beginner in android application. I want to create an android application, but instead of using a separate database (sqlite, firebase). I want to use my local storage (mobile storage) space itself.
For instance, There are 100 of members using my application. If one of the person want to share some document to others. Instead of sending the document, i want to share only the location to them (along with view or view/download option).
I am trying to achieve the security of the particular share documents. So that i believe it wont go outside my network members who are all using my application.
Each person can act as a server/client. Kind of mesh network topology.
Do we have any option already implemented in any other application.
Kindly help me.


text:
Q: Very simple I/O So I am trying to do some very simple read/writes on a file. Since it's for an assignment I can't use more sophisticated functions using File*.
I can easily create a file and write to it but if I try to read back my content (it's the same content but my problem boils down to this) I don't get what I expect and I can't yet see why.
Here the code snippet that causes me problems:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv){
        int fdisk = open("testfile.txt", O_RDWR | O_CREAT | O_APPEND);
        char buff [20] = "Just a short text!!!";
        write(fdisk, buff, sizeof(buff));
        char buff2[20];
        read((fdisk), buff2, sizeof(buff2));
        printf("Context of deleted file: %c\n",buff[1]);
        printf("Context of deleted file: %c\n",buff2[1]);
        return 0;
}

A: When you create a file you need to specify the file access mode:
int fdisk = open("testfile.txt", O_RDWR | O_CREAT | O_APPEND, 0666);

Otherwise the access mode is some indeterminate value.
And before reading it back you need to rewind it:
lseek(fdisk, 0, SEEK_SET); // rewind

A: The problem is that the write call leaves the file descriptor pointing to just after the data written (so more writes will go after that rather than overwriting the same data), so the following read call tries to read data after that which was written, and probably gets nothing.

A: I think it is a combination of issues:

*

*You are not rewinding or re-opening the file, so when you read you are always reading from the end of the file.

*You are using append mode, so it will add data to the end of the file. This means that after the first run you will be writing data at the end of the file but always reading from the beginning (assuming you address the first problem).

*You are not setting the permissions, so you get random file permissions and the file may not be readable after creating it.

*Your print statement is only printing the second character from each buffer, rather than a full string.

Here is a minimal working example. This compiles and runs with the expected results on my machine.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char** argv){
  int fdisk = open("testfile.txt", O_RDWR | O_CREAT, 0666);
  char buff[] = "Just a short text!!!";
  write(fdisk, buff, sizeof(buff));
  lseek(fdisk, 0, SEEK_SET);
  char buff2[sizeof(buff)];
  read((fdisk), buff2, sizeof(buff2));
  printf("Context of deleted file: %s\n",buff);
  printf("Context of deleted file: %s\n",buff2);
  return 0;
}

As a final note, the functions you are using (read/write) all return values indicating whether the operation was successful. You should check them. They would have indicated that the read operation in your problem was not actually reading any data (because it was at the end of the file).


text:
Q: Lua: Functions with Multiple Returns For some reason, I'm having issues wrapping my head around the appropriate way to use parameters in a function, and later call for that function and return the correct parameters.  If I wanted to use a function to find out the type of shape used.  This shape contains data right after the shape abbreviation, such as Sq105428, that I would like to use. Quick Ex:
function Shape(...) -- can I use "..." or should I put "Type, Shape_data, Shape_side" inside?
    Shapes = {["Tri"] = 3, ["Sq"] = 4, ["Po"] = 5, ["Hex"] = 6}
        for k,v in pairs (Shapes) do
            Type = string.match(input, k..".*")
                if Type == k then
                    Shape_data = string.match(input,Type.."(.*)")
                    Shape_side = v
                end
        end
        return Type, Shape_data, Shape_side -- can I call for these later in my code?
end

Later, I would call for the variables returned and use them.  I'm having problems understanding how to properly call for those variables that were returned.  In my code, I would like to take the three variables and use them throughout the code.  How would I properly call for them?
I understand that:
function f() body end  ==  f = function() body end -- pg 15 PIL and helps me to understand

I also understand how to properly use mathematical functions such as:
function exp (x)
    print x^2
end

print exp(4) -- yields 16

But what is the appropriate way to call for my example if I want to use the three variables at different points of the code?  I'm having problems completely understanding how to properly construct the function call and call for that later.  Is it as easy as:
Example = math.floor(math.pi * Shape(Shape_side) + 0.5) -- is this ok?

I appreciate the help.

A: That's not exactly right. First, you're setting global variables within your function, but if they are just temporaries used for your function, you should definitely use locals.
Now back to your function:
function(...)

means that you want to receive variable number of arguments in your function without assigning tchem to any variable yet. To use these arguments, you need to assign them to named variables, like this:
local side, type, data = ...

or use select function.
What you really want (I guess from your call to math.floor) is just tell the function, which data is should return. To do that, you don't need multiple arguments, you just need one argument:
function shape(what)

Then based on what's in what, return only that data, or (for example), if what is not provided, return all the data needed:
if what == "side" then
    return side
elseif what == "whatever" then
    return whatever
elseif not what then
    return side, whateveer
else
    return nil
end

Of course that's just an example. To use multiple return values, you need to store them somewhere:
local side, whatever = shape() -- returns multiple values, because `what` is nil
local result = math.floor(math.pi * side + 0.5)

About efficiency of your function:
It looks like it's suboptimal at best. Each time you call the function, it's parsing the input provided. So if you want to get data, it has to go over the input, if you want to get shape's side, it has to go over the input again. Each time you call the function, you're redeclaring a global Shapes.
It's also best if functions don't operate on global variables at all (apart from calling some other global functions, for example). It makes them more universal (for instance parse input from provided variables, not from a global input).
I might be misunderstanding your function's purpose, but I would go about it a bit differntly:
local Shapes = {["Tri"] = 3, ["Sq"] = 4, ["Po"] = 5, ["Hex"] = 6} -- create a closure

function Shape(input)
    for k, v in pairs(Shapes) do
        local type = string.match(input, k) --I thinkg with your match you'd never get past the next line
        if type then --no need to do the comparison, as type would be nil if no match is found
            return k, string.match(input, k.."(.*)"), v
        end
    end
    return nil --erroneous input, no match found
end

Now you would store all the data you need and simply later use it without having to reinvoke the function and parse the input again:
local type, data, side = Shape(userInput)

Or better yet, have the function return a table and access the data in a nicer way:
...
if type then --no need to do the comparison, as type would be nil if no match is found
    return {type = k, data = string.match(input, k.."(.*)"), side = v}
end
...

and then store the data as:
local userShape1 = Shape(userInput1)
local userShape2 = Shape(userInput2)
--now use the results
local result1 = math.floor(math.pi * userShape1.side + 0.5)
local result2 = math.floor(math.pi * userShape2.side + 0.5)
local dataResult1 = processShapeData(userShape1.data)

Now this is slower than multiple local values, but it's cleaner, imo, which is important, if you're new to Lua. There are some other things that could make the function better, faster (like requiring input to start with shape type), but I won't bore you with that.
So back to your original question, to use multiple return values, you need to store them in variables. If your function returns multiple values, but you only make assignment to one variable, the rest of the data is discarded:
local type = Shape(input) --assuming the function returns multiple values, not a table


text:
Q: Upsert (Update or Insert) without locking in SQL Server I've been reading about possible solutions on upsert. In particular, this thread here, where the solution for Upsert went along the lines of:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...)
END
COMMIT TRANSACTION;

However, with ISOLATION LEVEL SERIALIZABLE, I'll be introducing a lock at the table level, correct? Which is not ideal, as there will potentially be a lot of operations over that table using the Upsert.
I think we introduce the ISOLATION LEVEL SERIALIZABLE in the first place to prevent the issue where two concurrent transactions would be trying to update the same record non yet existent record and one of them would then fail INSERTing it. However, I was thinking of doing the following to solve that problem without the lock:
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  BEGIN TRY
    INSERT dbo.table(PK, ...)
  END TRY
  BEGIN CATCH
    IF ERROR_NUMBER() = 2627
    BEGIN
      UPDATE dbo.table SET ... WHERE PK = @PK;
    END
  END CATCH
END
COMMIT TRANSACTION;

In this case, if the INSERT would fail, it would mean that in the mean time some other concurrent transaction inserted a row. Then, we would do the Update again.
However, I'm concerned if ERROR Handling is actually more expensive than using SERIALIZABLE. What do you guys think?
Thanks!


text:
Q: Add signature to email I'm trying to utilize my default signature when I send an automated email.
My code pastes the location of the signature rather than the signature itself.
Sub CreateEmailForGTB()

    Dim wb As Workbook

    Set wb = Workbooks.Add
    ThisWorkbook.Sheets("BBC").Copy After:=wb.Sheets(1)

    'save the new workbook in a dummy folder
    wb.SaveAs "location.xlsx"

    'close the workbook
    ActiveWorkbook.Close

    'open email
    Dim OutApp As Object
    Dim OutMail As Object
    Dim newDate: newDate = Format(DateAdd("M", -1, Now), "MMMM")
    Dim sigstring As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    sigstring = Environ("appdata") & _
                "\Microsoft\Signatures\zbc.htm"

    'fill out email
    With OutMail
        .To = "abc@domain.com;"
        .CC = "xyz@domain.com;"
        .BCC = ""
        .Subject = "VCR - CVs for BBC " & "- " & newDate & " month end."
        .Body = "Hi all," & vbNewLine & vbNewLine & _
                 "Please fill out the attached file for " & newDate & " month end." & vbNewLine & vbNewLine & _
                 "Looking forward to your response." & vbNewLine & vbNewLine & _
                 "Many thanks." & vbNewLine & vbNewLine & _
                 sigstring

A: There's another way to grab to display the signature in a email message, that in easier to use in my opinion. It does require that you have set up your signature to display on new messages by default.
See the routine I have set up below for how to implement.
Sub SendMail(strTo As String, strSubject As String, strBody As String, strAttachments As String, Optional strCC As String, Optional strFolder As String, Optional blSend As Boolean)

'*******************************************************************
'**    Sub:         SendMail
'**    Purpose:     Prepares email to be sent
'**    Notes:       Requires declaration of Outlook.Application outside of sub-routine
'**                 Passes file name and folder for attachments separately
'**                 strAttachments is a "|" separated list of attachment paths
'*******************************************************************

'first check if outlook is running and if not open it
Dim olApp As Outlook.Application

On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
On Error GoTo 0
If olApp Is Nothing Then Set olApp = New Outlook.Application

Dim olNS As Outlook.Namespace
Dim oMail As Outlook.MailItem

'login to outlook
Set olNS = olApp.GetNamespace("MAPI")
olNS.Logon

'create mail item
Set oMail = olApp.CreateItem(olMailItem)

'display mail to get signature
With oMail
    .display
End With

Dim strSig As String
strSig = oMail.HTMLBody

'build mail and send
With oMail

    .To = strTo
    .CC = strCC
    .Subject = strSubject
    .HTMLBody = strBody & strSig

    Dim strAttach() As String, x As Integer
    strAttach() = Split(strAttachments, "|")

    For x = LBound(strAttach()) To UBound(strAttach())
        If FileExists(strFolder & strAttach(x)) Then .Attachments.Add strFolder & strAttach(x)
    Next

    .display
    If blSend Then .send

End With

Set olNS = Nothing
Set oMail = Nothing

End Sub

A: You need to actually get the text from the file as opposed to just setting the filepath as a string like you are now. I'd suggest something like this:
Function GetText(sFile As String) As String

   Dim nSourceFile As Integer, sText As String

   ''Close any open text files
   Close

   ''Get the number of the next free text file
   nSourceFile = FreeFile

   ''Write the entire file to sText
   Open sFile For Input As #nSourceFile
   sText = Input$(LOF(1), 1)
   Close

   GetText = sText

End Function

Source: http://www.exceluser.com/excel_help/questions/vba_textcols.htm
You can then simply use this in your code:
sigstring = GetText(Environ("appdata") & "\Microsoft\Signatures\zbc.htm")

A: Your variable sigstring literally is just the name of the file - you never read the file contents.
To read the contents try this (and don't forget to declare a variable (text and line in my example) to hold the file contents).
sigstring = Environ("appdata") & "\Microsoft\Signatures\zbc.htm"
Open sigstring For Input As #1
Do Until EOF(1)
    Line Input #1, line
    text = text & line
Loop
Close #1

A: You can add your default signature by  entering the items .Display right after your With statements and adding .body on the body message. see below code
With OutMail
.Display
.To = "abc@domain.com;"
     .CC = "xyz@domain.com;"
    .BCC = ""
    .Subject = "VCR - CVs for BBC " & "- " & newDate & " month end."
    .Body = "Hi all," & vbNewLine & vbNewLine & _
             "Please fill out the attached file for " & newDate & " month end." & vbNewLine & vbNewLine &  .body
             "Looking forward to your response." & vbNewLine & vbNewLine & _
             "Many thanks." & vbNewLine & vbNewLine