text:
Q: minimum length video for tracking milestones with sitecatalysts We are tracking videos with the media plugin and have configured it to track events at start, 25%, 50%, 75% and 100%. This works fine for our longer videos (2+ minutes), but short videos (<30s) are only sending start and 100%. Can't find any documentation on this nor has the PS been helpful. Anyone run into a similar issue?
EDIT: With the following params set
s.Media.autoTrack=false;
s.Media.trackWhilePlaying=true;
s.Media.trackVars="events,prop27,eVar23,eVar24,eVar25,eVar26";
s.Media.trackEvents="event21,event22,event23,event24,event25,event26,event27";
s.Media.trackMilestones="25,50,75";
s.Media.segmentByMilestones = true;
s.Media.trackUsingContextData = true;


text:
Q: Проверка пользователя, не понимаю как изменить import json

filename = 'numbers.json'

def get_new_username():
    """Получает новое имя пользователя"""
    username = input("What is your name? ")
    filename = 'numbers.json'
    with open(filename, 'w') as f_obj:
        json.dump(username, f_obj)
    return username

def get_storage_name():
    """Получает хранимое имя пользователя, если оно существует"""
    try:
        with open(filename) as f_obj:
            username = json.load(f_obj)
    except FileNotFoundError:
        return None
    else:
        return username

def greet_user():
    username = get_storage_name()
    if username:
        print("Welcome back, " + username + "!")
    else:
        username = get_new_username()
        print("We'll remember you when you come back " + username)

Как ее нужно изменить на тот случай, если текущий пользователь не является тем человеком, который последним использовал программу?

A: def itsyou():
    username = get_storage_name()
    print(username)
    a = input("its you?      <yes> or <not>: ")
    if a == "not":
        username = get_new_username()
        print("We'll remember you when you come back " + username)
        get_storage_name()
    else:
        greet_user()

itsyou()

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Web API & Android app - Error anti-forgery token could not be decrypted on POST with Cookie Ok, continuing from my previous question, where I stated that adding a Cookie to an Android HttpPost isn't that hard: It is hard(er than I thought)..
I use the following HttpPost method in my Android app:
@Override
protected String doInBackground(String... urls){
    String response = "";
    for(String url : urls){
        HttpPost post = new HttpPost(url);
        try{
            URL u = new URL(url);
            String baseUrl = u.getProtocol() + "://" + u.getHost();

            // POST-request requires anti-forgery Cookie
            CookieManager cookieManager = CookieManager.getInstance();
            String cookie = cookieManager.getCookie(baseUrl);
            post.setHeader("Cookie", cookie);

            // POST-request requires cookieToken, provider and returnUrl
            String[] cookieStrings = cookie.split("=");
            List<NameValuePair> nvPairs = new ArrayList<NameValuePair>(3);
            nvPairs.add(new BasicNameValuePair(cookieStrings[0], cookieStrings[1]));
            nvPairs.add(new BasicNameValuePair("provider", "Google"));
            nvPairs.add(new BasicNameValuePair("returnUrl", baseUrl));
            post.setEntity(new UrlEncodedFormEntity(nvPairs));

            HttpResponse execute = client.execute(post);

            // Get the response of the POST-request
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while((s = buffer.readLine()) != null)
                response += s;
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    return response;
}

When I debug the response, I'm getting the following error:

The anti-forgery token could not be decrypted. If this application is
  hosted by a Web Farm or cluster, ensure that all machines are running
  the same version of ASP.NET Web Pages and that the <machineKey>
  configuration specifies explicit encryption and validation keys.
  AutoGenerate cannot be used in a cluster.

I've Googled this error and found this link. Here they add a machineKey to the C# Web.config. I checked and this machineKey is already present in my C# project of the Web API.
So, reading the error above, I believe it's caused because I'm just running HttpPost and HttpGet requests from the Android App (which is the Web Farm or cluster part? Am I correct in this?
And more importantly, how do I fix this error in Android so I can send my Cookie + CookieToken successfully, so I'm logged in with the POST-request. Cause then I can start using GET-requests that are [Authorized] from the same DefaultHttpClient.
Thanks in advance for the responses.

Edit 1:
After reading the answers from this stackoverflow question:

*

*I don't have more than one @Html.AntiForgeryToken() on one page.

*The machineKey was already added to the Web.config as mentioned before.

A: Ok, this error is solved.. Turned out I had three cookies instead of one, so with the string-split I had part of the next cookie with the string token. So that's solved now by getting all cookies separately (splitting with ";"), and then splitting the correct cookie with "=" to send it.
After I did that however, if received a next error:

Validation of the provided anti-forgery token failed. The cookie
  "__RequestVerificationToken" and the form field
  "__RequestVerificationToken" were swapped.

But at least I can continue again and the error above is solved.


text:
Q: with cer file working and sign string files or xml files. Please help us I have some problems with x509certificates class.
These codes are working with usb stick. But not working ".cer" files.
Public Function signString(ByVal msg As String, ByVal imzasahibi As String) As String
    Dim unicode As Encoding = Encoding.UTF8
    Dim msgBytes As Byte() = unicode.GetBytes(msg)

    Dim signerCert As X509Certificate2 = GetSignerCert(imzasahibi)
    Dim encodedSignedCms As Byte() = SignMsg(msgBytes, signerCert)

    Dim result As String = Convert.ToBase64String(encodedSignedCms)

    If Not VerifyMsg(msgBytes, encodedSignedCms) Then
        Throw New Exception("Any problems")
    End If

    Return result
End Function

Public Function MesajImzala(ByVal msg As String, ByVal imzasahibi As String) As String
Dim sertifikamiz As String = HttpContext.Current.Server.MapPath("certificateFiles/testFile.cer")
Dim signerCert As X509Certificate2 = X509Certificate2.CreateFromCertFile(sertifikamiz)
    Dim unicode As Encoding = Encoding.UTF8
    Dim msgBytes As Byte() = unicode.GetBytes(msg)

    Dim encodedSignedCms As Byte() = SignMsg(msgBytes, signerCert)

    Dim result As String = Convert.ToBase64String(encodedSignedCms)

    If Not VerifyMsg(msgBytes, encodedSignedCms) Then
        Throw New Exception("Any problems")
    End If

    Return result
End Function

if you want i send files. Thank you all...
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: 'System.Security.Cryptography.X509Certificates.X509Certificate' türündeki nesne 'System.Security.Cryptography.X509Certificates.X509Certificate2' türüne atılamadı.

A: .CER files usually contain only the certificate without a private key. To sign data you must have the private key. This is why you can't sign the data with just a .cer file.


text:
Q: How Do You Add a Query String That Automatically Updates to a CSS File Included in Another CSS File via the @import Rule? I've got one CSS file included in a larger CSS file via the @import rule. The larger CSS file has a query string that gets automatically updated via a plugin for the CMS we use. However, the query string only forces the browser to reload the main CSS file and not the imported one.
Is there a way to have the @imported CSS file, embedded within the other CSS file, get an automatically updated query string?
Thanks!


text:
Q: Avoid Mean of Floating Point Error When I calculate the mean of a list of floats the following way
def mean(x):
    sum(x) / len(x)

then I usually do not care about tiny errors in floating point operations. Though, I am currently facing an issue where I want to get all elements in a list that are equal or above the list's average.
Again, this is usually no issue but when I face cases where all elements in the list are equal floating point numbers than the mean value calculated by the function above actually returns a value above all the elements. That, in my case, obviously is an issue.
I need a workaround to that involving no reliability on python3.x libraries (like e.g. statistics).
Edit:
It has been suggested in the comments to use rounding. This interestingly resulted in errors being rarer, but they still occur, as e.g. in this case:
[0.024484987, 0.024484987, 0.024484987, 0.024484987, ...]  # x
0.024485  # mean
[]  # numbers above mean

A: I believe you should be using math.fsum() instead of sum. For example:
>>> a = [0.024484987, 0.024484987, 0.024484987, 0.024484987] * 1360001
>>> math.fsum(a) / len(a)
0.024484987

This is, I believe, the answer you are looking for. It produces more consistent results, irrespective of the length of a, than the equivalent using sum().
>>> sum(a) / len(a)
0.024484987003073517

A: One neat solution is to use compensated summation, combined with double-double tricks to perform the division accurately:
def mean_kbn(X):
    # 1. Kahan-Babuska-Neumaier summation
    s = c = 0.0
    n = 0
    for x in X:
        t = s + x
        if abs(s) >= abs(x):
            c -= ((s-t) + x)
        else:
            c -= ((x-t) + s)
        s = t
        n += 1
    # sum is now s - c

    # 2. double-double division from Dekker (1971)
    # https://link.springer.com/article/10.1007%2FBF01397083
    u = s / n # first guess of division

    # Python doesn't have an fma function, so do mul2 via Veltkamp splitting
    v = 1.34217729e8 #  0x1p27 + 1
    uv = u*v
    u_hi = (u - uv) + uv
    u_lo = u - u_hi
    nv = n*v
    n_hi = (n - nv) + nv
    n_lo = n - n_hi
    # r = s - u*n exactly
    r = (((s - u_hi*n_hi) - u_hi*n_lo) - u_lo*n_hi) - u_lo*n_lo
    # add correction
    return u + (r-c)/n

Here's a sample case I found, comparing with the sum, math.fsum and numpy.mean:
>>> mean_kbn([0.2,0.2,0.2])
0.2
>>> sum([0.2,0.2,0.2])/3
0.20000000000000004
>>> import math
>>> math.fsum([0.2,0.2,0.2])/3
0.20000000000000004
>>> import numpy
>>> numpy.mean([0.2,0.2,0.2])
0.20000000000000004

A: How about not using the mean but just multiplying each element by the length of the list and comparing it directly to the sum of the original list?
I think this should do what you want without relying on division


text:
Q: how to printout help text using getopt in C? I have a question about use getopt with command with the following code:
void createFunction()
{
   printf("create function\n");
}

void printHelp()
{
   printf("print help info\n");
}

const struct option long_opts[] = {{"help", no_argument, NULL, HELP},
                                   {"c",    no_argument ,NULL, CREATE_OPTION},
                                   {NULL,   0,           NULL, 0}};

while((opt = getopt_long_only(argc, argv, "", long_opts, NULL)) != -1)
{
    switch(opt) {
        case HELP:
            printHelp();
            break;
        case CREATE_OPTION:
            createFunction();
            break;
        default:
            printf("type base --help for details\n");
    }
}

how to printout the help text when type command without any parameters or with any faulty parameters,
for example: only type command(in my case is "base") to trigger a printout of the help text? or command "base --" will trigger help text? Can anyone help?

A: You can use '?' case to trigger when an unrecognized option is passed :
case '?':
    printf("Unknown option `-%c'.\n", optopt);
    printHelp();
    break;


text:
Q: Extracting a part of a string up to a number in PHP I have various strings of data that I need to extract up to the first number occurance in the string.  For example, I may have the following:
John Doe12 Somewhere Lane
Basically I need the part of the string up to the number 1 (John Doe), and then I need the rest of the string (12 Somewhere Lane).  The string will not have a space between the name and the street address, so the number of the address will always be right up against the last name.  I don't know if this makes a difference but I figured I'd let it be known.
So is there a way to break the string apart like this using PHP?
Update:
@CMPS recommended the following, which works in the instance below when there is one name:
$result = "John Doe12 Somewhere Lane";
preg_match("/([a-zA-Z ]+)(\d.*)/", $result, $matches);
print_r($matches);

//************************ RESULTS FOR ABOVE SAMPLE ********************//
Array([0]=> John Doe12 Somewhere Lane [1]=> John Doe [2]=> 12 Somewhere Lane)
For the sample below, it only produces one name after the & sign, producing the same result as above:
$result = "Jane Doe & John Doe12 Somewhere Lane";
preg_match("/([a-zA-Z ]+)(\d.*)/", $result, $matches);
print_r($matches);

//************************ RESULTS FOR ABOVE SAMPLE ********************//
Array([0]=> John Doe12 Somewhere Lane [1]=> John Doe [2]=> 12 Somewhere Lane)

A: Live demo
Use regex, here's the pattern:
([a-zA-Z ]+)(\d.*)

Here's how to use it with PHP:
Live demo
<?php
$str = "John Doe12 Somewhere Lane";
preg_match("/([a-zA-Z ]+)(\d.*)/", $str, $matches);

print_r($matches);

Update
Here's another regex based on your comment:
([^0-9]+)(\d.*)


text:
Q: Problema ao gerar valor aleatório usando a classe Random O programa está gerando um valor aleatório, mas às vezes ele estoura a array, ou simplesmente não exibe nada.
Exemplos do erro:

Meu código:
import java.util.Scanner;
import java.util.Random;

public class Sorteio {

    public static void main(String []args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Informe o numero de pessoas no sorteio: ");
        int n = sc.nextInt();

        String pessoa [] = new String [n];

        for (int i = 0; i < n; i++) {
            System.out.println("Informe a " + (i + 1) + "a pessoa: ");
            pessoa[i] = sc.nextLine();
            if (i == 0) sc.nextLine();
        }

        Random rd = new Random();

        System.out.println("O vencedor do sorteio e: " + pessoa[rd.nextInt(n)]);
    }
}

A: O problema é esse seu if (i == 0) sc.nextLine(); que está no lugar errado.
Observe que isso está depois da linha anterior que tem o pessoa[i] = sc.nextLine();. Assim, ele não atribuir uma string vazia ao nome de pessoa[0] e vai pular o nome que deveria ser da primeira pessoa. Assim, quando ele não mostra nada é porque a primeira pessoa havia sido sorteado.
A solução é retirar o if e mover esse sc.nextLine(); para logo após o sc.nextInt();:
import java.util.Scanner;
import java.util.Random;

class Sorteio {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Informe o numero de pessoas no sorteio: ");
        int n = sc.nextInt();
        sc.nextLine();
        String[] pessoas = new String[n];
        for (int i = 0; i < n; i++) {
            System.out.println("Informe a " + (i + 1) + "a pessoa: ");
            pessoas[i] = sc.nextLine();
        }
        Random rd = new Random();
        for (int j = 0; j < 200; j++) {
            System.out.println("O vencedor do sorteio e: " + pessoas[rd.nextInt(n)]);
        }
    }
}

Observe que coloquei o sorteio sendo efetuado 200 vezes para te mostrar que sempre dá uma resposta que seja um dos nomes e nunca dá uma exceção.
Veja aqui funcionando no ideone.

A necessidade de utilizar esse nextLine() para esvaziar o buffer é meio ruim. A solução é eliminar o nextInt() e só usar o nextLine():
import java.util.Scanner;
import java.util.Random;

class Sorteio {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Informe o numero de pessoas no sorteio: ");
        int n = Integer.parseInt(sc.nextLine());
        String[] pessoas = new String[n];
        for (int i = 0; i < n; i++) {
            System.out.println("Informe a " + (i + 1) + "a pessoa: ");
            pessoas[i] = sc.nextLine();
        }
        Random rd = new Random();
        for (int j = 0; j < 200; j++) {
            System.out.println("O vencedor do sorteio e: " + pessoas[rd.nextInt(n)]);
        }
    }
}

Veja aqui funcionndo o ideone.
Esse comportamento estranho ocorre com o sc.nextInt() e com o sc.nextLine() por causa desses motivos:

*

*O System.in é o objeto que fornece a outros objetos aquilo que o usuário digitou.

*O System.in armazena o que o usuário digitou em uma área de memória denominada de buffer.

*Outros objetos (no caso o Scanner) podem solicitar ao System.in para fornecer alguns dos caracteres ou bytes digitados pelo usuário. (Ele trabalha com bytes, mas esses são interpretados/convertidos em caracteres pelo Scanner).

*Quando existe alguma coisa no buffer e o System.in é solicitado a fornecer alguns bytes, ele irá fornecê-los ao retirá-los do início do buffer. Se sobrarem bytes excedentes no buffer, eles continuarão lá.

*Quando o buffer estiver vazio e o System.in for solicitado a fornecer alguns bytes, ele vai travar e esperar o usuário digitar algum texto terminado com enter. Esse texto, inclusive o enter é armazenado no buffer e então segue-se o que está no item anterior: alguns bytes são retirados do início do buffer e entregues. Quaisquer bytes excedentes permanecem lá.

*Quando o método nextLine() do Scanner for chamado, ele vai consumir todos os bytes que encontrar até encontrar o enter e devolver isso que ele consumiu sem o enter. Ou seja, ele vai consumir a primeira linha do que estiver no System.in e descartar o enter.

*Já o método nextInt() funciona de uma forma diferente, ele vai consumir apenas os bytes que correspondam a dígitos, deixando o enter para trás dentro do buffer.

*Desta forma, temos uma diferença importante: O nextLine() consome e descarta o enter no final da linha, mas o nextInt() o deixa lá. É por isso que o nextLine() após o nextInt() é necessário e ele devolve uma string vazia. A função dele é retirar o enter que foi largado no começo do buffer pelo nextInt().

*Esse comportamento incoerente é resolvido ao usar-se apenas o nextLine() e abandonar o nextInt(). O Integer.parseInt(String) é usado para transformar a linha lida em um número.


text:
Q: Error (Cannot get property "subscribe" of undefined) in react-redux trySubscribe with Internet Explorer My React won't load on Internet Explorer 10 (Working correctly with Chrome and FF).
I'm getting error :
TypeError: Cannot get property "subscribe" of undefined
at trySubscribe
at componentDidMount
at notifyAll
at close
at closeAll
at perform
at perform
at perform
at m
at close

(translated)
the trySubscribe function is in react-redux ( src/components/connect.js ):
trySubscribe() {
        if (shouldSubscribe && !this.unsubscribe) {
          this.unsubscribe = this.store.subscribe(this.handleChange.bind(this))
          this.handleChange()
        }
      }

So it seems that this.store is undefined but I don't know why ?

A: Found it !
I was using a container component extending another container component, and both of them where decorated with @connect !
So I was trying to @connect a component which was not part of the components tree !
After removing @connect from superclass, problem solved !
(Actually I completely removed the superclass (not used anymore) and extended directly Component).


text:
Q: Inline if shell script Is it possible to execute shell script in command line like this :
counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ] then; echo "true";
>

