text:
Q: if jQuery statement | empty text boxes Ok so i have been literally trying to figure this out for the past hour, its such a simple thing that i never have a problem with. So the input 'username_input' has a jQuery if state that is
if($('#username_input').val() == 0) {
    alert('Empty');
} else {
    alert('Not empty');
}

After that it moves onto the 'password_input' if statement which is the same thing, but it keeps alerting 'empty'. Why?
<!doctype html>

        <title> Awflicks </title>
        <meta name=viewport content="width=device-width, initial-scale=1">
        <link type="text/css" rel="stylesheet" href="index.css">

            <form action="" method="post">

 Username:  <input type="text" name="username" id="username_input">

 Password: <input type="password" name="password" id="password_input">

 Retype password: <input type="password" name="retype_password" id="retype_password_input">

 Create Account

            </form>

A: Because the variable with the value does not get updated when the value changes. It is the value when it is read. You need to read the value when you want it or set the variable onchange.
Also not sure how the value would be zero since there is no value set. Shouldn't you be checking the length? And you are going to want to return a Boolean from your validation function so you know to cancel the form submission.

A: You can directly use this without defining variables
if(!$('#username_input').val()) // or if(!$('#password_input').val()) for password input
{
   alert('empty');
} else {
   alert('not empty')
}

A: You need to refactor as follows to ensure that $username will only store the value once an input has been committed (e.g. once submit has been pressed)
function create_account() {
   var $username = $('#username_input').val();
   var $password1 = $('#password_input').val();
   var $password2 = $('#retype_password_input').val();
   if($username == 0) {
      alert('empty');
   } else {
      alert('not empty')
   }
}

A: After you make the changes suggested by the other answers, you are going to have an issue with your form always getting submitted even when the alert shows "Empty". In fact, it will get submitted twice when the alert shows "Not empty". That is because your "submit_button" has type="submit" so it submits the form. You could change to type="button", but my preference is to bind the handler to the form's submit-event, instead of the button's click-event.
$('form').submit(function(event) {
    event.preventDefault(); // Stop the form from getting submitted.

    var username = $('#username_input').val();
    var password1 = $('#password_input').val();
    var password2 = $('#retype_password_input').val();

    var isValid = true;

    if (username == '') {
        alert('Empty');
        isValid = false;
    }

    if (isValid) {
        this.submit(); // Now submit the form.
    }
});


text:
Q: GMM weight matrix $W_n$ -- what does the index $n$ signify? The question is as in the title. The GMM estimator (in my Econometrics notes) is as follows:
$\hat \delta_{GMM}(W_n) = (S'_{xz} W_nS'_{xz})^{-1}(S'_{xz}W_ns_{xy})$

A: The weight matrix $W$ is unknown in this sample and must be estimated iteratively. The notation you've supplied for its estimation is consistent with the Newton-Raphson method where the change in iterative estimates is denoted by $\delta$. You've put the $\hat$ (hat) over that $\delta$, but it should really be over the $W$. As a rule, anything that's estimated (as indicated with hat notation), is implicitly subscripted with $n$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deleted objects in Python 3 not being released from memory? Writing a simple multi-processed database table archiver that dumps compressed data from a Postgres db to a Google Cloud Storage bucket.
Doing the memory profiling dance and noticed that objects that I'm deleting aren't actually being released from memory. Was hoping someone has an explanation or could point me to some material for better understanding of what's going on.
Python 3.7
Here's the code.
import gzip
import ETL.dbtools as db
from google.cloud import storage
from memory_profiler import *

@profile
def worker(table_name: str) -> None:
    """
    table_name: str name of table to be archived.
    """
    client = storage.Client()
    bucket = client.get_bucket('mein_bucket')
    blob = bucket.blob(table_name+'.csv.gzip')
    # // db.read_table simply reads data from PostgreSQL database
    # //    using sqlalchemy library into a pandas DataFrame
    df = db.read_table(table_name, schema='das_schema')
    csv_data = df.to_csv(index=False).encode('utf-8')
    del df
    compressed_csv_data = gzip.compress(csv_data)
    del csv_data
    blob.upload_from_string(compressed_csv_data)

And the profile output.
Line #    Mem usage    Increment   Line Contents
================================================
     7    107.6 MiB    107.6 MiB   @profile
     8                             def worker(table_name: str) -> None:
     9                                 """
    10                                 table_name: str name of table to be archived.
    11                                 """
    12    107.8 MiB      0.1 MiB       client = storage.Client()
    13    111.4 MiB      3.6 MiB       bucket = client.get_bucket('mein_bucket')
    14    111.4 MiB      0.0 MiB       blob = bucket.blob(table_name+'.csv.gzip')
    15                                 # // db.read_table simply reads data from PostgreSQL database
    16                                 # //    using sqlalchemy library into a pandas DataFrame
    17    414.0 MiB    302.6 MiB       df = db.read_table(table_name, schema='das_schema')
    18    589.5 MiB    175.5 MiB       csv_data = df.to_csv(index=False).encode('utf-8')
    19    589.5 MiB      0.0 MiB       del df
    20    566.5 MiB      0.0 MiB       compressed_csv_data = gzip.compress(csv_data)
    21    566.5 MiB      0.0 MiB       del csv_data
    22    566.5 MiB      0.0 MiB       blob.upload_from_string(compressed_csv_data)


text:
Q: nsslider.integerValue requires me to focus on another app before updating the value I have an NSSlider in my macos app, called wave_mode_slider. What I'm trying to do is update the value of said slider on input. So, what I did is this:
self.wave_mode_slider?.integerValue = ("\(params[2])" as NSString).integerValue

This sets the value of the slider (white dot) to the value of the input as intended. However, before I see any actual result, I have to click outside of the application, which causes the white dot of the slider to jump to it's new value. as shown here:
Is there a way to make the slider update immediately?
My slider is created like this:
    self.wave_mode_slider = NSSlider(frame:CGRect(x: 10, y: 100, width: 20, height: 300))
    self.wave_mode_slider?.cell = OWOWSliderVertical()
    self.wave_mode_slider?.maxValue = 127
    self.wave_mode_slider?.target = self
    self.view?.addSubview(self.wave_mode_slider!)

I tried to set the isContinuous property of the slider to true, but that doen't change the outcome.

edit:
    var midiClient : MIDIClientRef = 0
    var inPort : MIDIPortRef = 0
    let observer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())

        MIDIClientCreate("WobClient" as CFString, nil, nil, &midiClient)
        MIDIInputPortCreate(midiClient, "WobClient_InPort" as CFString, {
            (pktList: UnsafePointer<MIDIPacketList>, readProcRefCon: UnsafeMutableRawPointer?, srcConnRefCon: UnsafeMutableRawPointer?) -> Void in
            let packetList : MIDIPacketList = pktList.pointee
            var packet : MIDIPacket = packetList.packet
            let mySelf = Unmanaged<Wob>.fromOpaque(srcConnRefCon!).takeUnretainedValue()
            for _ in 1...packetList.numPackets {
                let bytes = Mirror(reflecting: packet.data).children
                var params : [UInt64] = []

                var i = packet.length
                for (_, attr) in bytes.enumerated() {
                    let string = String(format: "%02X ", attr.value as! UInt8)
                    params.append(UInt64(strtoul(string, nil, 16)))
                    i -= 1

                    if (i <= 0) {
                        break
                    }
                }

//                print(("\(params[2])" as NSString).integerValue)
                mySelf.setWaveSliderValue(value: ("\(params[2])" as NSString).integerValue)
                packet = MIDIPacketNext(&packet).pointee
            }

        }, nil, &inPort)

        MIDIPortConnectSource(inPort, self.source, observer)

This is fro m where i get the value

A: In the end it was pretty easy, as soon as i saw Willeke's comment about the threading, I just used the main thread to set the value on:
DispatchQueue.main.async {
    mySelf.wave_mode_slider?.floatValue = ("\(params[2])" as NSString).floatValue
}


text:
Q: Any quick way to restore or reset closures in clojure to initial state? Is there any quick way to restore or reset closures to their initial states? E.g. in below function, how can I reset values of stat1 and stat2 associated with myClosureFn back to 1?
The context of this question: I use below structure in different functions, and one function may "mess up" values associated with the closure. So I'd need to reset/restore it to initial states in order to pass it again into another function.
(def myClosureFn
  (let [stat1 (atom 1)
        stat2 (atom 1)
        ;..stat3 stat4 ...
        ]
    (fn [m]
      (swap! stat1 inc)
      (reset!   stat2 (* 2 m))
      [@stat1  @stat2])))

(myClosureFn 1) ;--> [2 2]
(myClosureFn 2) ;--> [3 4]
(myClosureFn 2) ;--> [4 4]
(myClosureFn 3) ;--> [5 6]
;...
; how to get [ 1 1 ] back to myClosureFn ?

A: Rather than explicitly having to re-set the state associated with your function, consider using a higher-order function:
(defn myClosureFn []
  (let [stat1 (atom 1)
        stat2 (atom 1)
        ;..stat3 stat4 ...
        ]
    (fn [m]
      (swap! stat1 inc)
      (reset!   stat2 (* 2 m))
      [@stat1  @stat2])))

So, to get fresh state, you just call myClosureFn which returns a function with clean counters. For example:
> (def f1 (myClosureFn))
> (def f2 (myClosureFn))
> (f1 1) ;--> [2 2]
> (f1 2) ;--> [3 4]
> (f2 1) ;--> [2 2]
> (f1 3) ;--> [4 6]

Instead of having global state, each function carries around its own state with it. You can even create and use two such functions at the same time and they won't interfere with each other.

A: You can make myClosureFn to act like a reset function when no argument is passed
(def myClosureFn
  (let [stat1 (atom 1)
        stat2 (atom 1)
        ;..stat3 stat4 ...
        ]
    (fn [& [m]]
      (if m
        (do
          (swap! stat1 inc)
          (reset!   stat2 (* 2 m))
          [@stat1  @stat2])
        (do
          (reset! stat1 1)
          (reset! stat2 1))))))

(myClosureFn 1) ;--> [2 2]
(myClosureFn 2) ;--> [3 4]
(myClosureFn) ;reset to 1 1

OR if you are using REPL, then just re-evaluate the myClosureFn form again in REPL.


text:
Q: I want to use ArrayBuffer in Dart, but got exception there seems to be no ArrayBuffer defined in Dart, although people say there is.
this is my code:
if (event.data is ArrayBuffer)

this is what I got:
 Error: line 43 pos 23: type 'ArrayBuffer' is not loaded

A: ArrayBuffer doesn't exist anymore. If you get a binary WebSocket frame it's returned as a ByteBuffer (requires that you set binaryType to 'arraybuffer'). You can convert the ByteBuffer to a list of bytes using new Uint8List.view(buffer.data). Both classes requires an import of dart:typed_data.


text:
Q: PHP keep me from eval ;) Variables inside string For reasons I'd rather not get into right now, I have a string like so:

$title

that gets stored in a database using mysql_real_escape_string.
During normal script execution, that string gets parsed and stored in a variable $string and then gets sent to a function($string).
In this function, I am trying to:
function test($string){
  $title = 'please print';
  echo $string;
}
//I want the outcome to be
please print

This seems like the silliest thing, but for the life of me, I cannot get it to "interpret" the variables.
I've also tried,
echo html_entity_decode($string);
echo bin2hex(html_entity_decode($string)); //Just to see what php was actually seeing I thought maybe the $ had a slash on it or something.

I decided to post on here when my mind kept drifting to using EVAL().
This is just pseudocode, of course. What is the best way to approach this?

A: Your example is a bit abstract. But it seems like you could do pretty much what the template engines do for these case:
function test($string){
   $title = 'please print';

   $vars = get_defined_vars();
   $string = preg_replace('/[$](\w{3,20})/e', '$vars["$1"]', $string);

   echo $string;
}

Now actually, /e is pretty much the same as using eval. But at least this only replaces actual variable names. Could be made a bit more sophisticated still.

A: I don't think there is a way to get that to work. You are trying something like this:
$var = "cute text";
echo 'this is $var';

The single quotes are preventing the interpreter from looking for variables in the string. And it is the same, when you echo a string variable.
The solution will be a simple str_replace.
echo str_replace('$title', $title, $string);

But in this case I really suggest Template variables that are unique in your text.

A: You just don't do that, a variable is a living thing, it's against its nature to store it like that, flat and dead in a string in the database.
If you want to replace some parts of a string with the content of a variable, use sprintf().
Example
$stringFromTheDb = '
%s is not %s
';

Then use it with:
$finalString = sprintf($stringFromTheDb, 'this', 'that');

echo $finalString;

will result in:

this is not that

A: If you know that the variable inside the div is $title, you can str_replace it.
function test($string){
  $title = 'please print';
  echo str_replace('$title', $title, $string);
}

If you don't know the variables in the string, you can use a regex to get them (I used the regex from the PHP manual).
function test($string){
  $title = 'please print';
  $vars = '/(?<=\$)[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/';
  preg_match_all($vars, $string, $replace);
  foreach($replace[0] as $r){
    $string = str_replace('$'.$r, $$r, $string);
  }
  echo $string;
}


text:
Q: Which test to choose? As you may have guessed from the title, I am very confused as to which statistical test I should use for my data.
So I have 15 individuals, for each of them I have several ( from 1 to 20) measures of the time they spent foraging. I also have two conditions, lets say A and B, under which the individuals foraged.
What I need to know is whether the individuals have been spending more time in condition A than in condition B.
It would be very nice if I could obtain an overall result, for example, if all the individuals spent globally more time foraging in condition A than in condition B.
I would also need a more detailed result, and knowing which individual did spend more time foraging in condition A than B, or if some of them did the opposite.
I would be very grateful if I could some advices as to which test would achieve what I aim for.

A: What you need is a linear mixed model (LMM) with the condition as fixed effect and the individual as a random offset. You can also include a random slope if you think some individuals exhibit a larger difference in foraging time between the two conditions.
The significance of the fixed effect will reveal if the condition has an effect on the mean foraging time. Closer scrutiny of the estimated values of the random effects will allow you to understand differences between the species, apart from the mean trend.


text:
Q: Encode HTML entities I am parsing some data from feedburner of which contains HTML entities. I am trying to encode the HTML entities using jQuery as such:
var encodedStr = data['1']['result']['content']; // content with HTML entities
$("#content").html(encodedStr).text();

but with no results.
Here is what its parsed: http://jsbin.com/ihadam/1/edit

A: Basically you should encode your html entities into html as such:
var encodedStr = data['1']['result']['content'];
var a = $("#content").html(encodedStr).text();

Then get the encoded text and apply it as html() as such:
$("#content").html(a);

That should work.
Demo: http://jsbin.com/ihadam/9/edit

A: You can save the bloat of JQuery with pure JavaScript functions.
Sometimes you just want to encode every character... This function replaces "everything except for nothing" in regxp.
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

function encode(w) {
  return w.replace(/[^]/g, function(w) {
    return "&#" + w.charCodeAt(0) + ";";
  });
}

test.value=encode(document.body.innerHTML.trim());
<textarea id=test rows=11 cols=55>www.WHAK.com</textarea>


text:
Q: Arranging The html Tables using Jquery Lets say I have this table:

Tracks

        Track Id
        Artist
        Track Name
        Uploader
        Status

        1
        Artist 1
        Track Name 1
        Uploader 1
        Blocked

        2
        Artist 2
        Track Name 2
        Uploader 2
        Visible

Through JQuery how would arrange the table rows depending on their value? lets say I want to show table rows that only contains  a table data value. How would I do that through Jquery?

A: Here is an example:
$('#search').on('keyup', function() {
    var val = $.trim(this.value).toLowerCase();
    $('table > tbody > tr:gt(1)').hide();
    if (val.length) {
        $('table > tbody > tr:gt(1) > td').filter(function() {
            return this.innerHTML.toLowerCase().indexOf(val) >= 0;
        }).parent().show();
    } else  $('table > tbody > tr:gt(1)').show();
});

( this will give you some guideline )
Demo

Related refs:

*

*.gt()

*parent > child selector

*.filter()

A: As a variant (DEMO):
HTML
<input id="search" type="text">

        Track Id
        Artist
        Track Name
        Uploader
        Status

        1
        Artist 1
        Track Name 1
        Uploader 1
        Blocked

        2
        Artist 2
        Track Name 2
        Uploader 2
        Visible

JavaScript
$(document).ready(function () {
    $('#search').keyup(function () {
        $('#table tr').show();
        var q = $(this).val().toLowerCase();

        $('#table tr:not(:first)').each(function () {
            var visible = false;

            $('td', this).each(function () {
                var content = $(this).text().toLowerCase();
                if (content.indexOf(q) != -1) visible = true;
            });

            $(this).toggle(visible);
        });
    })
});

DEMO


text:
Q: Cómo estructurar una mutación para conectar con Django Estoy teniendo problemas para hacer consultas, crear, actualizar y eliminar objetos en Django GraphQL a través del plugin GraphQL de Vuex ORM.
Desde la interfaz que me provee Django para ejecutar las consultas puedo hacer uso de mis mutaciones y consultar por cualquier objeto en particular o cualquier colección de los mismos.
Les escribo un ejemplo de cómo creo un objeto desde la interfaz de Django:
mutation myMutation {
  createTipoProducto(input: {nombre:"Pizza", descripcion:"foobar"}) {
    tipoProducto {nombre, descripcion}
    status
  }
}

Este código me devuelve el objeto con sus atributos y un status 200 si fue exitosa la consulta.
Éstas son las clases en mi esquema('schema'):
class TipoProductoNode(DjangoObjectType):
    class Meta:
        model = TipoProducto
        filter_fields = ['nombre', 'productos']
        interfaces = (relay.Node, )

class TipoProducto(graphene.ObjectType):
    nombre = graphene.String()
    descripcion = graphene.String()

class CreateTipoProducto(graphene.ClientIDMutation):

    class Input:
        nombre = graphene.String(required=True)
        descripcion = graphene.String(required=True)

    tipo_producto = graphene.Field(TipoProducto)
    status = graphene.Int()
    ok = graphene.Boolean()

    def mutate_and_get_payload(self, info, nombre, descripcion, client_id_mutation=None):
    tipo_producto = TipoProductoNode._meta.model(nombre=nombre, descripcion=descripcion)
    tipo_producto.save()
    return CreateTipoProducto(tipo_producto=tipo_producto, ok=bool(tipo_producto.id), status=200)

Mi modelo declarado en Vuex ORM:
import { Model } from '@vuex-orm/core';
import Product from './Product'

export default class TipProd extends Model {
    static entity = "tipProds"

    static fields () {
    return {
        id: this.increment(),
        nombre: this.attr(''),
        descripcion: this.attr(''),

        producto: this.hasMany(Product, 'tipProd_id')
        }
    }
}

Éste es el método que intenté usar desde Vuex ORM para crear un nuevo objeto:
"TipoProducto"
     methods: {
         async register (tipProduct) {
            await TipProd.insert({
                data:
                    tipProduct
            });
            const tipProd = TipProd.query().last()
            await tipProd.$mutate({ name: 'createTipoProducto' });
}

Los atributos correctos que están guardados en "tipProd" fueron tomados de un form, por eso no los incluyo explícitamente
No encuentro la manera que Vuex ORM me estructure correctamente la consulta para crear un objeto (entre otras mutaciones que no puedo usar). ¿Qué es lo que estoy haciendo mal?
Intenté ver con Apollo devtools cuál es la consulta que genera Vuex ORM pero no logré que me funcionara, así que estoy un poco ciego de cómo me está estructurando la consulta.

A: La estructura estaba bien, no podía ver la query saliente porque no había ninguna, me fallaba la conexión entre Django Graphene y Vuex-ORM plugin Graphql, ya que del lado de la API tenia mal definidas las mutaciones.


text:
Q: jquery replace part of a url I know practically nothing about jquery so please help me
I try this
function googlemapLinks {
 $('div.gmnoprint a').attr("href").replace('ll','q');
}

it does not work
I have a <div class="gmnoprint"> In that div Google maps puts a javascript link in
maps.google.com/maps?ll=5.....
I need maps.google.com/maps?q=5.....
Can you show me a function I can drop in a script file?

A: try this:
function googlemapLinks {
    var lnk = $('div.gmnoprint a').attr("href");
    $('div.gmnoprint a').attr("href",lnk.replace('ll','q'));
}

A: For setting a value with attr, you need to pass the new value as a second parameter. try this:
$('div.gmnoprint a').attr('href', $('div.gmnoprint a').attr('href').replace('ll','q'));

A: Bit late to the conversation but you could try:
$('.gmnoprint a').each(function() {
    this.href = this.href.replace('ll','q');
})

The other functions seem to loop whereas this will find the link and then replace '11' with 'q'. Well, it should =P

A: Try this to change any link or a tag href inside the gmnoprint container. If you don't use the each loop all the hrefs will contain the first instance of the href on the page.
this code looks at each a tag and replaces just that instance if it runs into 11 and changes the text to q
$('.gmnoprint a').each(function(){
    $(this).attr('href', $(this).attr('href').replace('11','q'));
});


text:
Q: How do polarizers really work? I've been searching for an explanation of how light is polarised, and I came across this short youtube video, which seemed reasonable.
From my lecture notes (ICL), I have that:

Okay, that's nice, no contradictions with the youtube video so far. But then the notes go on to say that:

The simplest linear polarizer are wire polarizers. Polarization in the direction of the wire drives
currents which leads to attenuation, whilst polarization orthogonal to the wires is unaffected. Natural materials can behave in the same way, especially long-chain polymers, such as Polaroid(TM) film.

This is backed-up by an answer given to this question from this site by @Gilbert which in their answer mentions that:

"For a wire-grid polarizer, the light polarized perpendicular to the wires will pass through. This counterintuitive result is because any electric field polarized parallel to the wires would excite currents in the wires, thereby reflecting/absorbing the light."

Also, on the Polarizer Wikipedia page under "Absorbative polarizers" section it is stated that:

A Polaroid polarizing filter functions similarly on an atomic scale to the wire-grid polarizer. It was originally made of microscopic herapathite crystals. Its current H-sheet form is made from polyvinyl alcohol (PVA) plastic with an iodine doping. Stretching of the sheet during manufacture causes the PVA chains to align in one particular direction. Valence electrons from the iodine dopant are able to move linearly along the polymer chains, but not transverse to them. $\color{red}{\text{So incident light polarized parallel to the chains is absorbed by the sheet;}}$$\color{red}{\text{light polarized perpendicularly to the chains is transmitted.}}$ The durability and practicality of Polaroid makes it the most common type of polarizer in use, for example for sunglasses, photographic filters, and liquid crystal displays. It is also much cheaper than other types of polarizer.

Bearing all the above facts in mind, then, if only the orthogonal components of the E-field are transmitted then why does figure 4] c) not look like this:

since the parallel (to $\theta_p$ direction) components of the E-field were attenuated away?


text:
Q: Windows 7 not installing over preinstalled ubuntu I bought a laptop recently and had ubuntu 12.04 pre installed. I wanted to install windows 7 so I wrote gparted live cd and booted into it, and formatted all the 3-4 partitions containing ubuntu, making the hdd an unallocated space of 500 gb. Then I made it into 2 partitions and formatted them into NTFS. But I've tried installing windows 7 through both dvd and usb which has worked on other laptops previously. The USB is not even being detected during boot and the  DVD starts to install but on pressing install now it shows the following error:
"windows could not retrieve information about the disks on this computer"
I can see in gparted that both the partitions are showing unmounted, does that have something to do with it? PLease help, i'm at wits end!
THanks

A: Delete all your partitions with gparted and boot the system with the Windows 7 bootable media to try again.
If the USB drive is not being found as a boot-up device, either the motherboard is too old to support it, your BIOS is configured to not boot in that order, USB is removed from the boot order, the USB boot media needs to be re-created (sometimes, on another USB drive), or your USB drive is NTFS and the system can only read FAT32 for boot-up media.
If your installer still doesn't see the hard disk after it loads the initial installation wizard, then you may want to swap out the drive.


text:
Q: Reboot console application How can i reboot my C# console application like in Java when programm still work in same console, without creating new one.
I tried to start new application with Process.UseShellExecute = false and kill current process from newly created, but i can kill parent process from child using this. I tried to kill current process after creating new, but also it doesnt work.

A: There is no straightforward way to do this, however you can simulate this behavior:

*

*Change your application from console application to Windows application.

*Create a console for the first instance of your application

*Start a new instance of your application and attach to the console created in step 2.

*Exit the first instance.

It is important not to forget to change the application type to Windows application.
The following code will restart the application until you press Ctrl+C:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;

class Program
{
    [DllImport("kernel32", SetLastError = true)]
    static extern bool AllocConsole();

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool AttachConsole(uint dwProcessId);

    const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;

    [STAThread]
    static void Main(string[] args)
    {
        if (!AttachConsole(ATTACH_PARENT_PROCESS))
        {
            AllocConsole();
        }
        Console.WriteLine("This is process {0}, press a key to restart within the same console...", Process.GetCurrentProcess().Id);
        Console.ReadKey(true);

        // reboot application
        var process = Process.Start(Assembly.GetExecutingAssembly().Location);

        // wait till the new instance is ready, then exit
        process.WaitForInputIdle();
    }
}


text:
Q: Degree of a polynomial over an algebraic curve (in particular Edwards curve) I've been very confused about how to define the degree of a rational function over an algebraic curve.
For an Elliptic curve in Weierstrass form $E : Y^2=X^3 - AX -B$ over an algebraically closed field $K$, char $K \neq 2,3$, the set of polynomials on $E$ is given by
$$ K[E] := K[X,Y]/\langle Y^2-X^3-AX-B \rangle $$
The set of rational functions is given by
$$ K(E):= K[E]^2 / \sim $$
Then, the degree of a polynomial $f \in K[E]$, where $ f(x,y)=v(x)+yw(x)$ is its canonical form is given by
$$ \deg(f) := \max \{ 2 \deg_x(v),3+2\deg_x(w) \}   $$
Here, $\deg_x(v)$ is the classical degree of a polynomial $v \in K[X].$
Let $C:X^2 + Y^2 = 1+dX^2Y^2$ be an Edwards curve over $K$, how do we define the degree of a polynomial $f \in K[C]$ ?
In particular, for any algebraic curve. How will the result vary when the base field is not algebraically closed (for example, $\mathbb{F}_q$)? From what I've read so far, it looks like it has something to do with the pole divisors of the rational function (x) and (y) in those curves, but this connection is not clear.


text:
Q: PHPUnit: How to require my apps config file I have a file called application.config.php in my apps root directory. I want to require it or autoload it for my tests. The config file is like so:
<?php
// database connection
$config = array(
  'database' => array(
    'dsn' => 'mysql:host=localhost;dbname=budgetz',
    'user' => 'budgetz_user',
    'password' => 't1nth3p4rk',
  ),
);

My app uses these to connect to the database. So, to test my models they also need to connect to the database, .. or some database. Is it just a matter of something along the lines of requiring it in the test file:
<?php
require_once 'vendor/autoload.php';
require_once 'application.config.php';

class MapperTest extends PHPUnit_Framework_TestCase {
    public function testFetchOne() {
        $dbAdapter = new DatabaseAdapter($config['database']);
        $userMapper = new UserMapper($dbAdapter); // using UserMapper but any child of Mapper will do

        $user = $userMapper->fetchOne(1);

        $this->assertsEquals(1, $user->id, 'message');
    }
}

I tried this but I get the error:
There was 1 error:

1) MapperTest::testFetchOne
Undefined variable: config

/var/www/new_orm/test/MapperTest.php:8

What am I doing wrong? Also, I appreciate anyone giving some advise on best practise here. Perhaps this approach to requiring a config file in every page is a little old. Thanks