Above example is not working I get only > character not the result I'm trying to get, that is "true"
When I execute ps -ef | grep -c "myApplication I get 1 output. Is it possible to create result from single line in a script ? thank you

A: Other responses have addressed your syntax error, but I would strongly suggest you change the line to:
test $(ps -ef | grep -c myApplication) -eq 1 && echo true

If you are not trying to limit the number of occurrences to exactly 1 (eg, if you are merely trying to check for the output line myApplication and you expect it never to appear more than once) then just do:
ps -ef | grep myApplication > /dev/null && echo true

(If you need the variable counter set for later processing, neither of these solutions will be appropriate.)
Using short circuited && and || operators is often much clearer than embedding if/then constructs, especially in one-liners.

A: Yes, with syntax issues fixed
That almost worked. The correct syntax is:
counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true"; fi

But note that in an expression of this sort involving ps and grep, the grep will usually match itself because the characters "grep -c Myapplication" show up in the ps listing. There are several ways around that, one of them is to grep for something like [M]yapplication.

A: I am using Mac OS and following worked very well
$ counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true";fi;

true
Space is needed after [ and before ]

A: It doesn't work because you missed out fi to end your if statement.
counter=`ps -ef | grep -c "myApplication"`; if [ $counter -eq 1 ]; then echo "true"; fi

You can shorten it further using:
if [ $(ps -ef | grep -c "myApplication") -eq 1 ]; then echo "true"; fi

Also, do take note the issue of ps -ef | grep ... matching itself as mentioned in @DigitalRoss' answer.
update
In fact, you can do one better by using pgrep:
if [ $(pgrep -c "myApplication") -eq 1 ]; then echo "true"; fi

A: I was struggling to combine both multiple lines feed into command and getting its results into a variable (not a file) and come up with this solution:
    FRA_PARAM="'db_recovery_file_dest'"
    FRA=$(
    sqlplus -S "/as sysdba" <<EOF
set echo off head off feed off newpage none pages 1000 lines 1000
select value from v\$parameter where name=$FRA_PARAM;
exit;
EOF
        )

Please note that single-quotes word was substituted, because otherwise I was receiving its autosubstitution to double quotes... ksh, HP-UX.
Hopefully this will be helpful for somebody else too.


text:
Q: How to display different images for non logged users in WooCommerce shop page? I'm using WooCommerce under the WordPress platform to create my e-commerce shop, but I want to display the archive shop page images for logged-in users only.
Non-logged-in users will see placeholders that prevents them to see the images of the shop.
I have followed this tutorial which seems exactly what I'm looking for, but no visual results accord, I believe this hook is either irrelevant or deprecated.
//Display different images for non-logged in users
add_filter( 'woocommerce_placeholder_img_src', 'growdev_custom_woocommerce_placeholder', 10 );

function growdev_custom_woocommerce_placeholder( $image_url ) {
    if ( is_user_logged_in() ) {
        return;
    }
  $image_url = 'https://vps1420.secured-cloud.net/wp-content/uploads/2021/04/516.webp';  // change this to the URL to your custom placeholder
  return $image_url;
}

Right now the images continue to display as usual (no matter if I'm logged in or not).
How can I display different images for unregistered users in WooCommerce?

A: You can use woocommerce_before_shop_loop_item_title action hook. first remove woocommerce_before_shop_loop_item_title hook then add that hook again and use is_user_logged_in() to check user logged in or not. code goes to your active theme functions.php file.

Use this woocommerce_get_product_thumbnail() funciton to get product
thumbnail.
Use this wc_placeholder_img() funciton to get product placeholder
image.

// Remove product images from the shop loop
function remove_shop_images() {
    remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
}
add_action( 'after_setup_theme', 'remove_shop_images' );

function display_product_image_based_on_logged_in(){
    if( is_user_logged_in() ){
        echo woocommerce_get_product_thumbnail();
    }else{
        echo wc_placeholder_img();
    }
}
add_action( 'woocommerce_before_shop_loop_item_title', 'display_product_image_based_on_logged_in', 10 );


text:
Q: Conflicts between CSS Menu and Image as Links There is logo on the top (image as link) and other images as links. These links are not working in FF and safari. The problem is with css/ul/li based navigation menu. If I remove the menu html code, images as links are working fine. The css based navigation menu is based on this code:
/* Navigation Menu */
#nav a, #nav a:hover, #nav a:focus {...}
#nav {...}
#nav ul {...}
#nav .menu .level1-li {...}
#nav .menu a {...}
#nav .menu a.level1-a {...}
#nav .menu .sub {...}
#nav .menu .sub a {...}
#nav .menu a:hover {...}

I am not much familiar with CSS and this is the example I have downloaded from the web. It seems "a" is doing something wrong here.
Prashant

A: #nav a, #nav a:hover, #nav a:focus {direction:ltr; outline:0;}
#nav {background:#252525; background:url(../images/tabs_0.gif) repeat-x left top;height:30px; font:normal 12px/30px arial, verdana, sans-serif; width:800px; margin:0 auto;border-bottom-style:solid;border-width:1px;border-color:#525151;}
#nav ul {margin:0; padding:0; list-style:none; display:inline-block;}
#nav .menu .level1-li {float:left; display:inline; width:160px; margin-top:-32000px;}
#nav .menu a {background:transparent;display:block; font-weight:bold; width:160px; text-decoration:none; text-align:center; color:#fff;}
#nav .menu a.level1-a {position:relative; float:left; display:inline; margin-right:-159px; margin-top:32000px;}
#nav .menu .sub {background:#F6C739;float:left; margin-top:-30px; padding-top:30px; margin-bottom:-32000px;}
#nav .menu .sub a {background:#4a4a4a; font-weight: normal; font-size: 9pt;text-align:left; position:relative; margin-right:-1px;text-indent:10px;}
#nav .menu a:hover {background:#F6C739;margin-right:0px; color:#000000;}


text:
Q: Object null when trying to convert JSON string to object I am trying to convert JSON from this format
    [
    {
        "id": 1,
        "firstName": "John",
        "lastName": "Smith",
        "company": {
            "id": 19297,
            "identifier": "XYZTestCompany",
            "name": "XYZ Test Company",
            "_info": {
                "company_href": "zzzzzzzzzzzz",
                "mobileGuid": "2685633f-6375-43"
            }
        },
        "site": {
            "id": 1502,
            "name": "Main",
            "_info": {
                "site_href": "zzzzzzzzz"
            }
        },
        "inactiveFlag": false,
        "title": "President",
        "marriedFlag": false,
        "childrenFlag": false,
        "unsubscribeFlag": false,
        "gender": "Male",
        "mobileGuid": "afghgfdfgh",
        "defaultPhoneType": "Direct",
        "defaultPhoneNbr": "00000000",
        "defaultBillingFlag": false,
        "defaultFlag": false,
        "companyLocation": {
            "id": 1,
            "name": "Company",
            "_info": {
                "location_href": zzzzzzzz"
            }
        },
        "communicationItems": [
            {
                "id": 10,
                "type": {
                    "id": 2,
                    "name": "Name",
                    "_info": {
                        "type_href": "zzzzzzz"
                    }
                },
                "value": "8",
                "defaultFlag": true,
                "communicationType": "Phone"
            }
        ],
        "types": [
            {
                "id": 2,
                "name": "Name",
                "_info": {
                    "type_href": "zzzzzzzz"
                }
            }
        ],
        "customFields": [
            {
                "id": 41,
                "caption": "Type",
                "type": "Text",
                "entryMethod": "List",
                "numberOfDecimals": 0
            },
            {
                "id": 42,
                "caption": "Synce",
                "type": "Checkbox",
                "entryMethod": "EntryField",
                "numberOfDecimals": 0
            }
        ],
        "ignoreDuplicates": false,
        "_info": {
            "lastUpdated": "2015-10-03T05:59:47Z",
            "updatedBy": "Portal",
            "communications_href": "z",
            "notes_href": "z",
            "tracks_href": "z",
            "portalSecurity_href": "z",
            "activities_href": "z",
            "documents_href": "z",
            "configurations_href": "z",
            "tickets_href": "z",
            "opportunities_href": "z",
            "projects_href": "z",
            "image_href": "z"
        }
    },
    {
     more of the same
        },

Into this format
    public class ContactJson
    {
        public List<Contact> Contact { get; set; }
    }
    public class Contact
    {
        public int id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
        public Company company { get; set; }
        public string site { get; set; }
        public bool inactiveFlag { get; set; }
        public string title { get; set; }
        public bool marriedFlag { get; set; }
        public bool childrenFlag { get; set; }
        public bool unsubscrubeFlag { get; set; }
        public string gender { get; set; }
        public string mobileGuid { get; set; }
        public string defaultPhoneType { get; set; }
        public string defaultPhoneNbr { get; set; }
        public bool defaultbillingflag { get; set; }
        public bool defaultFlag { get; set; }
        public string companyLocation { get; set; }
        public string communicationItems { get; set; }
        public string types { get; set; }
        public string customFields { get; set; }
        public bool ignoreDuplicates { get; set; }
        public string info { get; set; }

    }
    public class Company
    {
        public int id { get; set; }
        public string name { get; set; }
        public string info { get; set; }
    }

I am parsing it like this
    var ConnectwiseClient = new RestClient("https://api-      aus.myconnectwise.net/v4_6_release/apis/3.0//company/contacts/");
    var request = new RestRequest()
    {
        Method = Method.Get,
        Timeout = 300000
    };
    request.AddHeader("clientID", "");
    ConnectwiseClient.Authenticator = new HttpBasicAuthenticator("");

    var response = ConnectwiseClient.Execute(request);

    var result = JsonConvert.DeserializeObject<List<ContactJson>>(response.Content);

The result object then has a count of 25 which is the amount of items returned but all of the items in this object are null
The result object then has a count of 25 which is the amount of items returned but all of the items in this object are null. When looking at the response object I know that the response isn't null.

A: Assuming response.Content is exactly what you say it is, then you have the following problems:

*

*Your class is expecting strings for a few fields that are classes. Quickfix is to make them objects. For example

public object site { get; set; }
...
public object companyLocation { get; set; }
public object communicationItems { get; set; }
public object types { get; set; }
public object customFields { get; set; }
...
public object info { get; set; }

*You are Deserializing into the wrong object.Should be

JsonConvert.DeserializeObject<List<Contact>>
instead of
JsonConvert.DeserializeObject<List<ContactJson>>

*You're missing a " under companyLocation.location_href but that might be just in your SO question because if it was missing the code it would just throw istead of giving you nulls


text:
Q: Error 3709 in VBA/macros A runtime error of 3709 keeps popping up when I run this part of the program.  Does anyone know what I can do to fix it?
Public cn As New ADODB.Connection

Public rs As New ADODB.Recordset

Public CustomerID As Integer

Public CustFirstName As String

Public CustLastName As String

Sub GetCustomerList()

    Dim strSQL As String
    Dim Customers As Variant

    ' Import customer info and use it to populate the list box.
    ' After frmcustomers is unloaded, we will know the CustomerID
    ' and Customer Name of the selected order.

    strSQL = "SELECT CustomerID, CustFirstName, CustLastName FROM Customers"
    rs.Open strSQL, cn

    frmCustomers.Show

    rs.Close
End Sub

Thanks,
JM

A: I got the same error code when trying to edit one specific record. It was a regular record, with no data or validation inconsistency.
Apparently this was a random data corruption issue, the 1st I believe to have gotten after some years working with MS Access (just for statistical reference, not a pro or con statement!)
Problem solved by running Compact And Repair routine.

A: Solved,
I got this error "3709 the search key was not found in any record", while using this code :
DoCmd.CopyObject , "Data_OldCurrentMemberDetails", acTable, "Data_CurrentMemberDetails"

Leter what I leant is it was an issue with the name of my file which contained "[, ]" (square brackets).
To avoid these kind of errors keep your file names in plain text i.e Do not include "[, ], %, ..."

A: From the error you are reporting, it would seem that at the point you call GetCustomerList() the connection is not open.

A: In a database, when you create a Memo field that includes an index or when it creates a field name that contains the text automatically indexed, it can not write to the text field that includes more than 3450 characters or so. When you try to write more text in the field or modify existing data, receive an error message similar to the following Exception 3709
http://support.microsoft.com/kb/302525

A: Just for completeness, I get error 3709 (the search key was not found in any record) when trying to import an Excel spreadsheet that has a leading or trailing space in a column header. Remove that and it goes away. This is in Access 2013.


text:
Q: UWP App With Azure Mobile Apps Backend Offline Data Sync Issue I am developing a UWP app in C# that uses an Azure backend to sync from an Azure SQL Database to the local device SQLite database.  This has worked fine since the initial implementation.
Now I am running into an issue when trying to sync larger images.  Images smaller than ~ 3MB successfully convert from StorageFile to byte[] and are saved in the SQLite database and synced to the Azure DB.  However, images larger than ~ 3MB have issues syncing.  They will convert to byte[] and display properly, but the attempt to sync fails with this error:
"The HTTP request did not include a valid entity body.  Please ensure there is an entity body and an associated Content-Type header present in the request."
On the server end, this manifests as a malformed syntax error.
All images are processed exactly the same.  The web.config file has been altered to allow the requestLimits maxAllowedContentLength="2147483648".  The column in the Azure database is set to varbinary(MAX).
This code calls the method to convert the selected file to byte[]:
byte[] image = await ImageUtils.ChooseImageFile();

Here is the conversion method:
public static async Task<byte[]> ChooseImageFile()
    {
        FileOpenPicker openPicker = new FileOpenPicker();
        openPicker.ViewMode = PickerViewMode.Thumbnail;
        openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
        openPicker.FileTypeFilter.Add(".jpg");
        openPicker.FileTypeFilter.Add(".jpeg");
        openPicker.FileTypeFilter.Add(".png");
        StorageFile file = await openPicker.PickSingleFileAsync();

        if (file == null)
            return null;

        byte[] bytes = null;
        using (var stream = await file.OpenReadAsync())
        {
            bytes = new byte[stream.Size];
            using (var reader = new DataReader(stream))
            {
                await reader.LoadAsync((uint)stream.Size);
                reader.ReadBytes(bytes);
            }
        }
        return bytes;
    }

The caller method then assigns the byte[] to the Image property of the entity.
On syncing, I am using the following method:
public async Task SyncOfflineCacheAsync()
    {
        try
        {
            await InitializeAsync();

            await _client.SyncContext.PushAsync();

            await PullTables();
        }
        catch (MobileServicePushFailedException ex)
        {
            if (ex.PushResult != null)
            {
                foreach (var error in ex.PushResult.Errors)
                {
                    await ResolveConflictAsync(error);
                }
            }
        }
    }

Which is where it fails on PushAsync() with the above error.
Is there some sort of implicit size limit for syncing images this way?  I noticed the string representation of the byte[] displays as base64 for the larger images and hexadecimal for the smaller images, but I couldn't find any information on whether this is related to the issue.  The byte[] itself appears to be correct.
Thank you!

A:
The web.config file has been altered to allow the requestLimits maxAllowedContentLength="2147483648".

maxAllowedContentLength specifies the maximum length of content in a request supported by IIS, whereas maxRequestLength indicates the maximum request size supported by ASP.NET, So you need to set both in order to upload large files: the smaller one "takes priority".
The default value of maxRequestLength is 4096 KB (4 MB), so that you may need to set this value as well.
<system.web>
  <compilation debug="true" targetFramework="4.7"/>
  <httpRuntime targetFramework="4.7" maxRequestLength="102400"/>
</system.web>

See this thread for more details.


text:
Q: MappedSuperclass maps all child entities to one child I have the TranslationBase base abstract class, and tow subclasses[entities] : CountryTranslation and RegionTranslation as shown below :
TranslationBase:
@MappedSuperclass
@IdClass(TranslationBasePK.class)
public abstract class TranslationBase<T> implements Serializable {

    @Id
    @ManyToOne
    @JoinColumn(name = "id")
    private T ownerEntity;

    @Id
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @Column(name = "language_id")
    private Long languageId;

    private String name;
}

CountryTranslation :
@Entity
@Table(name = "country_translation")
public class CountryTranslation extends TranslationBase<Country> {
}

RegionTranslation :
@Entity
@Table(name = "region_translation")
public class RegionTranslation extends TranslationBase<Region> {
}

And TranslationBasePK :
public class TranslationBasePK implements Serializable {

    private Long ownerEntity;

    private Long languageId;
}

On DB i found the id column in CountryTranslation and RegionTranslation tables reference to Country table id !!
I expect CountryTranslation to reference the id of Country and RegionTranslation to reference the id of Region class.
Note : Country and Region have @Id feild named id;


text:
Q: lock-free synchronization, fences and memory order (store operation with acquire semantics) I am migrating a project that was run on bare-bone to linux, and need to eliminate some {disable,enable}_scheduler calls. :)
So I need a lock-free sync solution in a single writer, multiple readers scenario, where the writer thread cannot be blocked. I came up with the following solution, which does not fit to the usual acquire-release ordering:
class RWSync {
    std::atomic<int> version; // incremented after every modification
    std::atomic_bool invalid; // true during write
public:
  RWSync() : version(0), invalid(0) {}
  template<typename F> void sync(F lambda) {
    int currentVersion;
    do {
      do { // wait until the object is valid
        currentVersion = version.load(std::memory_order_acquire);
      } while (invalid.load(std::memory_order_acquire));
      lambda();
      std::atomic_thread_fence(std::memory_order_seq_cst);
      // check if something changed
    } while (version.load(std::memory_order_acquire) != currentVersion
        || invalid.load(std::memory_order_acquire));
  }
  void beginWrite() {
    invalid.store(true, std::memory_order_relaxed);
    std::atomic_thread_fence(std::memory_order_seq_cst);
  }
  void endWrite() {
    std::atomic_thread_fence(std::memory_order_seq_cst);
    version.fetch_add(1, std::memory_order_release);
    invalid.store(false, std::memory_order_release);
  }
}

I hope the intent is clear: I wrap the modification of a (non-atomic) payload between beginWrite/endWrite, and read the payload only inside the lambda function passed to sync().
As you can see, here I have an atomic store in beginWrite() where no writes after the store operation can be reordered before the store. I did not find suitable examples, and I am not experienced in this field at all, so I'd like some confirmation that it is OK (verification through testing is not easy either).

*

*Is this code race-free and work as I expect?

*If I use std::memory_order_seq_cst in every atomic operation, can I omit the fences? (Even if yes, I guess the performance would be worse)

*Can I drop the fence in endWrite()?

*Can I use memory_order_acq_rel in the fences? I don't really get the difference -- the single total order concept is not clear to me.

*Is there any simplification / optimization opportunity?
+1. I happily accept any better idea as the name of this class :)