A: Globals is an option, but not good one.
Create your class, witch extends PHPUnit_Framework_TestCase. Then use the setup to set your config.
e.g.
class myTestCase  extends PHPUnit_Framework_TestCase {
        private $config;
        public function setUp() {
            $this->config = ....
        }
        public function getConfig() {
           return $this->configl
        }

Then your testcases should extends myTestCase. You could access config with
$this->getConfig();

Anyway, accessing dev db is not a good idea, maybe it is better to mock the work with the db ?

A: Try
public function testFetchOne() {
    global $config;


text:
Q: Django Rest Framework Hanging on Large ChoiceField I'm trying to use the built-in API views from Django Rest Framework for a model that has a foreign key to a massive table.
class WidgetAttribute(models.Model):
    widget= models.ForeignKey(Widget, related_name="attributes")
    key = models.TextField()
    value = models.TextField()

I have the following serializer.
class WidgetAttributeSerializer(serializers.ModelSerializer):

    class Meta:
        model = WidgetAttribute

Unfortunately, the Widget table contains roughly 5 million rows, and by default DRF is trying to render this as a choice field including all items. That just hangs forever. I've tried using the instructions here by adding the following line to my serializer:
widget = serializers.RelatedField(queryset=Widget.objects.all(), style={'base_template': 'input.html'})

But I am still running into the same problem. When I look at program execution, it is still calling the __unicode__ method on Widget 5 million times. How can I resolve this issue? Ideally I would like going to /widget/attribute/ to show all existing widgets and then give me a big blank text area to insert data (not broken into choice fields or anything specific). I am not sure if it is relevant, but this is the view I am using:
class WidgetAttributeList(generics.ListCreateAPIView):
    model = WidgetAttribute
    serializer_class = WidgetAttributeSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('widget', 'key')

    def get_queryset(self):
        """
        Overwrite the query to check permissions.
        """
        qs_list = [o.id for o in self.model.objects.all() if hasWidgetPerms(self.request.user.client,
                                                                          o.widget)]
        return self.model.objects.filter(id__in=qs_list)


text:
Q: Is there a way in MySQL to have one column be just a reference to another column on the same table? Is there a way in MySQL to have one column be just a reference to another column on the same table?
I am dealing with a really old MySQL database that has no naming conventions.  I can't just rename the columns because that would break a lot of code. So I thought it would be cool if I could add a "shortcut column" to the poorly named column and then use them interchangeably.

A: I am not exactly sure what you mean by 'reference' (an example would be nice), but... in the SQL statement, you can define the same column multiple times and specify an alias to the column name.
Something like this:
SELECT *, [this_is_a_really_bad_name] as myNewName FROM MyTable

Assuming the table MyTable has the badly designed column this_is_a_really_bad_name, you can now refer to that column by its old name or as myNewName
Is that what you are trying to achieve?

A: Have you considered creating a view?
CREATE VIEW view_name
AS SELECT *, bad_name as New_name
FROM table


text:
Q: Dictionary for automated variable renaming I am working on a Java deobfuscation tool and one of the features I plan to implement is to automatically rename classes and methods with more memorable names. My plan is have a text file with a couple hundred possible names based on random distinctive English words. However, I am not sure where to get such a list.
I came across this which does the same thing for Perl. However, it is not clear what dictionary it is using.
Does anyone have suggestions on the best way to obtain such a list? Ideally the words would all be distinctive and memorable and not clash with common programming keywords or terminology.

A: If you are on unix you can try:
cat /usr/share/dict/words > words.txt

Else there is this link


text:
Q: After pasting a yanked line in Vim, why can't I paste it again? This question was probably answered before, but I tried searching and could not find the answer anywhere.
I am somewhat new to Vim and I am having the following issue. Once I yank a line and paste it, i cannot paste it again. For example, say in Word environment you would copy a text, paste it and then you can paste it again further. But in Vim, once I have pasted it and then try pasting again (p), it pastes the text I pasted the yanked line over.
So for example, I yanked the line "This line is yanked" onto "I don't want this line" and so "This line is yanked" takes place over "I don't want this line".
If I click p further on again, I won't get "This line is yanked" pasted but will get "I don't want this line".
Is there a way I can paste the same yanked line over again without going back and yanking it again?

A: From my .vimrc:
"Paste in visual mode without copying
xnoremap p pgvy

Explanation:
xnoremap - remap only in visual mode
p - Paste
gv - Reselect last selection (not the one that you currently on, but the original)
y - copy it (last selection)
Within this mapping you can paste over visually selected lines over and over.

A: This is because of vim's registers. When you paste a yanked line over another line, the line you just deleted (by pasting over it) takes up the place of the yanked line in the default register (which stores yanked lines). This is to make switching lines easy. Yank one, paste over the other and go back and paste again. However, to keep your yanked line you can specify a register, so instead of using y you can use "ay and this will yank your line into register a. Now to paste you can use "ap and this will paste the contents of register a, which will not get overwritten.
As a bonus "+y or "*y and "+p or "*p paste from the system clipboard (other applications' copy paste) if it is enabled in vim (which it is on most systems).
EDIT: As mentioned in the comments, when you use the yank command, the yanked text not only goes into the default register but also to the 0 register (which won't get overwritten when you paste over something else). This means that you can normally yank using y and then paste it with "0p and it won't get overwritten by anything you paste over.


text:
Q: Next page "spacebar button" press I need the JavaScript to go to 'pag2' when I press spacebar, but it does nothing, there isn't anything on 'pag1' or 'pag2' (the files)
`
document.body.onkeyup = function(e) {
  if (e.key == " " ||
      e.code == "Space" ||
      e.keyCode == 32
  ) {
    window.location.href="pag2.html"
  }
}

`
I've tried changing the href to replace, but it didn't work. You should know what I was expecting, but if you didn't, here's what I was expecting:
It to take me to file 'pag2'


text:
Q: Error while using chatterbot I'm trying to make a simple QnA program using Python chatterbot.
# -*- coding: utf-8 -*-
from chatterbot import ChatBot

bot = ChatBot(
    "SQLMemoryTerminal",
    storage_adapter='chatterbot.storage.SQLStorageAdapter',
    logic_adapters=[
        {
            "import_path": "chatterbot.logic.BestMatch",
            "statement_comparison_function":
"chatterbot.comparisons.levenshtein_distance"
        },
        {
            'import_path' : 'chatterbot.logic.LowConfidenceAdapter',
            'threshold' : 0.3,
            'default_response' : "Sorry. I can not find the exact answer."
        },
        'chatterbot.logic.multi_adapter.MultiLogicAdapter',
    ],
    input_adapter="chatterbot.input.TerminalAdapter",
    output_adapter="chatterbot.output.TerminalAdapter",
    read_only= True
)

print("input question")

while True:
    try:
        print("Q : ",end="")
        bot_input = bot.get_response(None)

    except (KeyboardInterrupt, EOFError, SystemExit):
        break

However, when I try to use the multiadapter function built in chatterbot, I get an error.
Traceback (most recent call last):
  File "C:/Users/KPvoice/PycharmProjects/Contact/ChatterbotTest.py", line
30, in <module>
    bot_input = bot.get_response(None)
  File "C:\Python36\lib\site-packages\chatterbot\chatterbot.py", line 113,
in get_response
    statement, response = self.generate_response(input_statement,
conversation_id)
  File "C:\Python36\lib\site-packages\chatterbot\chatterbot.py", line 132,
in generate_response
    response = self.logic.process(input_statement)
  File "C:\Python36\lib\site-packages\chatterbot\logic\multi_adapter.py",
line 52, in process
    output = adapter.process(statement)
  File "C:\Python36\lib\site-packages\chatterbot\logic\multi_adapter.py",
line  89, in process
    result.confidence = max_confidence
AttributeError: 'NoneType' object has no attribute 'confidence'

I do not know how to solve it.
The working environment is Windows 10, Python 3.7

A: The MultiLogicAdapter typically doesn't get used directly in this way.
Each logic adapter that you add to the logic_adapters=[] will get processed by the MultiLogicAdapter internally by ChatterBot, no need to explicitly specify it.


text:
Q: ElasticSearch: delete where _type contains Hi I would like to delete all indexes belongings to a particular type, but I have this error

[illegal_argument_exception] request [/datastorage] contains
  unrecognized parameter: [type]

deleteAllItems: function (type,callback) {
        console.log(type)
        client.indices.delete({
            index: 'datastorage',
            type : 'cliente_1',
            body: {
                query: {
                        "match_all": {}
                }
            }
        }, function (err, res) {
            if (err) {
                console.error(err.message);
            }
            callback();
        });

    }

Thanks
Andrea


text:
Q: Deleting Duplicates EXCEL VBA Macro I need some help with a macro and I'm not sure where to even start as I am quite new to this. I will have a list of data/Ref numbers in column "A" starting in "A7". Many of these Ref numbers will have duplicates. (mainly 2 duplicates)
Although, there are certain cases in which I will have 3 or 4 duplicates of the same Ref numbers. I need a macro to search for duplicate values In column "A" that appear more than twice and delete them and the row they are in while keeping the first and last instance.
I hope I explained this clearly enough to understand. I attached a snapshot of an example below.
Columns "A" through "C" contain a data set and it contains duplicates with one instance where there are 3 of them. (Highlighted in Red text) The final result I want is shown in columns "G" through "I".
Please note this needs to be done with a macro/VBA and the length of data in the columns and rows may vary each time this macro is ran, so it would need to apply till last used row and column.
Any help would be much appreciated!
Here is the basic script which I applied but the problem is it will delete all duplicates.
    Sub Dup ()
M = Cells(Rows.Count, "A").End(xlUp).Row

For i = M To 7 Step -1
        Set rlook = Range(Cells(i - 1, "A"), Cells(7, 1))
        If Application.WorksheetFunction.CountIf(rlook, Cells(i, "A")) > 0 Then
            Cells(i, "A").clear
        End If
    Next i
End Sub

Thanks

A: You need to look at the previous row value and the next row value. If the previous row's value is the same as the current and the next one is too... It's a 3rd+ record.
If (Current = Previous) AND (Current = Next) Then
Cells(i, "A").clear
End if

A: This should work for you:
Sub DeleteDuplicates()
Dim lRow As Long
Dim i, j, k As Integer
Dim Duplicates() As Integer
Dim sht As Worksheet
Dim Val1, Val2 As String

Set sht = Worksheets("Sheet1")

lRow = sht.Cells(Rows.Count, 1).End(xlUp).Row
Index = 0

For i = 7 To lRow
    Val1 = sht.Cells(i, 1).Value
    Index = 0
    For j = i + 1 To lRow
        Val2 = sht.Cells(j, 1).Value
        If Val1 = Val2 Then
            ReDim Preserve Duplicates(Index)
            Duplicates(Index) = j
            Index = Index + 1
        End If
        If j = lRow Then
            If Index > 1 Then
                For k = UBound(Duplicates) - 1 To 0 Step -1
                    sht.Rows(Duplicates(k)).EntireRow.Delete
                Next k
            End If
        End If
    Next j
Next i
End Sub

A: Use a Dictionary to save the last row where a value last appeared, so to add it to the deleted range when found again. The trick is, don't save it if it is the first appearence: on first appearance, put zero in the dictionary instead of the row number, so that you can avoid deleting the first appearance.
Sub keepFirstAndLast()
  Dim toDelete As Range: Set toDelete = Sheet1.Rows(999999) '(to not start with a null range)
  Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")

  Dim a As Range
  For Each a In Sheet1.Range("A7", Sheet1.Range("A999999").End(xlUp))
    If Not dict.Exists(a.Value2) Then
      dict(a.Value2) = 0 ' first appearence, dont save the row
    Else
      ' if last observed occurrence was a duplicate, add it to deleted range
      If dict(a.Value2) > 0 Then Set toDelete = Union(toDelete, Sheet1.Rows(dict(a.Value2)))
      dict(a.Value2) = a.row ' not first appearence, save the row for eventual deletion
    End If
  Next
  toDelete.Delete
End Sub


text:
Q: Source of long running find process on server I'm wondering where a long running find process on my ubuntu linux server (14.04 LTS) came from and what the meaning of it is. Here is the output of ps:
16915 ?        SN    32:41 /usr/bin/find /tmp /var/tmp -type f -exec head -n 1 {} ;

According to top this causes quite some CPU load. As far as I understand it, it checks the first line of every file in /var/tmp and /tmp with head - so it does nothing besides causing load?
Can anybody tell me what this process is supposed to do and where it might come from? And, if not needed, how I can get rid of it? I killed it once, but it reappeared.
EDIT: The server is used as a web server with PHP, MySQL, Varnish - if you need to know more about the installed software, let me know.
Thanks!

A: Thanks to "embedded" I checked the parent of the process via
cat /proc/[PID]/status | grep PPid
and it turns out that its parent was
/bin/sh /usr/sbin/chkrootkit -q
So everything seems fine.


text:
Q: confusion related to arrays of arrays and iteration I have a local variable ID within my main method as follow :
    ID = new int[9];
    ID[0] = 245;
    ID[1] = 76644;
    //etc

I also have an arrayList of object , with the following constructor :
    public Songs( String songName, String artistName, Integer duration, double price) {

    this.songName = songName;
    this.artistName =artistName;
    this.duration = duration;
    this.price = price;

I initiated a 2d array as following :
   Songs reco[][];
    reco = new Songs [99999] [];
    for (int i=0; i<99999; i++) {
        reco[i] = new Songs[20];
    }

What I am trying to do is use my variable ID as the first index of my 2d array, as follow :
    reco[ID[7]][1] = new Songs("Human", "The Killers", 288, 0.19); // ID always is a 5 digit number

So that i can skim through my 2d array, using the [ID[x]] as my reference in order to add the different values of duration i might come accross.
assuming the following 2d arrays :
     reco[ID[7]][0] = new Songs("Better Now", "Post Malone", 239, 0.25);
    reco[ID[7]][1] = new Songs("Human", "The Killers", 288, 0.19);
    reco[ID[0]][2] = new Songs("Smells like teen spirit", "Nirvana", 214, 0.28);

the expected outcome should be :
     "Customer:" [ID[7] total song duration is 239+288
     "Customer:" [ID[0]] total song duration is 214

Problem is, whatever loop i manage to fabricate, i end up with a null pointer error, as i am comparing [ID[x]][v] to [ID[x][v+1], calling a get() method on each, eventually reaching the null value.
Hope my problem is clear enough.
best to all
(i am aware one can make the numbers to iterate with less important with a hash function, although this is not the problem i want to adress right now)

A: The null pointer exception is caused by accessing your array filled with null Elements by default. You are using elements like

reco[ID[7]][1] = ...

without checking if the index 7 in ID array is an element or null.
If you want to create a really long Array like new Songs[99999] you should use a List and Iterators so there will be no reserved space in memory for that really long Array of
"99999 Songs"

Songs reco[][];
    reco = new Songs [99999] [];
    for (int i=0; i<99999; i++) {
        reco[i] = new Songs[20];
    }

It's much easier to create a ArrayList or List and fill this up with a List of songs like:
List<List<Songs>> songs = new ArrayList<ArrayList<Songs>>();

Then you can iterate throught the list like:
for(List<Songs> tempSongsArray : songs)
{
   for(Songs tempSong : tempSongsArray)
   {
      //Code using tempSong as Songs Element
   }
}

Using list should be null-pointer safe cause the length of a list <==> elements in the list


text:
Q: Dynamic single file upload issue? I have a form that generates multiple single file uploads. They currently upload fine but the upload file keeps overwriting $_SESSION['file'][0] in the array .
<?php
if(isset($_SESSION['UploadCount'])){
    for($i=0;$i<=$_SESSION['UploadCount'];$i++){ ?>

        Upload:

        <input type="file" name="Attachment<?php echo $i; ?>" value="<?php echo $i; ?>"id="Attachment" onchange="this.form.submit();"/>
        Choose File

        <input class="file-name" type="text" readonly="readonly" placeholder="<?php if(isset($_SESSION['file'][$i])){ echo $_SESSION['file'][$i]; } else { echo "No file selected"; } ?>" />

        <?php if(isset($_SESSION['UploadError'][$i])){ ?><?php echo $_SESSION['UploadError'][$i]; ?><?php } ?>

        Topic Description
    <textarea class="form-control" name="Topic" cols="20" rows="3"><?php if(isset($_SESSION['Topic'])){ echo $_SESSION['Topic']; } ?></textarea>

<?php } } ?>

The php to do upload is:
for($i=0;$i<=$_SESSION['UploadCount'];$i++){
    if(isset($_FILES["Attachment".$i]["name"])){
        if($_FILES["Attachment".$i]["name"])
        {
            $uperror = "";

            include ($_SERVER['DOCUMENT_ROOT'].'/Core/MultiUpload.php');

            if($uperror==""){
                $_SESSION['file'][$i] = basename($_FILES["Attachment".$i]["name"]);
                $_SESSION['stored'][$i] = $target_file;
            } else {
                $_SESSION['UploadError'][$i] = $uperror;
            }

            header( "Location: ".$hostname."/consultation/?page=".$Page."&assign=".$Assign ) ;
        exit;
        }
    }
}

MultiUpload.php file is:
<?php
$uploadfoldercheck = "../Uploads/".$_SESSION['CompanyName']."/";
$uploadfoldercheck = str_replace(' ', '_', $uploadfoldercheck);
if (!file_exists($uploadfoldercheck))
{
    mkdir($uploadfoldercheck, 0755, true);

    $copy_index = $uploadfoldercheck."/index.php";

    copy('../Uploads/index.php', $copy_index);
}

$filename = "../Uploads/".$_SESSION['CompanyName']."/".$_SESSION['UserID']."/";
$filename = str_replace(' ', '_', $filename);

if (!file_exists($filename))
{
    mkdir($filename, 0755, true);

    $copy_index = $filename."/index.php";

    copy('../Uploads/index.php', $copy_index);
}

$target_file = $filename . basename($_FILES["Attachment".$i]["name"]);
$uploadOk = 1;

$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if file already exists
if (file_exists($target_file)) {
    $uperror = "Sorry, file already exists:".$target_file;
    $uploadOk = 0;
}
// Check file size
if ($_FILES["Attachment"]["size"] > 2000000) {
    $uperror = "File to large. Max 2MB.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "pdf"  ) {
    $uperror = "Sorry, only PDF files are allowed.";
    $uploadOk = 0;
}

if($uploadOk=="1")
{
    if (move_uploaded_file($_FILES["Attachment".$i]["tmp_name"], $target_file)) {

    } else {
        $uperror = "Unable to load File!";
    }
}

?>

Upload count gets initiliased:
    if(!isset($_SESSION['UploadCount'])){
        $_SESSION['UploadCount']=3;
    }


text:
Q: Highchart export filename with special characters I am using Highcharts to render plots within ShinyServer.  Everything works well on Firefox but in Chrome the export chocks on duplicate headers; this is because the filename contains commas.
Is there a way to properly escape the filename within highcharts or Shiny?  The recommendation is to double quote the filename but I only pass the first part of the name to highcharts and not the extension so I cannot double quote the whole string in Shiny.  I have access to the highcharts server so I could modify that if I knew where to look.
I realise the simple solutions are

*

*Not to put commas in the filename or

*Not to use chrome,

but

*

*Sooner or later I will have to use a special character of some sort and

*Chrome is just adhering more strictly to safe practices and other browsers will follow suite one day.

A: You can wrap exporting function by API and then in this part, escape / modify name.
Highcharts.post(options.url, {
        filename: options.filename || 'chart',
        type: options.type,
        width: options.width || 0, // IE8 fails to post undefined correctly, so use 0
        scale: options.scale || 2,
        svg: svg
}, options.formAttributes);


text:
Q: render a child component afterViewInit in Angular

    <ng-container *ngIf="isTrue; else notTrue">
      <app-child
        [property1]="value"
        [property2]="value"
        [property3]="value"
        (function1)="func($event)"
      ></app-child>
    </ng-container>
    <ng-template #notTrue>
     <app-child
        [property1]="value"
        [property2]="value"
        (function1)="func($event)"
      ></app-child>
    </ng-template>

I want to initialize and render the child component wrapped in <ng-template #notTrue> after parent's afterViewInit() hook.
How to do that?
PS I'm using Angular 9

A: In your parent component for this template you could implement AfterViewInit and set isTrue = true like so:
export class ParentComponent implements AfterViewInit {
    isTrue: boolean;

    ngAfterViewInit() {
        this.isTrue = true;
    }
}

A: Whatever you do, you should do the logic to determine your *ngIf's in ngAfterViewInit if you want it to happen at that point in the lifecycle.
This will still cause your ng-template to render before the ngAfterViewInit triggers the switch, however. If you don't want anything to render till after the view is init (say your inputs aren't defined and it's breaking the child component's ngOnInit logic or something) then you could always throw another boolean into the class and set it to true on ngAfterViewInit(). Then, wrap both things inside of a
<ng-container *ngIf="viewHasInitialized">
...app-child components...
</ng-container>


text:
Q: Using BreezeJS for internal and external API I need some advice on how to proceed with this design please:

*

*I use BreezeJS internally on top of my Entity Framework Web API. So
all my data retrievals and saves are done in the Breeze style.

*I now need to expose an API for external consumption which has a subset of
the calls I use internally.

*Ideally I would like to consume the same API internally.

*I do not want to tell the consumers that they have to
use BreezeJS on their client-side to consume my API (I am using
Swagger on top of it)

So, for now I have a separate set of API calls for the External API which go through different validation code and have a structure like:

*

*Get(item)

*Get(items)

*List item

*Post(item)

etc.
My question is: Am I going down the wrong track? Should I either be using BreezeJS on the ExternalAPI or stop using Breeze internally and consume the External API, OR should I perhaps wrap the ExternalAPI methods around Breeze and restrict the saving of the entity graph to the entity type that is being queried at the time only?


text:
Q: Cleaning/Transposing a csv file I have a csv file that has the header row as dates, the first column is the country and the rest of the values are numbers of people that have recovered from a virus.
I am wanting assistance on how to read in the data to have it look like the Answer image below.
I have tried transposing the sheet and then again certain columns to keep the first one, but I am really struggling. I am new to R CODE and was hoping for some help or guidance. Any help would be so valuable.
Initial dataset

desired outcome

A: One approach would be to import your dataset using df <- read.csv("file.csv"), then 'pivot' the data using the pivot_longer() function from the tidyr package (https://tidyr.tidyverse.org/reference/pivot_longer.html):
library(tidyr)

# create an 'example' dataset
df <- data.frame(Country_Region = c("Australia", "New Zealand"),
                 `2020.01.22` = c(0, 0),
                 `2020.01.23` = c(0, 0),
                 `2020.01.24` = c(1, 0),
                 `2020.01.25` = c(2, 0),
                 check.names = FALSE)
df
#>   Country_Region 2020.01.22 2020.01.23 2020.01.24 2020.01.25
#> 1      Australia          0          0          1          2
#> 2    New Zealand          0          0          0          0

# conduct the 'pivot'
df %>%
  pivot_longer(-Country_Region,
               names_to = "date",
               values_to = "recovered")
#> # A tibble: 8 × 3
#>   Country_Region date       recovered
#>   <chr>          <chr>          <dbl>
#> 1 Australia      2020.01.22         0
#> 2 Australia      2020.01.23         0
#> 3 Australia      2020.01.24         1
#> 4 Australia      2020.01.25         2
#> 5 New Zealand    2020.01.22         0
#> 6 New Zealand    2020.01.23         0
#> 7 New Zealand    2020.01.24         0
#> 8 New Zealand    2020.01.25         0

Created on 2022-10-19 by the reprex package (v2.0.1)
Does that solve your problem?


text:
Q: Convert PDF to CSV via Powershell I am trying to take data from a webform that is generated in pdf format and migrate it to csv so I can use my limited powershell knowledge to automate VM builds.  This is all done on linux as well.  This is what I have so far and that seems to work, but I need to automate it all so I need to use wildcards as the file names will change.
pdftotext  -nopgbrk './AndyTest-2 - Linux - Debian 10_13.pdf' test.txt

Import-Csv test.txt | Export-Csv test.csv

A: Cool - it sounds like you've already got 90++% of the solution.
Q: Why not just call your PS script with parameters?
EXAMPLE:
$PdfFile=$args[0]
$TxtFile=$args[1]
$CsvFile=$args[2]
pdftotext  -nopgbrk $PdfFile $TxtFile
Import-Csv test.txt | Export-Csv $CsvFile

One possible "gotcha" is that apparently have spaces in your .Pdf filenames.  One solution is to quote your variable, e.g.:
"$PdfFile"

Look here for more ideas:

*

*https://social.technet.microsoft.com/Forums/en-US/3a527307-5bb1-40fa-94b3-9af0a3e181f3/

*https://social.technet.microsoft.com/Forums/en-US/8e51b6f4-4adf-4253-8228-c410032209f7/
'Hope that helps!


text:
Q: Finding and retrieving consecutive matches Say I want to match a string that should solely consist of parts adhering to a specific (regex) pattern and retrieve the elements in a loop. For this it seems that Matcher.find() was invented. However, find will match any string, not just one that is directly after the pattern, so intermediate characters are skipped.
So - for instance - I want to match \\p{Xdigit}{2} (two hexadecimal digits) in such a way that:

*

*aabb matches;

*_aabb doesn't match;

*aa_bb doesn't match;

*aabb_ doesn't match.

by using find (or any other iterated call to the regex) so I can directly process each byte in the array. So I want to process aa and bb separately, after matching.
OK, that's it, the most elegant way of doing this wins the accept.

Notes:

*

*the hexadecimal parsing is just an example of a simple repeating pattern;

*preferably I would like to keep the regex to the minimal required to match the element;

*yes, I know about using (\\p{XDigit}{2})*, but I don't want to scan string twice (as it should be usable on huge input strings).

A: It appears you want to get all (multiple) matches that appear at the start of the string or right after a successful match. You may combine \G operator with a lookahead that will assure the string only matches some repeated pattern.
Use
(?:\G(?!^)|^(?=(?:\p{XDigit}{2})*$))\p{XDigit}{2}

See the regex demo
Details

*

*(?: - start of a non-capturing group with 2 alternatives:

*

*\G(?!^) - the end of the previous successful match

*| - or

*^(?=(?:\p{XDigit}{2})*$) - start of a string (^) that is followed with 0+ occurrences of \p{XDigit}{2} pattern up to the end of the string ($)

*) - end of the non-capturing group

*\p{XDigit}{2} - 2 hex chars.

Java demo:
String regex = "(?:\\G(?!^)|^(?=(?:[0-9a-fA-F]{2})*$))[0-9a-fA-F]{2}";
String[] strings = {"aabb","_aabb","aa_bb", "aabb_"};
Pattern pattern = Pattern.compile(regex);
for (String s : strings) {
    System.out.println("Checking " + s);
    Matcher matcher = pattern.matcher(s);
    List<String> res = new ArrayList<>();
    while (matcher.find()) {
        res.add(matcher.group(0));
    }
    if (res.size() > 0) {
        System.out.println(res);
    } else {
        System.out.println("No match!");
    }
}

Output:
Checking aabb
[aa, bb]
Checking _aabb
No match!
Checking aa_bb
No match!
Checking aabb_
No match!

A: OK, I may finally have had a brainstorm: the idea is to remove the find() method out of the condition of the while loop. Instead I should simply keep a variable holding the location and only stop parsing when the whole string has been processed. The location can also be used to produce a more informative error message.
The location starts at zero and is updated to the end of the match. Each time a new match is found the start of the match is compared with the location, i.e. end of the last match. An error occurs if:

*

*the pattern is not found;

*the pattern is found, but not at the end of the last match.

Code:
private static byte[] parseHex(String hex){
        byte[] bytes = new byte[hex.length() / 2];
        int off = 0;

        // the pattern is normally a constant
        Pattern hexByte = Pattern.compile("\\p{XDigit}{2}");
        Matcher hexByteMatcher = hexByte.matcher(hex);
        int loc = 0;
        // so here we would normally do the while (hexByteMatcher.find()) ...
        while (loc < hex.length()) {

            // optimization in case we have a maximum size of the pattern
            hexByteMatcher.region(loc, loc + 2);

            // instead we try and find the pattern, and produce an error if not found at the right location
            if (!hexByteMatcher.find() || hexByteMatcher.start() != loc) {
                // only a single throw, message includes location
                throw new IllegalArgumentException("Hex string invalid at offset " + loc);
            }
            // the processing of the pattern, in this case a double hex digit representing a byte value
            bytes[off++] = (byte) Integer.parseInt(hexByteMatcher.group(), 16);

            // set the next location to the end of the match
            loc = hexByteMatcher.end();
        }

        return bytes;
 }

The method can be improved by adding \\G (end of last match) to the regex: \\G\\p{XDigit}{2}: this way the regular expression will fail immediately if the pattern cannot be found starting at the end of the last match or the start of the string).
For regular expressions with an expected maximum size (2 in this case) it is of course also possible to adjust the end of the region that needs to be matched.


text:
Q: How to get RGB fill color values from polygones? I'm trying to get color values from layers inserted into canvas. I used this code but it seems that I'm doing something wrong:
for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    sym = layer.rendererV2().symbols()[0]
    fill = QgsSimpleFillSymbolLayerV2().fillColor()
    p=fill.getRgb()
    print(p)

I always get (0,0,255,255) as a result.

Also this is how it looks Layer properties from one of the polygones in canvas.

 Is there any way or code to do this right?
I would also like to add that second fill color is added  using this code:
sym = layer.rendererV2().symbols()[0]
fill = QgsSimpleFillSymbolLayerV2()
fill.setFillColor(QColor.fromRgb(result[0], result[1], result[2]))
sym.appendSymbolLayer(fill)

A: You assign layer.rendererV2().symbols()[0] to sym variable
sym = layer.rendererV2().symbols()[0]

but then call .fillColor() on QgsSimpleFillSymbolLayerV2() not on your symbol sym. So try:
fill = sym.fillColor()

In QGIS 3 it should be something like this (example for active layer):
lay = iface.activeLayer()
sym = lay.renderer().symbol()[0]
fill = sym.color()
print(fill.getRgb())


text:
Q: how can i make expandable listView in Grid?
I want make ui like this image.
but I don't know how can I make expandable listview in grid.
    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="ElronWebtoon_Test.myLibrary.LibTab" BackgroundColor="White">

    <Grid RowSpacing="0">
        <Grid.RowDefinitions>
            <RowDefinition x:Name="TopGrid"/>
            <RowDefinition />
            <RowDefinition x:Name="menuRow"/>
        </Grid.RowDefinitions>

        <Grid Grid.Row="0" x:Name="GlobalLayout" >

            <Grid.RowDefinitions>
                <RowDefinition x:Name="TopBtn_Grid"/>
                <RowDefinition x:Name="menu_Grid"/>
            </Grid.RowDefinitions>

            <Grid Grid.Row="0" VerticalOptions="Start" >
                <Label x:Name="labelBox1" Text="LabelBox1" Font="Bold, 16" TextColor="Black" HorizontalOptions="Start"  HorizontalTextAlignment="Center" VerticalTextAlignment="Center" VerticalOptions="Center" Grid.Column="0" BackgroundColor="#A8D2F1">
                    <Label.GestureRecognizers>
                        <TapGestureRecognizer/>
                    </Label.GestureRecognizers>
                </Label>
                <Label x:Name="LabelBox2" Text="LabelBox2" Font="Bold, 16" TextColor="Black" HorizontalOptions="End"  HorizontalTextAlignment="Center" VerticalTextAlignment="Center" VerticalOptions="Center" Grid.Column="0" BackgroundColor="#A8D2F1">
                    <Label.GestureRecognizers>
                        <TapGestureRecognizer />

                    </Label.GestureRecognizers>
                </Label>
            </Grid>

            <Grid Grid.Row="1" x:Name="libMenu" RowSpacing="0" HorizontalOptions="CenterAndExpand">

                <Grid Grid.Column="0" x:Name="menuGrid_1" HorizontalOptions="Center">
                    <Button   BorderRadius="30" BorderColor="Black" BorderWidth="2" BackgroundColor="White"  VerticalOptions="Center"/>
                    <Label x:Name="BtnText1" Text="BtnText1" TextColor="Black" VerticalOptions="Center" HorizontalOptions="Center" VerticalTextAlignment="Center"/>
                </Grid>
                <Grid Grid.Column="1" x:Name="menuGrid_2" HorizontalOptions="Center">
                    <Button   BorderRadius="30" BorderColor="Black" BorderWidth="2" BackgroundColor="White"  VerticalOptions="Center"/>
                    <Label x:Name="BtnText2" Text="BtnText2" TextColor="Black" VerticalOptions="Center" HorizontalOptions="Center" VerticalTextAlignment="Center"/>
                </Grid>
                <Grid Grid.Column="2" x:Name="menuGrid_3" HorizontalOptions="Center">
                    <Button   BorderRadius="30" BorderColor="Black" BorderWidth="2" BackgroundColor="White"  VerticalOptions="Center"/>
                    <Label x:Name="BtnText3" Text="BtnText3" TextColor="Black" VerticalOptions="Center" HorizontalOptions="Center" VerticalTextAlignment="Center"/>
                </Grid>

            </Grid>

        </Grid>

        <Grid Grid.Row="1" VerticalOptions="Fill" x:Name="inner_Content">

        </Grid>

        <Grid Grid.Row="2" >
            <Grid>
                <Button Text="BTN1" Grid.Column="0" />
                <Button Text="BTN2" Grid.Column="1"/>
                <Button Text="BTN3" Grid.Column="2"/>
                <Button Text="BTN4" Grid.Column="3"/>
                <Button Text="BTN5" Grid.Column="4"/>
            </Grid>
        </Grid>
    </Grid>

</ContentPage>

this is my sample code.
I want insert expandable listview in Grid, named inner_Content in this code.
but if I searching expandable listview, that only in contentPage.
not in grid.
can you help me?

A: I guess you are looking something like an accordion control to be used in Xamarin.

Check the URL below:
  https://www.codeproject.com/Articles/1088093/Simple-Accordion-User-Control-in-Xamarin-Forms

Hope this helps, mark this as an answer if you think this meets your requirement.
Regards,
N Baua


text:
Q: How do I create a geoJSON layer with a div icon instead of the leaflet standard icon? I'm trying to load a geoJSON layer with div icons, since they are supposed to be more lightweight.
My problem is that I cannot get the divIcons to display.  The geoJSON object is stored as individualPoints.  I've tried styling the icon directly:
var myIcon = L.divIcon({className: 'my-div-icon'});

var geoJsonLayer = L.geoJson(individualPoints, {icon: myIcon});
map.addLayer(geoJsonLayer); //shows standard icon

and styling the icon on each layer:
var geoJsonLayer = L.geoJson(individualPoints, {
    onEachFeature: function (feature, layer) {
        layer.setIcon(myIcon);
    }
});
map.addLayer(geoJsonLayer); // nothing displays

and even creating an additional marker, and adding that to the map:
// create object to save markers
var markersID = [];

// exchanges latitude & longitude
function switchLatLong(oldLocation) {
    return new L.LatLng(oldLocation[1], oldLocation[0]);
}

var geoJsonLayer = L.geoJson(individualPoints, {
    onEachFeature: function (feature, layer) {
        // make a marker and add to map individually
        markersID[feature.properties.id] = L.marker(switchLatLong(feature.geometry.coordinates),{icon: myIcon});
        map.addLayer(markersID[feature.properties.id]); //nothing displays on map
    }
});

The first code snippet shows the standard leaflet icon; the second and third snippets do not display anything.
Question: How does one load a geoJson using divIcon?

Edit:
Using the new keyword on the second and third snippets displays the divIcon, but this doesn't work in the first code snippet.  Also, I would still like to have the divIcon appear without iterating through the layers to generate a new marker.  Also, why must the new keyword be used?
var geoJsonLayer = L.geoJson(individualPoints, {
    onEachFeature: function (feature, layer) {
        // set icon to a new DivIcon
        layer.setIcon(new L.DivIcon());
    }
});
map.addLayer(geoJsonLayer); // divIcon displays on map

A: Since you want to Set a DivIcon, you should know that it can be applied only to Markers.
The GeoJSON docs Say:

Points are handled differently than polylines and polygons. By default
  simple markers are drawn for GeoJSON Points. We can alter this by
  passing a pointToLayer function in a GeoJSON options object when
  creating the GeoJSON layer. This function is passed a LatLng and
  should return an instance of ILayer, in this case likely a Marker or
  CircleMarker.

You can use the following code to set your custom div icon, like this
    var myIcon = L.divIcon({
        iconSize: new L.Point(25, 25),
        className: 'my-div-icon'
    });

    var geoJsonLayer = L.geoJson(individualPoints, {
            pointToLayer: function (feature, latlng) {
                return L.marker(latlng, {icon: myIcon});
            }
        }).addTo(map);

A: I'm going to add this as an answer, because it works.  I'm still interested in finding out why I seem to need to create a new DivIcon each time, or if there's a more straightforward way to do this...
var geoJsonLayer = L.geoJson(individualPoints, {
    onEachFeature: function (feature, layer) {
        // set icon to a new DivIcon
        layer.setIcon(new L.DivIcon());
    }
});
map.addLayer(geoJsonLayer); // divIcon displays on map


text:
Q: Efficient way to pass Bitmap into registered COM component I have registered COM Class and interface written in .NET 2.0 . Now i am looking for a way to pass Bitmap object from WindowsForms .Net 4.5 application into COM component.
When i try to do this code:
 Type type = Type.GetTypeFromCLSID(clsid);
 source = (IBaseFilter) Activator.CreateInstance(type);
        public void SetBitmap(Bitmap input)
        {
 IImageSourceFilter advSource = (IImageSourceFilter)source;
 advSource.SetBitmapObj(input);
        }

I get next exception
    System.InvalidCastException
  HResult=0x80004002
  Message=Unable to cast COM object of type 'System.__ComObject' to class type 'System.Drawing.Bitmap'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
  Source=DShow
  StackTrace:
   at RTSPTestAPP.Camera.BMPtoCam.IImageSourceFilter.SetBitmapObj(Object inp)
   at RTSPTestAPP.Camera.BMPtoCam.SetBitmap(Bitmap input) in C:\Users\...\BMPtoCam.cs:line 43

Passing it as byte array is not efficient and locates a lot CPU resources (and i am sending alot bitmaps from decoded videostream).

A: Found a way: i just develop COM component with same .net as program which will use it. Then on Type type = Type.GetTypeFromCLSID(clsid); i'll get not raw type (System.__ComObject), instead i`ll get correct interface, with correct methods. And i just pass bitmap as argument. Its important too add reference to this assembly too.


text:
Q: Field fixed by a given aut group Suppose I have an algebraic field extension $L/F$. What do I call the fixed field of $\operatorname{Aut}(L/F)$? It's sort of like the mirror image of the Galois closure: the smallest field $K>F$ such that $L/K$ is Galois.
As a particular example, what is the fixed field of $\operatorname{Aut}(\overline{F_p(t)}/F_p(t))$?


text:
Q: Nodejs HTTP Createserver - unpredictable javascript execution while serving from html files When I serve an html file, having some javascript, from my nodejs web server I get different results, compared to when I include the same javascript from an external source. I have verified that directly opening the html file with the javascript inline or external source works the same, as expected.
In the example below I get "Modified header" in h1 tag, whereas with javascript as external source I get "Unmodofied header" in h1 tag.
Can somebody explain how to rectify the problem? Thanks.
Code for nodejs web server:
var http = require('http')
var fs = require('fs')
http.createServer(function (request, response) {
  fs.readFile('htmlfile.html', function(err, data) {
  response.writeHead(200, {'Content-Type': 'text'})
  response.write(data)
  response.end()
  })
}).listen(8081)

htmlfile.html is as follows:

 Unmodified header

A: In a nutshell, your http server is not configured to send populate_header.js to the browser when the browser asks for it.
When you do this in your HTML file:

You're telling the browser to send your web server a request for a resource named populate_header.js.  But your web server does not have a request handler that looks at what file is being requested and serve that specific resource.  Your web server always sends htmlfile.html no matter what resource is being requested.  So, the browser asks for a script file and gets an HTML file (causing it to basically just ignore it).  Thus, your Javascript in populate_header.js is never delivered to the browser and thus the script in it never runs.
When you include the script inline, the Javascript is delivered with the HTML and works just fine without requiring another route on your web server.
A node.js web server serves NO files at all by default.  It only serves files that you create a route handler for.  It is possible to create a single route that will serve lots of static files (when using the Express framework, express.static() does exactly that).  But, by default, it does not serve any files.
As soon as you need more than one route handler, I would recommend using a very simple framework like ExpressJS because it will save you a lot of time and is very lightweight.  But, if you were going to add a new route handler to your existing little web server, you could do so like this:
var http = require('http')
var fs = require('fs')
http.createServer(function (request, response) {
    if (request.method === "GET") {
        let fname;
        // Look at what resource was requested and match that up
        // with the appropriate file name
        // DO not accept any resource requested because that could open up
        // your server for people to request your actual server code files
        switch(request.url) {
            case "/":
                fname = "htmlfile.html";
                break;
            case "/populate_header.js":
                fname = "populate_header.js";
                break;
            default:
                break;
        }
        if (fname) {
            fs.readFile(fname, function(err, data) {
                if (err) {
                    response.writeHead(404);
                    response.end();
                } else {
                    response.writeHead(200, {'Content-Type': 'text'})
                    response.write(data)
                    response.end();
                }
            });
        } else {
            response.writeHead(404);
            response.end();
        }
    }
}).listen(8081)

Here, you can see you're looking at request.url to see what exactly was requested and then sending that resource.  It's also looking a request.method to only respond to GET requests.  And, it's sending 404 responses when some other file is sent.

This would all be a lot simpler using the ExpressJS framework.
const express = require('express');
const app = express();

// look for matching static resources in the static_files subdirectory
app.use(express.static("static_files"));

// send the htmlfile.html file when / is requested
app.get("/", function(req, res) {
   res.sendFile("static_files/htmlfile.html");
});

app.listen(8081);

Then, just locate all your static resources in a sub-directory below your main server directory named static_files and the Express framework will automatically look in that sub-directory for files that match the requested URL.  This code adds one custom route for / that specifically sends the htmlfile.html file, and you can certainly customize that however you want.

For further discussion of how node.js servers don't send any files by default, see these other related answers:
Can't load local files when using NodeJS server
Resources not loading in express
ajax request gives a 404 with express server (chrome) loads successfully with firefox without a server?
How to get files above the server directory in Node.js


text:
Q: SwiftUI String conform Identifiable seems not correct I am using an array in a List, in the List there's a ForEach, like:
struct AView: View {

    @State var foo: [String] = ["a", "b", "c"]

    var body: some View {
        ZStack {
            Color.white
            List {
                ForEach(foo.indices) { index in
                    Text(foo[index])
                }
            }
        }

    }
}

This works well, then I want to add a button to insert new items:
   List {
            ForEach(foo.indices) { index in
                Text(foo[index])
            }
        }
        Button("Add") {
            foo.append("foo")
        }
    }

Then I got the error, which is obviously:
ForEach<Range<Int>, Int, Text> count (4) != its initial count (3). `ForEach(_:content:)` should only be used for *constant* data. Instead conform data to `Identifiable` or use `ForEach(_:id:content:)` and provide an explicit `id`!

Here mentioned
Identifiable or use ForEach(_:id:content:)
I can use  ForEach(foo.indices, id:\.self) which solved the issue.
I also want to try Identifiable, and don't use id:\.self in the ForEach, ForEach(foo.indices).
I added extension to String like:
extension String: Identifiable {
    public var id: String { self }
}

But still got the same issue. Any thing I miss-understood? thanks!
EDIT
According to the comment @New Dev, as I literal indices, so I added extension to Int:
extension Int: Identifiable {
    public var id: Int { self }
}

still doesn't work.

A: ForEach has multiple init overloads.
init(Range<Int>, content: (Int) -> Content) only works with a constant range - hence the error.
init(Data, content: (Data.Element) -> Content) requires Data to conform to RandomAccessCollection of Identifiable elements. That's the one you want to use.
The problem is that your RandomAccessCollection (to which Range<Int> conforms) is a collection of Int elements.
Though you can conform Int to Identifiable, this would still not work. It would still use the first ForEach.init with a Range<Int> parameter, because of method overload preference - i.e. Range<Int> matches the more specific init with Range<Int> parameter, rather than the less specific init with RandomAccessCollection.

So, your choices are:

*

*Use the third init(Data, id: KeyPath<Data.Element, ID>, content: (Data.Element) -> Content) by explicitly specifying the id.

ForEach(foo.indices, id:\.self) { index in
}

*Convert to Array<Int> and conform Int: Identifiable:

extension Int: Identifiable { var id: Self { self } }

ForEach(Array(foo.indices)) { index in
}


text:
Q: Need to have edit button which changes field to editable; on submit it alters database I made a nice flowchart for you since this is kind of complicated.
Basically, I want to have a list of fields from a column in the database, displayed in a table. They have an EDIT button ext to them, and when you click the edit button you can edit the field. Then you click submit and it alters the table with the new value.
I pretty much know how to do each of the individual things, but I am having trouble combining all these things into one.
Flowchart:

Code:

STEP 1:

            First Name
           <?php
            // Collects data from "users" table

             $data = mysql_query("SELECT * FROM users")
             or die(mysql_error());

            // array

             $info = mysql_fetch_array( $data );

            // print data

             // Print out the contents of the entry
             Print "
";
             Print "".$info['fname'] . " ";
             Print "	";
             Print "".$info['lname'] . " ";
             Print "	";
             Print "".$info['email'] . "
";
             Print "
";

             // loop for each row in the column

             while($info = mysql_fetch_array( $data ))
             {
             Print "".$info['fname'] . " ";
             Print "	";
             Print "".$info['lname'] . " ";
             Print "	";
             Print "".$info['email'] . "
";
             Print "
";
             }
              ?>

STEPS 2 & 3: (incomplete or possibly inaccurate as well)
    <?php
        if(isset($_POST['submit'])){

            $variable = "somethinghere";
            $variable = "somethinghere";
            $variable = "somethinghere";
            $variable = "somethinghere";
            $variable = "somethinghere";

            $query = "UPDATE users
                      SET fname='$variable1'
                      WHERE $variable2='$variable3' AND $variable4='$variable5'
              (fname, lname, email) VALUES ('".$_POST['fname']."', '".$_POST['lname']."', '".$_POST['email']."')";

            mysql_query($query);

        }else{
    ?>

        <form method="post">

First Name:*

<input name="fname" type="text" />

Last Name:*

<input name="lname" type="text" />

Email:*

<input name="email" type="text" />

<input id="submit-button" value="submit" name="submit" type="submit" />

        </form>
    <?php }?>

A: Using JQuery is the way to change it.
Here's a plugin: http://www.appelsiini.net/projects/jeditable/default.html ; http://www.appelsiini.net/projects/jeditable


text:
Q: Merge the [named-arguments] and [named-parameters] tags I noticed that there are separate tags for named-arguments and named-parameters on Stack Overflow, so I'm suggesting that these tags should be merged, since they appear to be completely synonymous.

A: That was 9 questions to retag, from named-arguments to named-parameters.
named-arguments will be deleted tomorrow.


text:
Q: Como instalo ubuntu en una Pc que tiene lubuntu I want to install Ubuntu on my computer which has Lubuntu. How can I remove Lubuntu and install Ubuntu. Thanks.
Hola la verdad soy nuevo utilizando linux y no se como hacerlo pues yo quiero instalar ubuntu en mi ordenador pero tengo instalado el lubuntu como le puedo hacer para eliminar lubuntu y poner ubuntu bueno espero y me puedan responder Gracias.

A: You need to first install the ubuntu-desktop package from the Software Center. This will install everything related to Ubuntu. Afterwards, logout and then, on the login window (Where you type your user/password) select Ubuntu.
After logging in Ubuntu you can proceed to remove the lubuntu-desktop package and anything related to Lubuntu. Know that leaving it there won't affect performance. You will be only using a bit more space.


text:
Q: Divide 2 columns into 4 based on odd and even I want to divide 2 columns into 4 based on odd and even. I have a table
INSERT INTO @tab
VALUES ('test', 'desc'), ('test1', 'desc1'), ('test2', 'desc2'),
       ('test3', 'desc3'), ('test4', 'desc4')

I tried the following query:-
SELECT
    CASE
       WHEN A.RNK  % 2 = 1
          THEN Heading
    END AS Headingodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN Heading
    END AS Headingeven,
    CASE
       WHEN A.RNK  % 2 = 1
          THEN A.[Description]
    END AS Descriptionodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN A.[Description]
    END AS Descriptioneven
FROM
    (SELECT
         Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
     FROM
         @tab) A

Results I am getting from the query is:-

But I want the result in following format:-
DECLARE @tab1 TABLE(Headingodd VARCHAR(100), Headingeven VARCHAR(100), Descriptionodd VARCHAR(100), Descriptioneven VARCHAR(100))

INSERT INTO @tab1
VALUES ('test', 'test1', 'desc', 'desc1'),
       ('test2', 'test3', 'desc2', 'desc3'),
       ('test4', null, 'desc4', null)

SELECT * FROM @tab1

A: The other answers just seem so complicated.  This is really just aggregation and arithmetic:
select min(case when rnk % 2 = 1 then heading end) as heading_odd,
       min(case when rnk % 2 = 0 then heading end) as heading_even,
       min(case when rnk % 2 = 1 then description end) as description_odd,
       min(case when rnk % 2 = 0 then description end) as description_even
from (select t.*, row_number() over (order by id) as rnk
      from tab t
     ) t
group by (rnk - 1) / 2
order by min(rnk);

Here is a db<>fiddle.
Note:  You don't even need rnk if you know that the id is sequential with no gaps.

A: You need to generate the odd and even headings and descriptions separately and then you can JOIN them together on matching row numbers:
WITH A AS (
  SELECT Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
  FROM tab
),
ODD AS (
  SELECT Heading, [Description],
         (RNK - 1) / 2 AS RN
  FROM A
  WHERE RNK % 2 = 1
),
EVEN AS (
  SELECT Heading, [Description],
         (RNK - 1) / 2 AS RN
  FROM A
  WHERE RNK % 2 = 0
)
SELECT o.Heading AS Headingodds,
       e.Heading AS Headingeven,
       o.Description AS Descriptionodds,
       e.Description AS Descriptioneven
FROM ODD o
LEFT JOIN EVEN e ON e.RN = o.RN
ORDER BY o.RN

Output:
Headingodds     Headingeven     Descriptionodds     Descriptioneven
test            test1           desc                desc1
test2           test3           desc2               desc3
test4                           desc4

Demo on dbfiddle

A: you can also try this:
create table #tab(id int,test varchar(40),des varchar(40))

INSERT INTO #tab
VALUES (1,'test', 'desc'), (2,'test1', 'desc1'), (3,'test2', 'desc2'),
   (4,'test3', 'desc3'), (5,'test4', 'desc4')
select * from #tab

with cte as
(select ROW_NUMBER()OVER(ORDER BY a.TestODD) row_num,*
    from (select(case when id in (1,3,5)  then '0' else test end) TestODD from #tab) a
    where a.TestODD!='0'),
cte2 as (
select ROW_NUMBER() OVER(ORDER BY b.TestEven)row_num,*
   from (select(case when id in(2,4)then '0' else test end)TestEven from #tab)b
   where b.TestEven!='0'
 ),
 cte3 as (
 select ROW_NUMBER()OVER(ORDER BY  c.desODD) row_num,*
   from (select (case when id in (1,3,5)then '0' else des end) desODD from #tab)c
   where c.desODD!='0'
 ),
 cte4 as (
 select ROW_NUMBER()OVER(ORDER BY d.destEven)row_num,*
   from (select(case when id in (2,4)then '0' else des end)destEven from #tab) d
   where d.destEven!='0'
 )
  select TestEven,TestODD,destEven,desODD from cte2
       left join cte on cte.row_num=cte2.row_num
      left join cte3 on cte2.row_num=cte3.row_num
      left join cte4 on cte2.row_num=cte4.row_num


text:
Q: Transposing and Aggregating DataFrame I have a dataframe like this
  name tag  time  val
0  ABC   A     1   10
0  ABC   A     1   12
1  ABC   B     1   12
1  ABC   B     1   14
2  ABC   A     2   11
3  ABC   C     2   12
4  DEF   B     3   10
5  DEF   C     3    9
6  GHI   A     4   14
7  GHI   B     4   12
8  GHI   C     5   10

Each row is a timestamp and shows the value between the name and tag in that row.
What I want is a dataframe where each row shows the mean value from each tag at each timestamp, like this:
  name  time     A     B     C
0  ABC     1  11.0  13.0   NaN
1  ABC     2  11.0   NaN  12.0
2  DEF     3   NaN  10.0   9.0
3  GHI     4  14.0  12.0   NaN
4  GHI     5   NaN   NaN  10.0

I can achieve this successfully by grouping by name and time and returning a transposed series each time:
def transpose_df(observation_df):
  ser = pd.Series()
  for tag in tags:
    ser[tag] = observation_df[observation_df['tag'] == tag]['val'].mean()
  return ser

tdf = df.groupby(['name', 'time']).apply(transpose_df).reset_index()

But this is slow. I feel like there must be a smarter way using a builtin transpose/reshape tool, but I can't figure it out. Can anyone see suggest a better alternative?

A: In [175]: df.pivot_table(index=['name','time'], columns='tag', values='val').reset_index()
Out[175]:
tag name  time     A     B     C
0    ABC     1  11.0  13.0   NaN
1    ABC     2  11.0   NaN  12.0
2    DEF     3   NaN  10.0   9.0
3    GHI     4  14.0  12.0   NaN
4    GHI     5   NaN   NaN  10.0

A: Option 1
Use pivot_table:
df.pivot_table(values='val',index=['name','time'],columns='tag',aggfunc='mean').reset_index()

Output:
tag name  time     A     B     C
0    ABC     1  11.0  13.0   NaN
1    ABC     2  11.0   NaN  12.0
2    DEF     3   NaN  10.0   9.0
3    GHI     4  14.0  12.0   NaN
4    GHI     5   NaN   NaN  10.0

Option 2:
Use groupby and unstack
df.groupby(['name','time','tag']).agg('mean')['val'].unstack().reset_index()

Output:
tag name  time     A     B     C
0    ABC     1  11.0  13.0   NaN
1    ABC     2  11.0   NaN  12.0
2    DEF     3   NaN  10.0   9.0
3    GHI     4  14.0  12.0   NaN
4    GHI     5   NaN   NaN  10.0

Option 3
Use set_index and mean and unstack:
df.set_index(['name','time','tag']).mean(level=[0,1,2])['val'].unstack().reset_index()

Output:
tag name  time     A     B     C
0    ABC     1  11.0  13.0   NaN
1    ABC     2  11.0   NaN  12.0
2    DEF     3   NaN  10.0   9.0
3    GHI     4  14.0  12.0   NaN
4    GHI     5   NaN   NaN  10.0

A: You can also groupby and then unstack (equivalent to a pivot table).
>>> df.groupby(['name', 'time', 'tag'])['val'].mean().unstack('tag').reset_index()
tag name  time   A   B   C
0    ABC     1  11  13 NaN
1    ABC     2  11 NaN  12
2    DEF     3 NaN  10   9
3    GHI     4  14  12 NaN
4    GHI     5 NaN NaN  10

By the way, transform is for when you want to maintain the shape of your original dataframe, e.g.
>>> df.assign(tag_mean=df.groupby(['name', 'time', 'tag'])['val'].transform(np.mean))
  name tag  time  val  tag_mean
0  ABC   A     1   10        11
0  ABC   A     1   12        11
1  ABC   B     1   12        13
1  ABC   B     1   14        13
2  ABC   A     2   11        11
3  ABC   C     2   12        12
4  DEF   B     3   10        10
5  DEF   C     3    9         9
6  GHI   A     4   14        14
7  GHI   B     4   12        12
8  GHI   C     5   10        10


text:
Q: Change an existing file's permissions using cmake I have a component that I install onto my Linux distro using cmake.  There is a file on my machine on which I'd like to change permissions - I want to make it non-executable.
My use case is this:
There is a directory that contains several files.  A process periodically executes all of the files in that directory if they are executable.  When I install my program, I would like to make one of those files non-executable and drop my executable file(s) in that directory to be used by the system instead.
I found the file manipulation section in the cmake docs but the FILE_PERMISSIONS feature requires that I include a COPY or INSTALL of a file in order to use it.
How does one update file permissions on a file that already exists on the system?  I haven't tried anything yet because I don't see any support for such a feature.
Honestly, this seems a little beyond cmake's reach (manipulating files outside of my project) so if there is an alternative way to solve this cleanly, I'm open to ideas.  I'd like it to be tied to my existing application's installation procedure (hence my desire to utilize cmake).

A: Write a shell script that changes permissions and run it during installation using install(CODE "execute_process(COMMAND \"yourscript.sh\")".


text:
Q: Check where the consumer of kafka are connected Scenario
We have a shared Kafka environment and it is being used by multiple machines.
We manage by collaborating and run only one application at one time.
But now 1 consumer is running and there is no machine (in our knowledge) that is now running that application. Due to this, we are not able to properly test the application flow.
Question
Is there a way in Kafka (or Kafka Confluent) to tell on which machine(IP Address) is the consumer is running? So that I can identify the machine and kill the process there.

A: You can use any approach

*

*kafka-consumer-group API
Command to run in bash is:
enter code here
./kafka-consumer-groups.sh --describe  --group=<my-group> --bootstrap-server=<hostname>:<port> --members
Output of above command will give you these details.

CONSUMER-ID
HOST
CLIENT-ID
#PARTITIONS

*Zookeeper
You can store instance ip in zookeeper using curator when starting consumer and remove the entry while stopping the instance.

*Kafka Manager
There are some third party tools which give us kafka related metrics like

*

*Brokers List

*Topic List

*Consumer List

*Lags

Note: Approach 1 and 3 will give you correct answer after some delay