A: The code is basically correct.
Instead of having two atomic variables (version and invalid) you may use single version variable with semantic "Odd values are invalid". This is known as "sequential lock" mechanism.
Reducing number of atomic variables simplifies things a lot:
class RWSync {
    // Incremented before and after every modification.
    // Odd values mean that object in invalid state.
    std::atomic<int> version;
public:
  RWSync() : version(0) {}
  template<typename F> void sync(F lambda) {
    int currentVersion;
    do {
      currentVersion = version.load(std::memory_order_seq_cst);
      // This may reduce calls to lambda(), nothing more
      if(currentVersion | 1) continue;

      lambda();

      // Repeat until something changed or object is in an invalid state.
    } while ((currentVersion | 1) ||
        version.load(std::memory_order_seq_cst) != currentVersion));
  }
  void beginWrite() {
    // Writer may read version with relaxed memory order
    currentVersion = version.load(std::memory_order_relaxed);
    // Invalidation requires sequential order
    version.store(currentVersion + 1, std::memory_order_seq_cst);
  }
  void endWrite() {
    // Writer may read version with relaxed memory order
    currentVersion = version.load(std::memory_order_relaxed);
    // Release order is sufficient for mark an object as valid
    version.store(currentVersion + 1, std::memory_order_release);
  }
};

Note the difference in memory orders in beginWrite() and endWrite():

*

*endWrite() makes sure that all previous object's modifications have been completed. It is sufficient to use release memory order for that.

*beginWrite() makes sure that reader will detect object being in invalid state before any futher object's modification is started. Such garantee requires seq_cst memory order. Because of that reader uses seq_cst memory order too.
As for fences, it is better to incorporate them into previous/futher atomic operation: compiler knows how to make the result fast.

Explanations of some modifications of original code:
1) Atomic modification like fetch_add() is intended for cases, when concurrent modifications (like another fetch_add()) are possible. For correctness, such modifications use memory locking or other very time-costly architecture-specific things.
Atomic assignment (store()) does not use memory locking, so it is cheaper than fetch_add(). You may use such assignment because concurrent modifications are not possible in your case (reader does not modify version).
2) Unlike to release-acquire semantic, which differentiate load and store operations, sequential consistency (memory_order_seq_cst) is applicable to every atomic access, and provide total order between these accesses.

A: The accepted answer is not correct. I guess the code should be something like "currentVersion & 1" instead of "currentVersion | 1". And subtler mistake is that, reader thread can go into lambda(), and after that, the write thread could run beginWrite() and write value to non-atomic variable. In this situation, write action in payload and read action in payload haven't happens-before relationship. concurrent access (without happens-before relationship) to non-atomic variable is a data race. Note that, single total order of memory_order_seq_cst does not means the happens-before relationship; they are consistent, but two kind of things.


text:
Q: How do I modify this query in MYSQL? SELECT title, title REGEXP 'apple' as is_fruit FROM mytable;

TO:
SELECT title, title REGEXP 'apple' or orange...or grapes...as is_fruit...

Basically, how do I do an "OR" for REGEXP?

A: SELECT title, title REGEXP '(apple|orange|...)' as is_fruit FROM mytable;


text:
Q: How can I manipulate tibbles in my list with R? I am pretty sure that has been asked previously, but as I am stuck to proceed although the considerable amount of search.
I needed to ask:
18 xlsx files and all are the same structure. Each of size is: 40X7. They belong to different subjects. My first variable/vector is event_number starting from 1 to 40 for each subject/files.
I want to create data frames for each event containing all subjects: so I should have 40 data frames(event_number with 18X7 size(number of subjects X #_of_other variables) in the end.
Any suggestions how can I loop over subjects?
What I did so far was:
path <- "my_path"
url_xlsx <- list.files(path, pattern = "*.xlsx", recursive = TRUE)
read_xlsx_files <- function(x){df <- read_xlsx(path = paste(path, x, sep = "/"))
return(df)}
df <- lapply(url_xlsx, read_xlsx_files )
df <- as.list(df)
analyze <- function(filename) {
  file_subj <- separate_rows(df[[i]], 1, sep = ",")
  split(file_subj, file_subj$event_number)
}
bb <- lapply(df, FUN = analyze)

Actually, I have all tibbles in bb, but I couldn`t proceed to manipulate through the list.
Thank you so much in advance!!


text: Q: Diagonalizing classes of matrix I know that the class of circulant matrices is diagonalized by the Discrete Fourier Transform Matrix. Are there other any such classes of matrices diagonalized by other well-known matrices?


text:
Q: Does not boot ubuntu?
Possible Duplicate:
How can I repair grub? (How to get Ubuntu back after installing Windows?)

I had Ubuntu installed. When I installed ubuntu I completely formated the hard disk and then I made 3 partitions, one for root, one for home, and one for data.I left 25 Gb unused.
All partitions were ext 4. After some months now I have installed the Windows 8 in the free space(24GB) . Now it directly boots Windows 8 and does not ask for the choice between Windows 8 and ubuntu . I can only access the partition in which I have installed the Windows. I want it to ask for choice between Windows 8 or ubuntu or some other way to run ubuntu or to access the data in the other partitions . Because I have very imported data there. I'm using Hp Pavilion dv6 i3 . 320gig hard disk.

A: I think your win8 install put the win8 bootloader in sector 0 (the so-called
MBR = master boot record,) and destroyed your grub loader there.
There is a story on linuxbsdos.com  (google dual boot win7 linux)
that may help you fix the windows boot-loader to boot your ubuntu system
if you can get grub written in your ubuntu boot directory. (This
will be chain loading from windows to grub.)
One good thing is that since your hp dv6 is pre win8, you probably
do not have an uefi bios that would cause a lot of trouble.


text:
Q: How to Post List of Objects through AJAX to Spring Controller? I am trying to POST a list of forms through AJAX.
$('html').on('click', '#update-cartentries', function() {
  var forms = $('html').find("form.updateCartForm");
  alert('there are : ' + forms.length + ' forms');
  var entryData = new Array();

  $("form.updateCartForm").each(function(index, element) {
    var updatedQty = $(element).find('input[name=quantity]').val();
    var initialQuantity = $(element).find('input[name=initialQuantity]').val();
    var entryNumber = $(element).find('input[name=entryNumber]').val();

    if (initialQuantity != updatedQty) {
      var entry = {};
      entry.entryNumber = entryNumber;
      entry.quantity = updatedQty;
      entryData.push(entry);
    }
  });

  alert('Entry Data: ' + entryData);

  if (entryData.length > 0) {
    $.ajax({
      url: '/update-entries',
      type: 'POST',
      data: {
        "entries": entryData
      },
      success: function(response) {
        // alert("Success" + response);
        window.location.reload();
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // log the error to the console
        // alert("Something Went wrong" + errorThrown);
        console.log("The following error occurred: " + textStatus, errorThrown);
      }
    });
  }
});

The controller method:
@RequestMapping(value = "/update-entries", method = RequestMethod.POST)
@ResponseBody
public String updateCartEntries(final Model model, @RequestBody final UpdateCartEntryList entries, final BindingResult bindingResult,
                                final HttpServletRequest request, final RedirectAttributes redirectModel) throws CMSItemNotFoundException
{
  // ...
}

It is not hitting the controller method and generates a 405 error code in the browser.
The UpdateCartEntryList class has a List of another object which has 2 properties, entryNumber and quantity.
Can anyone tell me the correct process or code to resolve the issue? Is anything wrong in the code? Please identify and let me know.


text:
Q: Assigning new values to polygon based on overlapping area with other polygons I have two square polygons df1 and df2. Both polygons are assigned a value of 10 (df1) and 20 (df2) in the "content" column. Let's assume, I have a circle with the midpoint 1.5,1.5 and a radius of 1.
How can I assign to this circle a new value "content", based on the overlap with the other polygons?
For example, one third of the circle overlaps with df1 and one third of the circle overlaps with df2. In this case, the circle would then obtain 10 * 1/3 + 20 * 1/3 as a value for "content".
from shapely.geometry import Polygon
import geopandas

polys1 = geopandas.GeoSeries([Polygon([(0,0), (2,0), (2,2), (0,2)])])

polys2 = geopandas.GeoSeries([Polygon([(1,1), (3,1), (3,3), (1,3)])])

df1 = geopandas.GeoDataFrame({'geometry': polys1, 'df1':[1], 'content':[10]})

df2 = geopandas.GeoDataFrame({'geometry': polys2, 'df2':[1], 'content':[20]})

ax = df1.plot(color='red');
df2.plot(ax=ax, color='green', alpha=0.5);

A:
from shapely.geometry import Polygon, Point
import geopandas

polys1 = geopandas.GeoSeries([Polygon([(0,0), (2,0), (2,2), (0,2)])])
polys2 = geopandas.GeoSeries([Polygon([(1,1), (3,1), (3,3), (1,3)])])

df1 = geopandas.GeoDataFrame({'geometry': polys1, 'df1':[1], 'content':[10]})
df2 = geopandas.GeoDataFrame({'geometry': polys2, 'df2':[1], 'content':[20]})

#Geometries
geom1 = df1.iloc[0].geometry
geom2 = df2.iloc[0].geometry
circle = Point(1.5, 1.5).buffer(1)

#Areas
area_common = geom1.intersection(geom2).area
area1 = circle.intersection(geom1).area
area2 = circle.intersection(geom2).area

#Ratio excluding brown area
ratio1 = (area1 - area_common) / circle.area #ratio of blue area
ratio2 = (area2 - area_common) / circle.area #ratio of yellow area

#Ratio including brown area
#ratio1 = area1 / circle.area
#ratio2 = area2 / circle.area

content = df1.iloc[0].content * ratio1 + df2.iloc[0].content * ratio2
df3 = geopandas.GeoDataFrame({'geometry': circle, 'df3':[1], 'content':content})

ax = df1.plot(color='red')
df2.plot(ax=ax, color='green', alpha=0.5);
df3.plot(ax=ax, color='yellow', alpha=0.5);


text:
Q: String variable comparison with value failing in php Here is the array $item_meta_data I am working on:

And here is the code I have:
$found = false;
foreach( $item_meta_data as $key => $meta ){
                if( $meta['name'] == "Hardware" && $meta['display'] == "Free-Standing Hardware (max height = 14')" ) {
                    $found = true;
                    break;
                }
            }

The $meta['display'] == "Free-Standing Hardware (max height = 14')" is unexpectedly failing...I used double quotes to wrap the value because there's a single quote in the value. I have also checked the value is string:

Can anyone point out if there's something wrong with the if statement? Interestingly, everything works if array has a simpler value in $meta['display']
PS: I have also tried the triple === comparative $meta['display'] === "Free-Standing Hardware (max height = 14')" with no effect


text:
Q: Dynamic connection to Database ASP.NET I want write autorization system in asp.net - user of Postgres (which created throws CREATE ROLE...) entering login and password and working with own tables. Problem is i working in ASP.NET core and connecting throws Dapper.
appsettings.json
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "DBInfo": {
    "Name": "coresample",
    "ConnectionString": "User ID=username;Password=userpassword;Host=localhost;Port=5432;Database=Documents;Pooling=true;"
  }
}

DocumentsRepository
public class DocumentsRepository : IRepository<Documents>
    {
        private string connectionString;

        public DocumentsRepository(IConfiguration configuration, string login, string password)
        {
            connectionString = configuration.GetValue<string>("DBInfo:ConnectionString");
            connectionString = connectionString.Replace("username", login);
            connectionString = connectionString.Replace("userpassword", password);
        }

        internal IDbConnection Connection
        {
            get
            {
                return new NpgsqlConnection(connectionString);
            }
        }

        public void Add(Documents item)
        {
            using (IDbConnection dbConnection = Connection)
            {
                dbConnection.Open();
                dbConnection.Execute("SELECT addrecuserdocuments(@DocumentName,@Contents,@DocumentIntroNumber)", item);
            }
        }

        public IEnumerable<Documents> FindAll()
        {
            using (IDbConnection dbConnection = Connection)
            {
                dbConnection.Open();
                return dbConnection.Query<Documents>("SELECT * FROM selectdata()");
            }
        }

DocumentController
public class DocumentsController : Controller
    {
        private readonly DocumentsRepository dRepository;

        public DocumentsController(IConfiguration configuration)
        {
            dRepository = new DocumentsRepository(configuration);
        }

        public IActionResult Index()
        {
            return View(dRepository.FindAll());
        }

        public IActionResult Create()
        {
            return View();
        }

        // POST: Documents/Create
        [HttpPost]
        public IActionResult Create(DocumentViewModel dvm)
        {
            Documents docs = new Documents { DocumentName = dvm.DocumentName, DocumentIntroNumber = dvm.DocumentIntroNumber };

            if (ModelState.IsValid)
            {
                if (dvm.Contents != null)
                {
                    byte[] imageData = null;
                    using (var binaryReader = new BinaryReader(dvm.Contents.OpenReadStream()))
                    {
                        imageData = binaryReader.ReadBytes((int)dvm.Contents.Length);
                    }
                    docs.Contents = imageData;
                }
                dRepository.Add(docs);
                return RedirectToAction("Index");
            }
            return View(docs);
        }

In Startup.cs i connection throws
services.AddSingleton(Configuration);
Please, help me understand, how i can call connection string and transfering login and password of user? And where? And is it possible?
Please, i realy need help with this!


text:
Q: How does Google App Engine (GAE) Java server check if it a backend? I want the server to know if it's a backend or not preferably already during
contextInitialized(final ServletContextEvent event)

(but less preferably when the first HTTP request arrives).
I tried
BackendServiceFactory.getBackendService().getCurrentBackend()

but it is always returning null (at least locally in Google Eclipse plugin) even when it is a backend and even in the context of an incoming http request!

A: Update.
    BackendServiceFactory.getBackendService().getCurrentBackend()

DOES work on product but not in the Eclipse plugin.  Would still like a version that works for both. Perhaps this is just a bug:
http://code.google.com/p/googleappengine/issues/detail?id=8058&thanks=8058&ts=1346615492


text:
Q: i wanted to play .mp4 video in windows phone 7.5 but it doesn't work with PHP I have coded it for android and Iphone but it doesn't work in Windows Phone 7.5.
I search into forums but I've found nothing.
the device opens the player but doesn't load video.
I don't know what headers are needed, any idea?
my code for android is this:
$file

$fp = @fopen($file, 'rb');

$size   = filesize($file); // File size
$length = $size;           // Content length
$start  = 0;               // Start byte
$end    = $size - 1;       // End byte

header('Content-type: video/mp4');
header("Accept-Ranges: 0-$length");
if (isset($_SERVER['HTTP_RANGE'])) {

    $c_start = $start;
    $c_end   = $end;

    list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
    if (strpos($range, ',') !== false) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    if ($range == '-') {
        $c_start = $size - substr($range, 1);
    }else{
        $range  = explode('-', $range);
        $c_start = $range[0];
        $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
    }
    $c_end = ($c_end > $end) ? $end : $c_end;
    if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
        header('HTTP/1.1 416 Requested Range Not Satisfiable');
        header("Content-Range: bytes $start-$end/$size");
        exit;
    }
    $start  = $c_start;
    $end    = $c_end;
    $length = $end - $start + 1;
    fseek($fp, $start);
    header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);
header("Content-Disposition: inline; filename=".$outname);

$buffer = 1024 * 8;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {

    if ($p + $buffer > $end) {
        $buffer = $end - $p + 1;
    }
    set_time_limit(0);
    echo fread($fp, $buffer);
    flush();
}

fclose($fp);
exit();

A: Windows Phone 7.5 supports the MP4 container with the following codecs (source):

*

*AAC-LC

*AAC+

*eAAC+

You should try to open the video and debug on the Desktop version of IE9 (it has the same codebase as Mobile IE9).


text:
Q: FindIndex value continuously returning as a -1? I have the following expressions:
This fetches the ID parameter passed through the URL:
editUserId = this.route.snapshot.paramMap.get('id');

Then i used FindIndex on an array of objects to find the index of an element in the array equal to the above mentioned ID value fetched from the URL:
this.userToUpdate = this.allUsers.findIndex((x: any) => x.UserId === this.editUserId);

(this.allUsers) being my array of objects.
Although the findIndex continuously returns the value -1 ..
I have tried the following two methods, both of which return the same error: "This condition will always return 'false' since the types 'number' and 'string | null' have no overlap":
this.userToUpdate = this.allUsers.findIndex((x: any) => parseInt(x.UserId) === this.editUserId);

this.userToUpdate = this.allUsers.findIndex((x: any) => Number(x.UserId) === this.editUserId);

Any reason as to why this may be happening?

A: Seventh, I guess that can be the editUserId needs to be number, you can try it:

this.userToUpdate = this.allUsers.findIndex((x: any) => Number(x.UserId) === Number(this.editUserId));

or

editUserId = this.route.snapshot.paramMap.get('id');
editUserId = Number(editUserId)

I guess it because when you return the params to your variable, always it will be string


text:
Q: PHP WebSocket doesn't connect I'm using Ratchet to create a PHP WebSocket connection. On my localhost it's working normally and as expected, but when I upload it to my server it just stops working.
I'm using an online shared hosting and this is the code on the PHP file:
$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new Chat()
        )
    ), 8000, '0.0.0.0'
);

And this is my JS file
var socket = new WebSocket('ws://mywebsite.com:8000');

The only error I got is this:

Error in connection establishment: net::ERR_CONNECTION_REFUSED

Note: I've already ran php server.php to initiate the ws server via SSH command. I got no errors there but still can't connect. I also tried using different port but nothing seems to be working.

Why I'm trying to use WebSockets?
I have an e-commerce and I'm using the WebSockets to load/update each order without needing to refresh the page and also without using JavaScript Interval, so if an order change from 'Packing..' to 'Delivery' status, the system autoupdate without needing to refresh the page.
If there is another way around this, I'm open to ideas, as long as I can get the final result.


text:
Q: Swift 4 - AVMetadataObject stringValue has incomplete information when reading pdf417 barcode I'm trying to read information from a barcode type PDF417 with the AVFoundation library.
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
    if let metadataObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
        print(metadataObj.stringValue)//prints 0357379329
    }
}

At the point of execution for the didOutput method in the "AVCaptureMetadataOutputObjectsDelegate", I can capture the AVMetadataObject and its stringValue; nevertheless the stringValue has not complete information contained in the barcode, it generates something like this:
0357379329
I can see more information when I use paid applications like BlinkId.
According to this topic, I tried to use the "_internal.basicDescriptor" method:
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
    if let metadataObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
        if let basic_descriptor = metadataObj.value(forKeyPath: "_internal.basicDescriptor") as? NSObject {
            if let barcodeRawData = basic_descriptor.value(forKeyPath: "BarcodeRawData") as? NSData {
                let barcode_raw_data_length = barcodeRawData.length
                let memory_layout = MemoryLayout<UInt8>.size
                let count = barcode_raw_data_length / memory_layout
                var array = [UInt8](repeating: 0, count: count)//Array con 1050 elementos. Cada elemento es igual a cero
                barcodeRawData.getBytes(&array, length:count * memory_layout)
                let data_character = array.reduce("", { $0 + String(format: "%c", $1)})
                print(data_character)
            }
        }
    }
}

data_character prints a string with something like this that I don't know how to interpret:
ÍHÕÛ+ÝY-<4mI ËÇ;ÚÖ
ÂÿûJhiòþ
^HT¶îèm½C3&îðÜ,Feæ»0æ¤öc$¯#m,WÆç4Pá$Ññü0njtYÜ0U¼ÇçA°'£aR.)9
Êq3uúù7=,~mV½Qý;áu½7ó&æiTÝJ¸ËõÚAZähc¨à¼Ø²BsÇKZÖëu-Õß/³©îprX×Ijßçól{¡¿ý...
I would like to know any of these:

*

*How can I get the AVMetadataObject stringValue with the whole info?

*How can I interpret the string generated with the "_internal.basicDescriptor"?

*Is there another method to get info from a pdf417 in swift 4?

Thanks!


text:
Q: (Material-table)Unable to fetch my option list to lookup field of the table column Currently, I have a useEffect code like this, trying to obtain my preset options from axios get request and send it to the lookup field of the table column
  const [optionList, setOptionList] = useState({});

  const [columns, setColumns] = useState({
    columns: [
      {
        title: 'Image_ID',
        field: 'image_ID',
        lookup: optionList,
      },
    ]
  });

  useEffect(() => {
    const getOption = async () => {
      let data = [];
      let options = {};
      const response = await axios.get(sampleUrl);
      const { data: { image_sample } } = response;
      image_sample.map((item) => {
        data.push(item.image_ID);
      });
      data.forEach(item => options[item] = item);
      setOptionList(JSON.stringify(options));
    }
    getOption();
  }, [])

Everything went well in the console, my optionList look exactly what I wanted:
{"p01":"p01","p02":"p02","p03":"p03"} However, the table options remained empty. But if you directly fetch the optionList manually to the column like this:
  const [columns, setColumns] = useState({
    columns: [
      {
        title: 'Image_ID',
        field: 'image_ID',
        lookup: {"p01":"p01","p02":"p02","p03":"p03"},
      },
    ]
  });

It will work for some reason. At some point, I suspect the optionList has already been sent to the table before my useEffect was mounted. Anyone has an idea what's happening?

A: Because initialize of columns.columns[0].lookup state have set by value of optionList. In the first render, this state recieve a {} until useEffect call, inside useEffect setOptionList was called to change optionList state, optionList had change but column state not change cause this component not re-render to show what you want to see.
If you want fix it, just add useEffect with dependencies includes optionList and have function setColumns:
const [optionList, setOptionList] = useState({});

  const [columns, setColumns] = useState({
    columns: [
      {
        title: 'Image_ID',
        field: 'image_ID',
        lookup: optionList,
      },
    ]
  });

  useEffect(() => {
    const getOption = async () => {
      let data = [];
      let options = {};
      const response = await axios.get(sampleUrl);
      const { data: { image_sample } } = response;
      image_sample.map((item) => {
        data.push(item.image_ID);
      });
      data.forEach(item => options[item] = item);
      setOptionList(JSON.stringify(options));
    }
    getOption();
  }, [])

  useEffect(() => {  // <== Add this useEffect
    setColumns({
     columns: [
      {
       title: 'Image_ID',
       field: 'image_ID',
       lookup: optionList,
      },
     ]
   })
  }, [optionList])


text:
Q: Feedback on PCB-layout wanted I'm currently making a weather station as a personal project. It will consist of one BLE peripheral and one BLE central. I will fabricate both as one PCB, and panelize them with a vcut.
As mentioned earlier, this is a personal project, so I would love to get some feedback on the layout so I can improve the design, and myself as a designer.
Some things worth mentioning:

*

*2-layer design

*Uses Renesas DA14531mod BLE-modules

*Battery powered (3V0)

*Will display data on e-paper display through SPI.

Here is the schematic:

Here is the top layer:

And here is the bottom layer:

As I'm using the same ground for both PCBs in the schematic, there is a netline visible in the layout (over the vcut).

A:
Feedback on PCB-layout wanted

*

*Reserve the GND flood for the blue side

*Minimize the length of any tracks that are not GND on the blue side

*Where possible use the red-side flood for power supplies like 3.3 volts

*Follow recommendations in data sheets for PCB layout

These are all obvious tracks to move (almost in their entirety) to the red-side: -

*Try and place components all on one side of the PCB

Reason: minimize disruption of the GND plane to vastly improve EMI withstand and EMI generation. If that means extra vias that's OK in most cases.

A: Just some observations:

*

*Your schematic is basically an accumulation of components and net labels. One can make a case for personal preference for sure, but just having a lot of labels makes it very hard to understand signal flow and the basic logic of the circuit. Arrange your components in a reasonable way and connect them with wires instead of labels.

*You should try to have an as solid as practicable GND plane on the bottom layer. Only route signals on the bottom layer if you absolutely have to. And when you have to, keep them as short as possible.

*I'm not really a fan of "multiple boards in one" trickery. Your split GND net is an obvious example: Your CAD tool will flag this as an error. Once you start ignoring/disabling design rule checks you are asking for trouble eventually.
Also you accidentally created an inside "radius" that needs to be milled. Since that inside radius is zero, the outcome is undefined as it will depend on the milling tool size of your fabricator. Or your order might get "on hold" for clarification.
Then you had to come up with weird net names like "SDL_2" or "BME_VDD" to keep the nets of the boards separated.
Depending on your fabricator my guess is that a two-in-one board won't provide much cost advantage anyway. Since it appears to be a low volume project, you'll probably order the boards from a pooling service. So the boards will probably end up on the same panel anyway and you can let the fabricator worry about panelizeation.

*V-Scoring makes sense for high volume production where a whole panel is filled with multiple instances of a single design. Since you'll probably use a pooling service, v-scoring might not make much sense.


text:
Q: I have question about one2many and many2one field in odoo 10 If the user has already selected a value (list generated from Many2one) in a record, Now I don't want to show that value in the list that is generated from Many2one fields for any new value (records), this edit can performed in .xml file

A: Setup another One2many field field_ids on the comodel that is the model in related in the Many2one relationship. Add an Integer field relation_count with computed function _get_size, that computed function depends on the One2many field field_ids and returns the size of that field. Now on the view, set domain to the Many2one field such that [('relation_count', '=', 0)], which will only limit to list records that is not yet selected, thus relation count being 0.


text:
Q: How to create a python function passing an information to refer a case I would like to create a function where we can specify an information as a string input. The result will be change by the information and an error might be raised if the information is not correct
i mean something like this small example :
def f(a,b,method='repartition uniforme'):
  if method=='repartition uniforme':
    return a+b
  if method=='repartition fin de ligne':
    return a*b
  else:
    raise NameError('méthode de répartition des charge non valide')

What is the best and proper way to create this kind of function ?

A: Your code is fine with one exception - NameError is usually reserved for namespace errors, while what you want is ValueError which is commonly used for argument values of correct type but outside of expected range.
Since Python 3.10 you can use match statements instead of chained 'if's to make it more readable. Your code would look like that using that syntax:
def f(a,b,method='repartition uniforme'):
    match method:
        case 'repartition uniforme':
            return a+b
        case 'repartition fin de ligne':
            return a*b
        case _:
            raise ValueError('méthode de répartition des charge non valide')

A: You can store your functions in a dictionary:
funcs = {
    'repartition uniforme': lambda x, y: x + y,
    'repartition fin de ligne': lambda x, y: x * y
}

def f(a,b,method='repartition uniforme'):
    try:
        return funcs[method](a, b)
    except KeyError:
        raise NameError('méthode de répartition des charge non valide')


text:
Q: Query em sql server com valor diferente consoante algumas variáveis Boa tarde eu tenho a seguinte query:
select distinct(T.Grupo) 'Grupo', MAX(G.Descricao) 'Grupo', sum(E.QtdCat*S.FactConvEst) 'M2 cativos'
from EncLin as E
INNER JOIN Stock as s
on s.CodProd=e.CodProd
inner join terceiros as t
on t.terceiro=e.Terceiro
inner join grupo as g
on g.Grupo=t.grupo
where
E.QtdCat>0 and E.Estado in ('P','N','C') and E.Arm not in ('03P','05G') and E.TpDoc not in ('ENI','ENS')
Group by T.Grupo
order by 3 desc, 2

Precisava de adicionar mais duas colunas, uma que devolva o valor de sum(E.QtdCatS.FactConvEst) quando E.Estado='N' e outra que devolva o valor de sum(E.QtdCatS.FactConvEst) quando E.Estado='C'.
Penso que isso se faz com case... Mas não tenho a certeza até porque já tentei e está a dar valores errados.

A: Com um CASE se pode condicionar uma soma
select T.Grupo   Grupo ,
       MAX(G.Descricao) "Grupo",
       sum(E.QtdCat*S.FactConvEst) "M2 cativos",
       sum(case when E.Estado='N' then E.QtdCatS.FactConvEst else 0 end) estado_n,
       sum(case when E.Estado='C' then E.QtdCatS.FactConvEst else 0 end) estado_c
from EncLin as E
INNER JOIN Stock as s
on s.CodProd=e.CodProd
inner join terceiros as t
on t.terceiro=e.Terceiro
inner join grupo as g
on g.Grupo=t.grupo
where
E.QtdCat>0 and E.Estado in ('P','N','C') and
E.Arm not in ('03P','05G') and
E.TpDoc not in ('ENI','ENS')
Group by T.Grupo
order by 3 desc, 2


text:
Q: Including files from library on publish I have created a WPF application which uses a library in the same solution. To make things easier, let's call them MyClient and MyLibrary.
In MyLibrary I import some .dll files using DLLImport().
I included these files in the MyLibrary project, they are set as Content and Copy if newer.
When MyLibrary is built, the files are copied into the /bin/Release/ or /bin/Debug/ directories.
MyClient references MyLibrary, but upon publishing, the .dll files are missing, so the application doesn't work properly.
As a workaround, I have included the .dll files in the MyClient project and that seems to work, but it defeats the point of a library.
I'm hoping someone knows a way to do this in a way which lets me keep the files only in the MyLibrary project.


text:
Q: Auto generated validators being created for Nullable fields I have an MVC 3 application which has to be localizable. For my integer MVC is automatically adding Number Validation however I have marked the field as nullable.
This is in my ViewModel:
public int? UserValidity
{
   get { return this.Company.UserValidity; }
   set { this.Company.UserValidity = value; }
}

This is in my Model:
public Nullable<int> UserValidity { get; set; }

I have read that MVC adds this validation only for Non-nullable fields but in my case it is also doing it for nullable field.
What could be the reason for it?
Actually in my application all the validation messages have to be multi-lingual so I have to create my custom validators to get these messages from db. But MVC's auto-generated validator is taking precedence over my validators plus it is only in english.


text:
Q: Contacts created with Android emulator (2.0) not being seen I created contacts with the emulator for v 2.0. However, I am unable to see these contacts. One of the errors I get even before my code that executes read contacts is:

Cannot determine the default account for contacts compatibility

See below for full stack:
E/ContactsProvider(  109): Cannot determine the default account for contacts compatibility
E/ContactsProvider(  109): android.accounts.AuthenticatorException: bind failure
E/ContactsProvider(  109):      at android.accounts.AccountManager.convertErrorToException(AccountManager.java:659)
E/ContactsProvider(  109):      at android.accounts.AccountManager.access$500(AccountManager.java:53)
E/ContactsProvider(  109):      at android.accounts.AccountManager$BaseFutureTask$Response.onError(AccountManager.java:566)
E/ContactsProvider(  109):      at android.accounts.IAccountManagerResponse$Stub.onTransact(IAccountManagerResponse.java:69)
E/ContactsProvider(  109):      at android.os.Binder.execTransact(Binder.java:287)
E/ContactsProvider(  109):      at dalvik.system.NativeStart.run(Native Method)

A: You're getting this error because you don't have any accounts registered on your virtual device.
Unfortunately, solving this is a bit difficult, since the SDK doesn't come bundled with Google Accounts support. As a result, there's no account types available on your device that you could use to register a new account.
Unless you can find a third-party application that registers itself as an contact provider (I'm not aware of any yet), I can't think of a solution here other than to develop on an actual phone.

A: Please check this link.It looks related . http://groups.google.com/group/android-developers/browse_thread/thread/72fcf849c092b219/8b83e5d1580a7d45?lnk=raot&pli=1


text:
Q: want to merge specific code lines from 2 text files for starters, i am actually a medical student, so i wouldn't know first thing about programming, but i found myself in desperate need for this, so pardon me for my complete ignorance about the subject.
i have 2 XML files containing text, each one contains nearly 2 million lines, the first one looks like this:
<TEXT>
    <Unknown1>-65535</Unknown1>
    <autoId>1</autoId>
    <autoId2>0</autoId2>
    <alias>Name2.Boast_Duel_Season01_sudden_death_1vs1</alias>
    <original>Уникальная массовая дуэль: Битва один на один до полного уничтожения в один раунд</original>
  </TEXT>
  <TEXT>
    <Unknown1>-65535</Unknown1>
    <autoId>2</autoId>
    <autoId2>0</autoId2>
    <alias>Name2.Boast_Duel_Season01_sudden_death_3vs3</alias>
    <original>Уникальная массовая дуэль: Битва трое на трое до полного уничтожения в один раунд</original>

and the second one looks like this:
<TEXT>
    <Unknown1>-65535</Unknown1>
    <autoId>1</autoId>
    <autoId2>0</autoId2>
    <alias>Name2.Boast_Duel_Season01_sudden_death_1vs1</alias>
    <replacement>Unique mass duel one on one battle to the complete destruction of one round</replacement>
  </TEXT>
  <TEXT>
    <Unknown1>-65535</Unknown1>
    <autoId>2</autoId>
    <autoId2>0</autoId2>
    <alias>Name2.Boast_Duel_Season01_sudden_death_3vs3</alias>
    <replacement>Unique mass duel Battle three against three to the complete destruction of one round</replacement>
  </TEXT>

and those blocks of code are repeated along the files for like half a million time, netting me the 2 million liner i told you about..
now what i need to do is merge both files to make the final product look like this:
<TEXT>
    <Unknown1>-65535</Unknown1>
    <autoId>1</autoId>
    <autoId2>0</autoId2>
    <alias>Name2.Boast_Duel_Season01_sudden_death_1vs1</alias>
    <original>Уникальная массовая дуэль: Битва один на один до полного уничтожения в один раунд</original>
    <replacement>Unique mass duel one on one battle to the complete destruction of one round</replacement>
  </TEXT>
  <TEXT>
    <Unknown1>-65535</Unknown1>
    <autoId>2</autoId>
    <autoId2>0</autoId2>
    <alias>Name2.Boast_Duel_Season01_sudden_death_3vs3</alias>
    <original>Уникальная массовая дуэль: Битва трое на трое до полного уничтожения в один раунд</original>
    <replacement>Unique mass duel Battle three against three to the complete destruction of one round</replacement>
  </TEXT>

so, Basically i want to add the "Replacement" line under each respective "original" line while the rest of the file is kept intact (it's the same in both) , doing this manually would take me like 2 weeks..and i only have 1 day to do so!
any help is appreciated, and again..sorry if i sound like a total idiot at this, cause i kind of am!
P.S: i can't even chose a proper tag! i will totally understand if i just get lashed in the answers now..this job is way to big for me!

A: The truth about "where to start" is to learn basic python string manipulation. I was feeling nice and I like these sorts of problem, however, so here's a (quick and dirty) solution. The only things you'll need to change are the "original.xml" and "replacement.xml" file names. You'll also need a working python version, of course. That's up to you to figure out.
A couple caveats about my code:

*

*Parsing XML is a solved problem. Using regular expressions to do it is frowned upon, but it works, and when you're doing something as simple and fixed as this, it really doesn't matter.

*I made a few assumptions when building the outputted XML file (for example an indentation style of 4 spaces), but it outputs valid XML. The application you're using should play nice with it.

-
import re

def loadfile(filename):
    '''
    Returns a string containing all data from file
    '''
    infile = open(filename, 'r')
    infile_string = infile.read()
    infile.close()
    return infile_string

def main():
    #load the files into strings
    original = loadfile("original.xml")
    replacement = loadfile("replacement.xml")

    #grab all of the "replacement" lines from the replacement file
    replacement_regex = re.compile("(<replacement>.*?</replacement>)")
    replacement_list = replacement_regex.findall(replacement)

    #grab all of the "TEXT" blocks from the original file
    original_regex = re.compile("(<TEXT>.*?</TEXT>)", re.DOTALL)
    original_list = original_regex.findall(original)

    #a string to write out to the new file
    outfile_string = ""
    to_find = "</original>" #this is the point where the replacement text is going to be appended after
    additional_len = len(to_find)
    for i in range(len(original_list)): #loop through all of the original text blocks
        #build a new string with the replacement text after the original
        build_string = ""
        build_string += original_list[i][:original_list[i].find(to_find)+additional_len]
        build_string += "\n" + " "*4
        build_string += replacement_list[i]
        build_string += "\n</TEXT>\n"
        outfile_string+=build_string

    #write the outfile string out to a file
    outfile = open("outfile.txt", 'w')
    outfile.write(outfile_string)
    outfile.close()

if __name__ == "__main__":
    main()

Edit (reply to comment): The IndexError, list out of range error means that the regex isn't properly working (it's not finding the exactly correct amount of replacement text and grabbing each item to put it into a list). I tested what I wrote on the blurbs you provided, so there's a discrepancy between the blurbs you provided and the full-blown XML files. If there aren't the same amount of original/replacement tags or anything like that, that will break the code. Impossible for me to figure out without access to the files themselves.

A: here I present a straightforward way to do that (without xml parseing).
def parse_org(file_handle):
    for line in file_handle:
        if "<TEXT>" in line:
            record = line## start a new record if find tag <TEXT>
        elif "</TEXT>" in line:
            yield record## end a record if find tag <\TEXT>
            record = None
        elif record is not None:
            record +=line

def parse_rep(file_handle):
    for line in file_handle:
        if "<TEXT>" in line:
            record = None
        elif "</TEXT>" in line:
            yield record
            record = None
        elif "<replacement>" in line:
            record = line

if __name__ == "__main__":
    orginal_file = open("filepath/yourfile.xml")
    replacement_file = ("filepath/yourfile.xml")
    a_new_file = open("result_file","w")
    END = "NOT"
    while END =="NOT":
        try:
            org = parse_org(orginal_file).next()
            rep = parse_rep(replacement_file).next()
            new_record = org+rep+"</TEXT>\n"
            a_new_file.write(new_record)
        except StopIteration:
            END = "YES"
    a_new_file.close()
    orginal_file.close()
    replacement_file.close()

the code is written using python, and it uses keyword yield, use http://www.codecademy.com/ if you want to learn python, google yield python to learn how to use yield in python. if you would like to process such txt file in future, you should learn a script language, python may be the easiest one. If you encounter any questions you could post them on this website, but dont do nothing and just ask like "write this program for me".


text:
Q: How can I simplify this code with a loop or function? I'm working on my first WordPress theme option from scratch. I have some code like below that fills the empty options if they don't set 'in current send form process'...
(Without this code, if a user sends the form then the other options that aren't in the current view will be clear and their value will be deleted! This code keeps their values and is working correctly.)
I just need to simplify this code:
if ( empty( $options['index1_status'] ) ) {$options['index1_status'] = get_status('index1_status');}
if ( empty( $options['index2_status'] ) ) {$options['index2_status'] = get_status('index2_status');}
if ( empty( $options['index3_status'] ) ) {$options['index3_status'] = get_status('index3_status');}
if ( empty( $options['index4_status'] ) ) {$options['index4_status'] = get_status('index4_status');}
if ( empty( $options['index5_status'] ) ) {$options['index5_status'] = get_status('index5_status');}

How can I simplify this code with a loop or function?

A: And just add more to the $optionsArray
$optionsArray = [
    'index1_status',
    'index2_status',
    'index3_status',
    'index4_status',
    'index5_status',
];

foreach ($optionsArray as $v)
{
 // if $options[$v] is empty, then set it to get_status($v), else keep its original value
    $options[$v] = (empty($options[$v])) ? get_status($v) : $options[$v];
}


text:
Q: C++ STL Algorithms upper_bound() that is not strictly greater Unlike lower_bound, upper_bound does not return an iterator to the element if it compares equivalent to value, but only if it compares strictly greater.
Is there an alternative if I want an upper_bound algorithm that is greater than or equal to.

A: You could decrease the iterator by 1.
auto begin = ...;
auto end = ...;
auto it = std::upper_bound(begin, end, target);
if (it == begin)
  return it;
-- it;
if (*it < target)
  return ++it;
else
  return it;

The position of the iterator will be like this, assume you are searching for 2:
1 1 1 2 2 2 2 3 3 3 3
      ^     ^ ^
      lb    | ub
            this function

1 1 1 1 3 3 3 3
        ^
        lb & ub & this function

A: I did this using option (2)
https://en.cppreference.com/w/cpp/algorithm/upper_bound?force_isolation=true
Assuming you know your data type (int in this case, but you could easily template this):
std::upper_bound(v.begin(), v.end(), target,
                 [](const int &a, const int &b) { return a <= b; });


text:
Q: NoSql databases - Decent tutorial/book that covers the concepts Am looking for a good resource on learning the concepts behind NoSql databases.
Most things I find are related to a specific technology (MongoDb, CouchDB etc) but I'm after all the concepts behind NoSql instead of focusing on a specific area (some are graph DBs, some key-value etc).
Can you share from your experience and point me to a good resource?

A: I don't know if that's even possible.
NoSQL is a broad term that covers graph databases, document stores, key-value stores. Their lowest common factor is just that you don't have an SQL interface to access the data.

A: There's an upcoming (as yet unreleased) book that might cover what you are looking for - http://www.amazon.com/NoSQL-Distilled-Martin-Fowler/dp/0321826620
You might also find Ian Varley's master's thesis useful - http://ianvarley.com/UT/MR/Varley_MastersReport_Full_2009-08-07.pdf
Another overview - http://www.aosabook.org/en/nosql.html
For specific implementations, this site covers a lot of ground - http://nosql-databases.org/

A: The NoSQL wikipedia article covers everything you need to know about the different types of NoSQL databases available.
If you want to delve into specifics, you can read about each one of them individually on wikipedia, or look for other types of documentation.


text:
Q: IIS throwing HTTP 404 not found but resource exists. Requested URL also changing automatically.! I'm facing a really weird scenario here with my local IIS. I have hosted multiple sites in the default website in my local IIS. One of them has the login page. From the login page, I'm redirecting the user to another page that is located in another site (which is also hosted in the same IIS inside default website virtual directory).
Now in the submit button click event of my login page, after authenticating the user, I have written a "Response.Redirect(redirect_url)". the redirect_url is being formed dynamically and given as a parameter to the Redirect method.
While debugging, the final redirect_url that is being sent as parameter to Redirect method is:
http://localhost/CP/web/console/console.aspx?sk=3e3cc1a8-73c4-4945-b3f8-08af22ea4324.50008

But after I try to go to the next step, I'm suddenly getting a HTTP 404 error saying that the resource doesn't exist and I have observed that Requested URL shown in the error page is different that what was dynamically sent to the Response.Redirect(...) method.
In the error page, the requested url shows the value as
http://localhost/CP/web/console/localhost/CPLogin?err=5

whereas my actual requested url formed in the code is:
http://localhost/CP/web/console/console.aspx?sk=3e3cc1a8-73c4-4945-b3f8-08af22ea4324.50008

I'm just unable to understand why the requested url is getting changed automatically.! Also, I observe that "localhost" is being appended to the requested URL again which is not what is supposed to happen.
Please visit THIS link[^] to understand this question more clearly. I have added screen shot of the error page.
http://amoghnatu.wordpress.com/2013/09/16/question-please-help-iis-throwing-http-404-not-found-but-requested-resource-actually-exists-requested-url-also-changing-automatically/[^]
Thanks a lot.!

A: Indeed, the problem was with the way I had hosted the sites in my application. I just removed all the sites related to my application from IIS and then hosted all of them again much more carefully. This resolved the "wrong redirect url" problem.
Also, I had some tables with missing required data because of which I was getting the error code.
So after I got all the tables filled with the required data and also after properly hosting the application in IIS, my problem got resolved.

A: In IIS, go to relevant folder, right click and "browse". Check out what is the URL. In most cases, this is due to the URL should have port number appended. For instance it will be something like :
http://localhost:<port number>/CP/web/console/console.aspx?sk=3e3cc1a8-73c4-4945-b3f8-08af22ea4324.50008

instead of
http://localhost/CP/web/console/console.aspx?sk=3e3cc1a8-73c4-4945-b3f8-08af22ea4324.50008


text:
Q: ParametricPlot Question I want to graph more than two, lets say 5 different ParametricPlot-s all in terms of different time variables. Is there any way to do this, such that they all show up on the same plot? For example, I want to plot:

*

*{3Cos[a],4Sin[a]}.. on some interval,

*{4Cos[b],5Sin[b]}.. on some interval,

*{5Cos[c],6Sin[c]}.. on some interval,

*{6Cos[d],7Sin[d]}.. on some interval,

*{7Cos[e],8Sin[e]}.. on some interval,
all on one picture.
Thank You Very Much.

A: Combine them using Show[].
An example:
a1 = ParametricPlot[{3 Cos[a], 4 Sin[a]}, {a, 0, π}];

a2 = ParametricPlot[{4 Cos[b], 5 Sin[b]}, {b, 0, π/2},
     PlotStyle -> Green];

a3 = ParametricPlot[{5 Cos[c], 6 Sin[c]}, {c, 0, π/4},
     PlotStyle -> Purple];

a4 = ParametricPlot[{6 Cos[d], 7 Sin[d]}, {d, 0, π/8},
     PlotStyle -> Brown];

a5 = ParametricPlot[{7 Cos[e], 8 Sin[e]}, {e, 0, π/16},
     PlotStyle -> Cyan];

Show[a1, a2, a3, a4, a5, PlotRange -> All]


text:
Q: Verify method of Moq throwing error in ASP.NET MVC unit testing I am developing an ASP.NET MVC project. In my project I am doing unit testing. I am using Moq to mock my business logics. But I am having a problem with Moq. Especially with mock.Verify method.
This is the action I am testing
[HttpPost]
        public ActionResult Edit(CreateRegionVM model)
        {
            if(ModelState.IsValid)
            {
                Region region = new Region
                {
                    Id = model.Id,
                    Name = model.Name,
                    MmName = model.MmName,
                    Description = model.Description,
                    MmDescription = model.MmDescription,
                    GeoLocation = model.GeoLocation,
                    ImagePath = model.ImagePath
                };
                String imagePath = String.Empty;
                if(model.ImageFile!=null && model.ImageFile.ContentLength>0)
                {
                    imagePath = fileHelper.UploadFile(model.ImageFile, AppConfig.RegionImageDir,null);
                    if(String.IsNullOrEmpty(imagePath))
                    {
                        return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
                    }
                    else
                    {
                        //create thumb & delete old images - check the image operations
                        fileHelper.CreateThumb(imagePath, AppConfig.RegionImageDir, AppConfig.RegionMediumThumbWidth, AppConfig.RegionMediumThumbHeight, AppConfig.MediumThumbSuffix);
                        fileHelper.CreateThumb(imagePath, AppConfig.RegionImageDir, AppConfig.RegionSmallThumbWidth, AppConfig.RegionSmallThumbHeight, AppConfig.SmallThumbSuffix);

                        fileHelper.DeleteFile(model.ImagePath);
                        fileHelper.DeleteFile(fileHelper.GetImagePath(model.ImagePath, AppConfig.MediumThumbSuffix));
                        fileHelper.DeleteFile(fileHelper.GetImagePath(model.ImagePath, AppConfig.SmallThumbSuffix));
                        model.ImagePath = imagePath;
                    }
                }

                try
                {
                    regionRepo.Update(region);
                    TempData["message"] = "Region successfully edited";
                    TempData["class"] = AppConfig.FlashSuccessClass;
                    return RedirectToAction("Edit", new { id = model.Id });
                }
                catch
                {
                    return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
                }
            }
            return View("Create",model);
        }

This is my test function
 [TestMethod]
        public void Edited_And_Redirected()
        {
            var postFile = new Mock<HttpPostedFileBase>();
            postFile.Setup(m => m.ContentLength).Returns(1);

            CreateRegionVM model = new CreateRegionVM
            {
                Id = 1,
                Name = "test",
                ImageFile = postFile.Object
            };

            Mock<IRegionRepo> regionMock = new Mock<IRegionRepo>();
            regionMock.Setup(m => m.Update(new Region())).Verifiable();
            Mock<IFileHelper> fileMock = new Mock<IFileHelper>();
            fileMock.Setup(m => m.UploadFile(model.ImageFile, It.IsAny<String>(), null)).Returns("upload_file_path");

            RegionController controller = new RegionController(regionMock.Object, fileMock.Object, 0);
            var unknownView = controller.Edit(model);
            regionMock.Verify();
            Assert.IsInstanceOfType(unknownView, typeof(RedirectToRouteResult), "Not redirected");
        }

As you can see my test method, I am using verify to make sure regionRepo.Update method is called. But it is giving me this error when I run the test.

Moq.MockVerification Exception: The following setups were not matched:
  IRegionRepo m=>m=>Update()

Why is this error thrown? How does the verify method of moq work?

A: Take a look at this line:
regionMock.Setup(m => m.Update(new Region())).Verifiable();

It's going to compare the input to new Region(), but most likely whatever you're passing in is not going to be referentially equal to that.
If the Region doesn't matter, try
regionMock.Setup(m => m.Update(It.IsAny<Region>())).Verifiable();


text:
Q: Find MySql specific key constraints I have a question: When I am manipulating data in my mysql database, it gives   some errors such as

Duplicate entry '' for key 'UNIQ_99719D5877153098',

...
My question is: "How can I find out that what exactly the key UNIQ_99719D5877153098 or any other keys with this code pattern is?"
How can I find out the key constraints, the table that this constraint is defined on it, etc from the key codes mentioned in the error?

A: Use INFORMATION_SCHEMA.TABLE_CONSTRAINTS
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_NAME = 'UNIQ_99719D5877153098';


text:
Q: Huygens principle and path integral for classical waves I want to better understand what the path integral is and what it isn't.
Even though I do this to learn QFT, this question is purely concerned with classical fields, no quantization is intended at all. Neither am I talking about classical particles with well-defined paths, though.
Feynman introduces the path integral with the Gedankenexperiment of expanding a double slit experiment to have an infinite amount of screens with an infinite amount of holes in each. He does this, talking about the options a particle has to travel to the screen. In QM, all possible paths then interfere and the path integral is used to calculate this interference.
What I read out there is nothing but Huygens principle.
Thus, if we have a classical field with a point source at point $A$ at time $t_0$ and we want to calculate the amplitude/phase of the field at point $B$ at time $t$, would the path integral be a proper tool for it?
If so,

*

*how does it relate to Fermat's principle in this case?

*is there any important difference in either the measure or the involved action between a classical field or a quantum particle? (differences that would apply to any classical field)

Or put differently: Is the path integral a (mathematical) tool for quantum things or for wave things? Is it linked to the probability aspect or only to the wave nature of quantum phenomena?