text:
Q: How to make a html table appear using ajax and jquery? Ive been trying to make my html table appear when i click the submit button but all it does is inserts data into the database and the html table doesnt appear.
here is my index.html
<!DOCTYPE html>

    <form action = "insert.php" method="post">
      Firstname: <input type="text" name="firstname">

      Lastname: <input type="text" name="lastname">

      Middlename: <input type="text" name="middlename">

      <button type="submit">submit</button>
    </form>

here is my table.php
<?php

$con = mysqli_connect("localhost","root","","study");

if (mysqli_connect_errno($con))
{
  echo "Failed to connect to mysql" . mysqli_connect_error();
}

echo '
';
echo '
';
echo ' FIRSTNAME	';
echo 'LASTNAME	';
echo ' MIDDLENAME	';
echo ' DELETE	';
echo '
';
$result = mysqli_query($con,"SELECT * FROM sample_employers");
while($row=mysqli_fetch_array($result))
{
  echo "
";
  echo "" . $row['firstname'] . "	";
  echo "" . $row['lastname'] . "	";
  echo "" . $row['middlename'] . "	";
  echo " <input type='button' value='Delete' 	";
  echo "
";
}
mysqli_close($con);
echo '
';
?>

I did some editing in my index.php. I put the submit button outside the form tag and the html table appears but the problem now is there is no data inserted to the database.So how am i going to make the html table appear and at the same time insert data to the database when i click the submit button.??

A: // example 1 GET
$(document).ready(function(){
  $("#submitButt").click(function(e){    // u should give a id to the button.
    e.preventDefault();    // this is to prevent the form submit by it self

    // using ajax to submit
    $("#div1").load("insert.php",
        $(this.form).serialize();    // this will use GET to submit data
    );
  });
});

// example 2 POST
$(document).ready(function(){
  $("#submitButt").click(function(e){    // u should give a id to the button.
    e.preventDefault();    // this is to prevent the form submit by it self

    // using ajax to submit
    $("#div1").load("insert.php",
        $(this.form).serializeArray();    // this will use POST to submit data
    );
  });
});

http://jsfiddle.net/9kcek/

use Tamper Data to check the request when u click the submit button.

A: If you press submit, then you will be redirected to insert.php. Hence, your click event will never be executed. You must prevent the redirect first in order for you to load your data.
Furthermore, you will need to switch the way in which your data is posted. As you want to directly insert the table on the current page, you should switch to an ajax approach. Your data will be sent to your insert.php in the background via $.ajax and then you can load your #div1 on success with the content of table.php.


text:
Q: Clicking a tag in div dropdown in Selenium Python, nothing is working I am trying to click an a tag inside a div dropdown. I have tried 4 code options and nothing works. I know the XPATH is right. I have implicit sleep on.
1.)              browser.find_element_by_xpath(OrderOrderTypeXPATH).send_keys('/n')
2.)
browser.execute_script('arguments[0].click()',
browser.find_element_by_xpath(OrderTypeXPATH))

3.)
ActionChains(browser).move_to_element(browser.find_element_by_xpath(OrderTypeXPATH)).click().perform()

4.)
browser.find_element_by_xpath(OrderTypeXPATH).click()

My div code looks like this:

    Order 1
    Order 2
    Order 3
    Order 4

There is no error messages. Just doesn't click it and the dropdown just disappears.
XPATH is right because sendKeys('\n') outputs an outline.

A: Induce WebDriverWait  and element_to_be_clickable() and click the div element first and then click the desire element like below.
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div.dropdown"))).click()
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='dropdown']/a[text()='Order 2']"))).click()

Note: You need to import followings.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Edited:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver=webdriver.Chrome()
driver.get("https://robinhood.com/stocks/AMD")
driver.maximize_window()
element=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//h3[contains(.,'Buy AMD')]/following::*[name()='svg'][2]"))).click()
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"//h3[contains(.,'Order Type')]/following::div/a[text()='Limit Order']"))).click()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Сразу несколько значений в [ ] Учусь писать ТГ ботов на php,
такой вопрос у меня ответ на сообщение записан как $DelegateMessage
и каждое последующее слово будет как $DelegateMessage[1]...$DelegateMessage[100]
Как мне сделать так что бы в одном $DelegateMessage[вот тут] было сразу несколько значений
тобишь от 1 до 50, что бы не прописывать все в ручную


text:
Q: Openshift not forwarding packets to pod I'm trying to setup a pod which receives packets for port 1234 coming from external hosts. I confirmed via tcpdump that the packets are indeed arriving at the openshift cluster. Now, I have pod AAAA running already which supposed to get the packets for port 1234 (routed or forwarded from the openshift master). We already have assigned an IP for the pod so the docs below has been followed thoroughly to setup the externalIP, ports, etc. I suspect the issue is with the master-config but I cant paste them here.
My question is what are the configs necessary to be put in place in the master-config in order to route port 1234 packets to pod AAAA.
Tried already below Openshift docs:

*

*https://docs.openshift.com/container-platform/3.3/admin_guide/tcp_ingress_external_ports.html

*https://docs.openshift.com/container-platform/3.3/dev_guide/getting_traffic_into_cluster.html#using-ingress-IP-self-service

A: First of all - You are only referring to a POD. I would recommend to deploy your app as a Deployment rather. Please refer to this and this.
Additionally, in order to expose Deployments to the outside world in Kubernetes you have to establish a Service. It can expose your app in a few different ways. Please read through this for the details.
If you using any standard app you can usually find an example deployment/service by googling the name of the app and 'kubernetes'.

A: In your master config (etc/origin/master/master-config.yaml), just add
servicesNodePortRange: "1234-1234"
kubernetesMasterConfig:
  apiServerArguments:
  controllerArguments:
  masterCount: 1
  masterIP: x.x.x.x
  podEvictionTimeout:
  proxyClientInfo:
    certFile: master.proxy-client.crt
    keyFile: master.proxy-client.key
  schedulerArguments:
  schedulerConfigFile: /etc/origin/master/scheduler.json
  servicesNodePortRange: "1234-1234"
  servicesSubnet: 172.30.0.0/16
  staticNodeNames: []

After that, restart atomic-openshift-master service.
Then, create a second service for your deployment with a load balancer type. Assuming your deployment config name is "myapp", create new file similar below,
--- "new-svc.yml" ----
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: myapp
    template: myapp-template
  name: myapp-ext
spec:
  ports:
  - name: myapp
    nodePort: 1234
    port: 1234
    protocol: TCP
    targetPort: 1234
  selector:
    name: myapp
  sessionAffinity: None
  type: LoadBalancer

After that, create a new service
#oc create -f new-svc.yml

Finally, expose the new service "myapp-ext" by adding route (1234 <-- 1234).


text:
Q: Ios Adobe Creative Sdk Customization I have successfully integrated Adobe Creative SDK (Image Editor) in my iOS application.And now I wanted to add my own features to this editor such as i want to add my own stickers into the sticker header.I have explored but found nothing.My code is
@IBAction func btnBrowseAction(_ sender: UIButton) {
    let editorController = AdobeUXImageEditorViewController (image:  UIImage (named: "3_1_Greeting_Screen_Landscap_1.jpg")!)
    let editorCustomzation =        AdobeImageEditorCustomization.setToolOrder([_kAFStickers(),_kAFFrames() as Any])

    self.present(editorController, animated: true, completion: nil)

    editorController.delegate = self
}

func photoEditor(_ editor: AdobeUXImageEditorViewController,  finishedWith image: UIImage?) {

    self.dismiss(animated: true, completion: nil)
    imageVieww.image = image
}

func photoEditorCanceled(_ editor: AdobeUXImageEditorViewController) {
    self.dismiss(animated: true, completion: nil)
}

Is there any way to do this? please suggest me.


text:
Q: Show/hide clear icon inside input field not working properly I have created an input with an icon that clears the input text.
I initially have it set to display:none.
When you focus on the input, the clear icon appears which is what I want, but when you click the clear icon it disappears and does not clear the input text, but then only reappears when you focus on the input again, which I dont want it to do this, as it should stay visible only until you click out of the input, then it should hide...
So the use case should be:

*

*the clear icon should initially be set to hidden (in css or can be jQuery)

*the clear icon should show when you focus on input

*the clear icon should hide again, when you click out of the input

My script is not working properly, and I have tried a number of ways to work it out myself but nope, cant figure it out.

$("input")
  .focus(function() {
    $(this).attr("placeholder", "enter your email address...");
    $(".material-icons").show();
  })
  .blur(function() {
    $(".material-icons").hide();
    $(this).attr("placeholder", "input here");
    $(".clear-input").click(function() {
      $(this).prev().val("").focus();
    });
  });
html {
  box-sizing: border-box;
}

form {
  margin: 20vh;
}

.container {
  border: none;
  width: 248px;
  position: relative;
}

input {
  border: 1px solid pink;
  box-shadow: none;
  padding: 8px 100px 8px 5px;
  position: relative;
}

input:hover {
  border: 1px solid #222;
}

input:focus {
  border: 1px solid blue;
}

.material-icons {
  position: absolute;
  right: 0px;
  top: 0px;
  margin: auto;
  font-size: 3px;
  cursor: pointer;
  color: #aaa;
  padding: 8px;
  display: none;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<form>

    <input class="type-here" type="text" placeholder="input here" />
    clear

</form>

A: Just change click to mousedown because blur fires sooner than click event and deletes the click event and put click event in focus event.

$(document).ready(function(){
  $(".material-icons").hide();
  $("input")
  .focus(function() {
    $(this).attr("placeholder", "enter your email address...");
    $(".material-icons").show();
    $(".clear-input").mousedown(function(e) {
      e.preventDefault();
      $(this).prev().val("");
    });
  })
  .blur(function() {
    $(".material-icons").hide();
    $(this).attr("placeholder", "input here");
  });
});
html {
  box-sizing: border-box;
}

form {
  margin: 20vh;
}

.container {
  border: none;
  width: 248px;
  position: relative;
}

input {
  border: 1px solid pink;
  box-shadow: none;
  padding: 8px 100px 8px 5px;
  position: relative;
}

input:hover {
  border: 1px solid #222;
}

input:focus {
  border: 1px solid blue;
}

.material-icons {
  position: absolute;
  right: 0px;
  top: 0px;
  margin: auto;
  font-size: 3px;
  cursor: pointer;
  color: #aaa;
  padding: 8px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<form>

    <input class="type-here" type="text" placeholder="input here" />
    clear

</form>

A: Here's a somewhat inelegant solution:
$("input").focus(function() {
    $(this).attr("placeholder", "enter your email address...");
    $(".material-icons").show();
});

$('body').click(function(e){
   if ( !$(e.target).is('input') && !$(e.target).is('.material-icons') ) {
     $(".material-icons").hide();
   }
});

$('.clear-input').click(function(){
  $('input').val('')
});

http://jsfiddle.net/7ju9hqpt/44/


text:
Q: Prove that $f_n(x)=\frac{1-(x/b)^n}{1+(a/x)^n}$ is uniformly convergent on the interval $[a+\epsilon ; b - \epsilon]$ Title says it all; I have to prove that the function sequence $f_n(x)=\dfrac{1-(x/b)^n}{1+(a/x)^n}$ is uniformly convergent on the interval $[a+\epsilon ; b - \epsilon]$, with $0<\epsilon<(b-a)/2$ - I've already shown that the sequence is pointwise convergent on $f(x)=1$, and intuitively it's pretty obvious, that for a high enough $N \in \mathbb{N}$ that $\sup\{|f_n(x)-1|\}<\epsilon$ for $n \geq N$ - but I am having trouble actually proving it, that is writing down a proper proof of it. Any hints?
Much appreciated

A: For all $x \in [a - \epsilon, b + \epsilon]$,
$$|f_n(x) - 1| = \frac{(a/x)^n + (x/b)^n}{1 + (a/x)^n} \le (a/x)^n + (x/b)^n \le \left(\frac{a}{a + \epsilon}\right)^n + \left(\frac{b - \epsilon}{b}\right)^n.$$
Thus
$$\sup_{x\in [a-\epsilon,b+\epsilon]} |f_n(x) - 1| \le \left(\frac{a}{a+\epsilon}\right)^n + \left(\frac{b-\epsilon}{b}\right)^n.$$
Now finish the argument.


text:
Q: JavaScript code works perfectly in other browsers but breaks AngularJS in ie11? I'm using this nice directive that replicates jQuery's slideToggle in AngularJS, I've found it does not work in IE11. No errors, the code just doesn't work when you open the fiddle in IE11. Any ideas of how to 'fix' it so that it works in IE11?
http://jsfiddle.net/rh7z7w0a/2/
angular.module('angularSlideables', [])
 .directive('slider', function () {
    return {
        restrict:'A',
        compile: function (element) {
            // wrap tag
            var contents = element.html();
            element.html('
' + contents + '
');

            return function postLink(scope, element, attrs) {
                var i = 0;
                // default properties
                scope.$watch(attrs.slider, (n, o) => {
                    if (n !== o) {
                        i++;
                        var target = element[0],
                            content = target.querySelector('.slideable_content');
                        if(n) {
                            content.style.border = '1px solid rgba(0,0,0,0)';
                            var y = content.clientHeight, z = i;
                            content.style.border = 0;
                            target.style.height = y + 'px';
                            setTimeout(() => {
                                if (z === i) {
                                    target.style.height = 'auto';
                                }
                            }, 500);
                        } else {
                            target.style.height = target.clientHeight + 'px';
                            setTimeout(() => {
                                target.style.height = '0px';
                            });
                        }
                    }
                });

                attrs.duration = (!attrs.duration) ? '0.5s' : attrs.duration;
                attrs.easing = (!attrs.easing) ? 'ease-in-out' : attrs.easing;
                element.css({
                    'overflow': 'hidden',
                    'height': '0px',
                    'transitionProperty': 'height',
                    'transitionDuration': attrs.duration,
                    'transitionTimingFunction': attrs.easing
                });
            };
        }
    };
});

The problem seems to be to do with this section:
scope.$watch(attrs.slider, (n, o) => {

A: Arrow functions are not supported in IE11, so (n, o) => is considered invalid syntax by IE11. You should be able to use a normal anonymous function instead, like this:
scope.$watch(attrs.slider, function(n, o) {
    ...
});

Bear in mind that this behaves differently in anonymous functions than it does to arrow functions. In your case, that isn't a problem, but it's worth reading the MDN documentation on arrow functions to know the differences.
You might also want to consider a transpiler such as Babel if you want to use all of the latest ES6 features without breaking compatibility for older browsers. Babel can convert newer code into the equivalent ES5 which is supported by nearly all browsers created within the last few years.

A: Arrow functions are being introduced with ES6 which is not yet compatible with many browsers and will not be anytime soon. You should use the old javascript syntax till ES6 is fully supported in all browsers.
Or, you can use Babel Compiler. It will convert your ES6 code to ES5.


text:
Q: How to search for files in a record on python? I am writing a program where students are written onto a file and can be search when inputted their specific data. However I am not sure if the search_record method in my script is right. It can sometimes return the right results but also on other times when inputted different data it doesn't work.
TA = Teacher advisor
Here is my current program:
def read_record():
    in_file = open("student.txt", "r")

    stud_num = in_file.readline()

    while stud_num != "":
        last_name = in_file.readline
        first_name = in_file.readline
        TA = in_file.readline()

        stud_num = stud_num.rstrip("\n")
        last_name = last_name.rstrip("\n")
        first_name = first_name.rstrip("\n")
        TA = TA.rstrip("\n")

        print "Student number: ", stud_num
        print "Last name: ", last_name
        print "First name: ", first_name
        print "TA: ", TA
        print

        stud_num = in_file.readline()

    in_file.close()

def write_record():
    num_students = input("Enter number of students: ")

    out_file = open("student.txt" , "w")

    for counter in range (1, num_students + 1):
        stud_num = raw_input("Enter student number: ")
        last_name = raw_input("Enter last name: ")
        first_name = raw_input("Enter first name: ")
        TA = raw_input("Enter TA: ")

        out_file.write(stud_num +"\n")
        out_file.write(last_name +"\n")
        out_file.write(first_name +"\n")
        out_file.write(TA + "\n")

    out_file.close()

def menu():
    print "STUDENT MENU"
    print "============="
    print "A. Create student file"
    print "B. Display student file"
    print "C. Add student file"
    print "D. Search records"
    print
    choice = raw_input("Enter your choice: ")

    return choice

def add_record():
    out_file = open("student.txt", "a")

    another = "Y"

    while another == "Y":
        stud_num = raw_input("Enter student number: ")
        last_name = raw_input("Enter last name: ")
        first_name = raw_input("Enter first name: ")
        TA = raw_input("Enter TA: ")
        print

        out_file.write(stud_num + "\n")
        out_file.write(last_name + "\n")
        out_file.write(first_name + "\n")
        out_file.write(TA + "\n")

        another = raw_input("Do you want to enter another student (Y or N): ")

    out_file.close()

def search_record():
    in_file = open("student.txt", "r")

    found = False

    print "RECORD MENU"
    print "============="
    print "A. Search student number"
    print "B. Search student last name"
    print "C. Search student name"
    print "D. Search student TA"
    print

    choice = raw_input("Enter your choice: ")

    if choice == "A":
        search = raw_input("Enter a student number: ")
        stud_num = in_file.readline()

        while stud_num != "":
            last_name = in_file.readline()
            first_name = in_file.readline()
            TA = in_file.readline()

            stud_num = stud_num.rstrip("\n")
            last_name = last_name.rstrip("\n")
            first_name = first_name.rstrip("\n")
            TA = TA.rstrip("\n")

            if search == stud_num:
                print "Student number: ", stud_num
                print "Last name: ", last_name
                print "First name: ", first_name
                print "TA: ", TA
                print
                found = True

            stud_num = in_file.readline()

    elif choice == "B":
        search = raw_input("Enter a student last name: ")
        last_name = in_file.readline(2)

        while last_name != "":
            stud_num = in_file.readline()
            first_name = in_file.readline()
            TA = in_file.readline()

            stud_num = stud_num.rstrip("\n")
            last_name = last_name.rstrip("\n")
            first_name = first_name.rstrip("\n")
            TA = TA.rstrip("\n")

            if search == last_name:
                print "Student number: ", stud_num
                print "Last name: ", last_name
                print "First name: ", first_name
                print "TA: ", TA
                print
                found = True

            last_name = in_file.readline()

    elif choice == "C":
        search = raw_input("Enter a student name: ")
        first_name = in_file.readline(3)

        while first_name != "":
            stud_num = in_file.readline()
            last_name = in_file.readline()
            TA = in_file.readline()

            stud_num = stud_num.rstrip("\n")
            last_name = last_name.rstrip("\n")
            first_name = first_name.rstrip("\n")
            TA = TA.rstrip("\n")

            first_name = in_file.readline()

            if search == first_name:
                print "Student number: ", stud_num
                print "Last name: ", last_name
                print "First name: ", first_name
                print "TA: ", TA
                print
                found = True
            first_name = in_file.readline()

    elif choice == "D":
        search = raw_input("Enter a TA: ")
        TA = in_file.readline(4)

        while TA != "":
            stud_num = in_file.readline()
            last_name = in_file.readline()
            first_name = in_file.readline()

            stud_num = stud_num.rstrip("\n")
            last_name = last_name.rstrip("\n")
            first_name = first_name.rstrip("\n")
            TA = TA.rstrip("\n")

            if search == TA:
                print "Student number: ", stud_num
                print "Last name: ", last_name
                print "First name: ", first_name
                print "TA: ", TA
                print
                found = True

            TA = in_file.readline()

    else:
        print "Invalid entry"

    in_file.close()

    if not found:
        print "Student record not found"

def main():
    choice = menu()

    if choice == "A":
        write_record()
    elif choice == "B":
        read_record()
    elif choice == "C":
        add_record
    elif choice == "D":
        search_record()
    else:
        print "error"

main()

the student file I have created to test is
12345
Potter
Harry
Wong
6789
Turner
Timmy
Mack

A: first of all I want to mention that you have a lot of cut and pasted code.
Then to make your search function work.
You need to have virtually the same code running as when you search for student number..the only difference is you're asking a different prompt like for choice B Search by student last name to ask for a last name instead of student number.
and instead of comparing search == stud_num:
you compare search == last_name:...that should be the only difference.
How you loop through and reading the data should be identical to when user enter choice A...
But it's not working because you're trying to read last_name first and also you're calling readline() but with a number which specifies number of bytes to read.  that's why it's failing.


text:
Q: matlab change upper case character to lower case character in string I would like to take a string and change the first letter of that string from upper to lower case in MATLAB.  Any suggestions.
Example:
a = 'Upper';

% Do something to a

a = 'upper'

thank you in advance

A: Use lower():
a = lower(a);

If you only need to change the first letter to upper case, try the following:
a = [lower(a(1)) a(2:end)];

Check out here for more info.

A: If you want all the letters to be lower case, then
s = 'String'
lowercase(s)

gives
string

If you want only the first letter, then
s = 'STring'
[lower(s(1)) s(2:end)]

gives
sTring


text:
Q: Divide by 10 using bit shifts? Is it possible to divide an unsigned integer by 10 by using pure bit shifts, addition, subtraction and maybe multiply?  Using a processor with very limited resources and slow divide.

A: to expand Alois's answer a bit, we can expand the suggested y = (x * 205) >> 11 for a few more multiples/shifts:
y = (ms *        1) >>  3 // first error 8
y = (ms *        2) >>  4 // 8
y = (ms *        4) >>  5 // 8
y = (ms *        7) >>  6 // 19
y = (ms *       13) >>  7 // 69
y = (ms *       26) >>  8 // 69
y = (ms *       52) >>  9 // 69
y = (ms *      103) >> 10 // 179
y = (ms *      205) >> 11 // 1029
y = (ms *      410) >> 12 // 1029
y = (ms *      820) >> 13 // 1029
y = (ms *     1639) >> 14 // 2739
y = (ms *     3277) >> 15 // 16389
y = (ms *     6554) >> 16 // 16389
y = (ms *    13108) >> 17 // 16389
y = (ms *    26215) >> 18 // 43699
y = (ms *    52429) >> 19 // 262149
y = (ms *   104858) >> 20 // 262149
y = (ms *   209716) >> 21 // 262149
y = (ms *   419431) >> 22 // 699059
y = (ms *   838861) >> 23 // 4194309
y = (ms *  1677722) >> 24 // 4194309
y = (ms *  3355444) >> 25 // 4194309
y = (ms *  6710887) >> 26 // 11184819
y = (ms * 13421773) >> 27 // 67108869

each line is a single, independent, calculation, and you'll see your first "error"/incorrect result at the value shown in the comment.  you're generally better off taking the smallest shift for a given error value as this will minimise the extra bits needed to store the intermediate value in the calculation, e.g. (x * 13) >> 7 is "better" than (x * 52) >> 9 as it needs two less bits of overhead, while both start to give wrong answers above 68.
if you want to calculate more of these, the following (Python) code can be used:
def mul_from_shift(shift):
    mid = 2**shift + 5.
    return int(round(mid / 10.))

and I did the obvious thing for calculating when this approximation starts to go wrong with:
def first_err(mul, shift):
    i = 1
    while True:
        y = (i * mul) >> shift
        if y != i // 10:
            return i
        i += 1

(note that // is used for "integer" division, i.e. it truncates/rounds towards zero)
the reason for the "3/1" pattern in errors (i.e. 8 repeats 3 times followed by 9) seems to be due to the change in bases, i.e. log2(10) is ~3.32.  if we plot the errors we get the following:

where the relative error is given by: mul_from_shift(shift) / (1<<shift) - 0.1

A: Editor's note: this is not actually what compilers do, and gives the wrong answer for large positive integers ending with 9, starting with div10(1073741829) = 107374183 not 107374182.  It is exact for smaller inputs, though, which may be sufficient for some uses.
Compilers (including MSVC) do use fixed-point multiplicative inverses for constant divisors, but they use a different magic constant and shift on the high-half result to get an exact result for all possible inputs, matching what the C abstract machine requires.  See Granlund & Montgomery's paper on the algorithm.
See Why does GCC use multiplication by a strange number in implementing integer division? for examples of the actual x86 asm gcc, clang, MSVC, ICC, and other modern compilers make.

This is a fast approximation that's inexact for large inputs
It's even faster than the exact division via multiply + right-shift that compilers use.
You can use the high half of a multiply result for divisions by small integral constants. Assume a 32-bit machine (code can be adjusted accordingly):
int32_t div10(int32_t dividend)
{
    int64_t invDivisor = 0x1999999A;
    return (int32_t) ((invDivisor * dividend) >> 32);
}

What's going here is that we're multiplying by a close approximation of 1/10 * 2^32 and then removing the 2^32. This approach can be adapted to different divisors and different bit widths.
This works great for the ia32 architecture, since its IMUL instruction will put the 64-bit product into edx:eax, and the edx value will be the wanted value. Viz (assuming dividend is passed in eax and quotient returned in eax)
div10 proc
    mov    edx,1999999Ah    ; load 1/10 * 2^32
    imul   eax              ; edx:eax = dividend / 10 * 2 ^32
    mov    eax,edx          ; eax = dividend / 10
    ret
    endp

Even on a machine with a slow multiply instruction, this will be faster than a software or even hardware divide.

A: Though the answers given so far match the actual question, they do not match the title. So here's a solution heavily inspired by Hacker's Delight that really uses only bit shifts.
unsigned divu10(unsigned n) {
    unsigned q, r;
    q = (n >> 1) + (n >> 2);
    q = q + (q >> 4);
    q = q + (q >> 8);
    q = q + (q >> 16);
    q = q >> 3;
    r = n - (((q << 2) + q) << 1);
    return q + (r > 9);
}

I think that this is the best solution for architectures that lack a multiply instruction.

A: Considering Kuba Ober's response, there is another one in the same vein.
It uses iterative approximation of the result, but I wouldn't expect any surprising performances.
Let say we have to find x where x = v / 10.
We'll use the inverse operation v = x * 10 because it has the nice property that when x = a + b, then x * 10 = a * 10 + b * 10.
Let use x as variable holding the best approximation of result so far. When the search ends, x Will hold the result. We'll set each bit b of x from the most significant to the less significant, one by one, end compare (x + b) * 10 with v. If its smaller or equal to v, then the bit b is set in x. To test the next bit, we simply shift b one position to the right (divide by two).
We can avoid the multiplication by 10 by holding x * 10 and b * 10 in other variables.
This yields the following algorithm to divide v by 10.
uin16_t x = 0, x10 = 0, b = 0x1000, b10 = 0xA000;
while (b != 0) {
    uint16_t t = x10 + b10;
    if (t <= v) {
        x10 = t;
        x |= b;
    }
    b10 >>= 1;
    b >>= 1;
}
// x = v / 10

Edit:  to get the algorithm of Kuba Ober which avoids the need of variable x10 , we can subtract b10 from v and v10 instead. In this case x10 isn't needed anymore. The algorithm becomes
uin16_t x = 0, b = 0x1000, b10 = 0xA000;
while (b != 0) {
    if (b10 <= v) {
        v -= b10;
        x |= b;
    }
    b10 >>= 1;
    b >>= 1;
}
// x = v / 10

The loop may be unwinded and the different values of b and b10 may be precomputed as constants.

A: On architectures that can only shift one place at a time, a series of explicit comparisons against decreasing powers of two multiplied by 10 might work better than the solution form hacker's delight. Assuming a 16 bit dividend:
uint16_t div10(uint16_t dividend) {
  uint16_t quotient = 0;
  #define div10_step(n) \
    do { if (dividend >= (n*10)) { quotient += n; dividend -= n*10; } } while (0)
  div10_step(0x1000);
  div10_step(0x0800);
  div10_step(0x0400);
  div10_step(0x0200);
  div10_step(0x0100);
  div10_step(0x0080);
  div10_step(0x0040);
  div10_step(0x0020);
  div10_step(0x0010);
  div10_step(0x0008);
  div10_step(0x0004);
  div10_step(0x0002);
  div10_step(0x0001);
  #undef div10_step
  if (dividend >= 5) ++quotient; // round the result (optional)
  return quotient;
}

A: Of course you can if you can live with some loss in precision. If you know the value range of your input values you can come up with a bit shift and a multiplication which is exact.
Some examples how you can divide by 10, 60, ... like it is described in this blog to format time the fastest way possible.
temp = (ms * 205) >> 11;  // 205/2048 is nearly the same as /10

A: Well division is subtraction, so yes.  Shift right by 1 (divide by 2).  Now subtract 5 from the result, counting the number of times you do the subtraction until the value is less than 5.  The result is number of subtractions you did.  Oh, and dividing is probably going to be faster.
A hybrid strategy of shift right then divide by 5 using the normal division might get you a performance improvement if the logic in the divider doesn't already do this for you.

A: I've designed a new method in AVR assembly, with lsr/ror and sub/sbc only. It divides by 8, then sutracts the number divided by 64 and 128, then subtracts the 1,024th and the 2,048th, and so on and so on. Works very reliable (includes exact rounding) and quick (370 microseconds at 1 MHz).
The source code is here for 16-bit-numbers:
http://www.avr-asm-tutorial.net/avr_en/beginner/DIV10/div10_16rd.asm
The page that comments this source code is here:
http://www.avr-asm-tutorial.net/avr_en/beginner/DIV10/DIV10.html
I hope that it helps, even though the question is ten years old.
brgs, gsc

A: elemakil's comments' code can be found here: https://doc.lagout.org/security/Hackers%20Delight.pdf
page 233. "Unsigned divide by 10 [and 11.]"


text:
Q: How run glue job locally? I have setup project as described here. But code:
import com.amazonaws.services.glue.{AWSGlueClientBuilder, GlueContext}
import org.apache.spark.SparkContext
import org.slf4j.LoggerFactory

object MyGlueJob {
  private val logger = LoggerFactory.getLogger(getClass)
  def main(sysArgs: Array[String]) {

    val spark: SparkContext = SparkContext.getOrCreate()
    val glueContext: GlueContext = new GlueContext(spark)
    val awsGlueClient = AWSGlueClientBuilder.defaultClient
  }
}

fails with error:
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
19/11/21 15:40:32 INFO SparkContext: Running Spark version 2.4.3
19/11/21 15:40:33 ERROR SparkContext: Error initializing SparkContext.
org.apache.spark.SparkException: A master URL must be set in your configuration
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:368)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:117)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2544)
    at MyGlueJob$.main(MyGlueJob.scala:13)
    at MyGlueJob.main(MyGlueJob.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)
19/11/21 15:40:33 ERROR Utils: Uncaught exception in thread main
java.lang.NullPointerException
    at org.apache.spark.SparkContext.org$apache$spark$SparkContext$$postApplicationEnd(SparkContext.scala:2416)
    at org.apache.spark.SparkContext$$anonfun$stop$1.apply$mcV$sp(SparkContext.scala:1931)
    at org.apache.spark.util.Utils$.tryLogNonFatalError(Utils.scala:1340)
    at org.apache.spark.SparkContext.stop(SparkContext.scala:1930)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:585)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:117)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2544)
    at MyGlueJob$.main(MyGlueJob.scala:13)
    at MyGlueJob.main(MyGlueJob.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)
19/11/21 15:40:33 INFO SparkContext: Successfully stopped SparkContext
Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:66)
Caused by: org.apache.spark.SparkException: A master URL must be set in your configuration
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:368)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:117)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2544)
    at MyGlueJob$.main(MyGlueJob.scala:13)
    at MyGlueJob.main(MyGlueJob.scala)
    ... 5 more

It is obvious that master url should be set but how to this from commandline or system variables? (E.g. without touching the code)
Also I have [read] that --master argument can fix problem, but adding it to args do nothing (here is Intellij Idea run configuration):

The key question is to run glue job locally and be able to run it in aws without code touching, is it possible?

A: You can created a spark session explicitly and set any parameters you want. But I cannot say that this will work eventually in Glue. The following is a local session that I use to test Spark jobs locally even though I do run them eventually in Glue. I test only pure spark code.
  lazy val spark: SparkSession = {
    UserGroupInformation.setLoginUser(UserGroupInformation.createRemoteUser("hduser"))
    SparkSession
      .builder()
      .master("local")
      .appName("spark unit test")
      .getOrCreate()
  }

The key question is to run glue job locally and be able to run it in aws without code touching, is it possible?

It's possible to run any code with a dev endpoint and Zeppelin. See aws docs.


text:
Q: Unable to query all history/count data with Hyperledger fabric v1.0.0 chaincode I have a problem in my chaincode as I am unable to query all data(past records) and display out.
What I was hoping to do was to add a counter if the same uniqueID variable is keyed in.
With the counter, adding with the uniqueID value i can get the right query.
Currently, I could get singular entry data from the blockchain when i ran this command:
peer chaincode query -C food -n food_ccv01 -c '{"Args":["queryFoodInfo","1","123456789"]}'

Using the "123456789" as a unique ID and "1" as the counter, combining them gives me a unique entry
However I am unable to use this "123456789"+counter to pull ALL data that was previously entered into the blockchain.
How can i go about this? or is there a better way?
i am not sure why my counter could not be initialized as a integer, i am using a string for now...
This is my chaincode.

A: I do not think you need to append your key with a counter, instead you can simply continue to update same key and to query for all updates since ever you can use following API:
// GetHistoryForKey returns a history of key values across time.
// For each historic key update, the historic value and associated
// transaction id and timestamp are returned. The timestamp is the
// timestamp provided by the client in the proposal header.
// GetHistoryForKey requires peer configuration
// core.ledger.history.enableHistoryDatabase to be true.
// The query is NOT re-executed during validation phase, phantom reads are
// not detected. That is, other committed transactions may have updated
// the key concurrently, impacting the result set, and this would not be
// detected at validation/commit time. Applications susceptible to this
// should therefore not use GetHistoryForKey as part of transactions that
// update ledger, and should limit use to read-only chaincode operations.
GetHistoryForKey(key string) (HistoryQueryIteratorInterface, error)

E.g. something along these lines should do a work for you:
func queryFoodFullInfo(stub shim.ChaincodeStubInterface, args []string) pb.Response {
    fmt.Println("Entering Query Food information")

    // Assuming food key is at zero index
    historyIer, err := stub.GetHistoryForKey(args[0])

    if err != nil {
        errMsg := fmt.Sprintf("[ERROR] cannot retrieve history of food record with id <%s>, due to %s", args[0], err)
        fmt.Println(errMsg)
        return shim.Error(errMsg)
    }

    result := make([]FavouritefoodInfo, 0)
    for historyIer.HasNext() {
        modification, err := historyIer.Next()
        if err != nil {
            errMsg := fmt.Sprintf("[ERROR] cannot read food record modification, id <%s>, due to %s", args[0], err)
            fmt.Println(errMsg)
            return shim.Error(errMsg)
        }
        var food FavouritefoodInfo
        json.Unmarshal(modification.Value, &food)
        result = append(result, food)
    }

    outputAsBytes, _ := json.Marshal(&result)
    return shim.Success(outputAsBytes)
 }

Following your initial path you probably would like to explore the range query capabilities:
// GetStateByRange returns a range iterator over a set of keys in the
// ledger. The iterator can be used to iterate over all keys
// between the startKey (inclusive) and endKey (exclusive).
// The keys are returned by the iterator in lexical order. Note
// that startKey and endKey can be empty string, which implies unbounded range
// query on start or end.
// Call Close() on the returned StateQueryIteratorInterface object when done.
// The query is re-executed during validation phase to ensure result set
// has not changed since transaction endorsement (phantom reads detected).
GetStateByRange(startKey, endKey string) (StateQueryIteratorInterface, error)

See marbles example.


text:
Q: What is the difference between on_press and on_release in kivy python I need to know what is the difference between on_press and on_release in kivy and python button

A: on_press triggers only when you press the button. On the other hand, on_release fires only when you release the button. This link from the docs that was sent in the comments should help: https://kivy.org/doc/stable/api-kivy.uix.behaviors.button.html


text:
Q: Getting specific node from children props React I'm quite new to React. Is there a way to get a specific node from an array of children props. So I have a component that accepts children. <CustomComponent> {children} </CustomComponent. Children property is an array of elements with a lot of child nodes.
<div> <h1> Title </h1> <p> Paragraph </p> <span> Text </span> <button> Text </button> </div>

Is there a way for CustomComponent to get only the <h1> tag using React.Children?

A: If possible, you can attach refs to child elements you want to fetch. So that you can do that :
this.props.children.refs['yourRefKey']

A: If I understand your question, this is doable by using the refs attribute and then accessing it later.
<input type="text" ref="myinput">
then
this.refs.yourref


text:
Q: Replace URL with different string I try to replace all my URL with another into my mariadb database (10.3.31)
URL's Example :
https://website.com/download/8fd4g8er4ger5f84/filename.zip
https://website.com/download/fggf4hf5gh4/filename.zip
https://website.com/download/1v8t77hth/filename.zip
https://website.com/download/fgh48rt4g/filename.zip

I want to replace : https://website.com/download/8fd4g8er4ger5f84 (< this using different hash folder name)
with my new URL : https://newurl.com/download/filename.zip
I used "update / replace" SQL command in the past, but I don't know how to do with unique hash name folder like above
Help me please?

EDIT : Found it
Found it :
UPDATE table_name SET column_name = REGEXP_REPLACE(column_name, 'website.com/download/(.*?)/', 'NEWwebsite.com/download/')

A: Use Regex in this case
UPDATE table_name SET column_name = REGEXP_REPLACE(column_name, 'website.com/download/(.*?)/', 'newUrl.com/download/');


text:
Q: IntegrityError: The row in table 'main_post' with primary key '2' has an invalid foreign key: main_post.author_id cointains a value '1' After makemigrations, then migrate I got this error
IntegrityError: The row in table 'main_post' with primary key '2' has an invalid foreign key: main_post.author_id cointains a value '1' that does not have a corresponding value in auth_user.id
I try some solutions in similar question but it doesnot work
My models.py
User = get_user_model()

class PostView(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
    post = models.ForeignKey('Post', on_delete=models.CASCADE, blank=True)

    def __str__(self):
        return self.user.username

class Comment(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    content = models.TextField()
    post = models.ForeignKey('Post', related_name='comments', on_delete=models.CASCADE)

    def __str__(self):
        return self.user.username

class Author(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    profile_picture = models.ImageField()

    def __str__(self):
        return  self.user.username

class Category(models.Model):
    title = models.CharField(max_length=40)

    def __str__(self):
        return self.title

class Post(models.Model):
    title = models.CharField(max_length=100)
    overview = models.TextField()
    detail = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    content = RichTextUploadingField(config_name='post_ckeditor')
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    thumbnail = models.ImageField()
    categories = models.ManyToManyField(Category)
    featured = models.BooleanField()
    previous_post = models.ForeignKey('self', related_name='previous', on_delete=models.SET_NULL, blank = True, null = True)
    next_post = models.ForeignKey('self', related_name='next', on_delete=models.SET_NULL, blank = True, null = True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={
            'id': self.id
            })

    def get_update_url(self):
        return reverse('post-update', kwargs={
            'id': self.id
            })

    def get_delete_url(self):
        return reverse('post-delete', kwargs={
            'id': self.id
            })

    @property
    def get_comments(self):
        return self.comments.all().order_by('-timestamp')

    @property
    def view_count(self):
        return PostView.objects.filter(post=self).count()

    @property
    def comment_count(self):
        return Comment.objects.filter(post=self).count()

My views.py
#Some code not include in this

def post(request, id):
    most_recent = Post.objects.order_by('-timestamp')[:3]
    category_count = get_category_count()
    post = get_object_or_404(Post, id=id)
    PostView.objects.get_or_create(user=request.user, post=post)
    form = CommentForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            form.instance.user = request.user
            form.instance.post = post
            form.save()
            return redirect(reverse('post-detail', kwargs={
                'id':post.id
                }))
    context = {
        'form': form,
        'post': post,
        'category_count':get_category_count,
        'most_recent': most_recent,
    }
    return render(request, 'post.html', context)


text:
Q: The universal windows app designer doesn't appear? I am new to Windows development in general and I am facing a problem that doesn't appear in any of my search results.
The problem is the designer of the universal windows app disappeared - became transparent except only the borders of the virtual device, when I was trying to change the theme of the application.
I think this screenshot will explain the problem better than me:

Does any one encounter this same problem and have solved it?


text:
Q: Getting User From Within Python Script What is a "pythonic" way to determine which user ran a python script from within the script?
For instance, I know that you can run shell commands from within the script to do an
echo $USER

but is there a more standard python way of determining which user is running the script?
Like a get_user() command for a standard library?

A: As noted in my comment, the answer is given here: https://stackoverflow.com/a/842096/2531279
Note: this is available for Windows and Unix

A: Wouldn't it depend on what OS you are running the script on? Running shell commands is more common on some flavor of Linux but it could be a windows or Mac machine. Python may have a way of doing that cross platform, i'm not sure.


text:
Q: Desktop Environment is a custom OS If I write an OS using c, how would I make the desktop? Could I implement Java, or is there a way to do this is the C programming language? I've never done anything with any sort of graphics in C. Does anybody know the answer, much less a tutorial or a way to get started and learn how to write the desktop environment?

A: The Gnome desktop on Linux is written in C (mostly).
But if you write an OS, the desktop is not your priority; getting right important things like processes, scheduling, threads, drivers, protection, authentification, .... is more important, and time consuming.
Don't confuse the desktop environment with the operating system. Most computers (probably the Web server at stackoverflow providing you this very answer, running in some datacenter) don't have any desktop environments. They do have an OS.
About OSes, read Operating Systems: Three Easy Pieces. You probably are writing some kernel, so look into osdev.org for guidance.
About desktop environments, they are specific to the display server provided and used by your OS. On my Linux box in 2019, that server is Xorg (but maybe you are using Wayland), and the rules related to desktop environments include ICCCM & EWMH. And GNOME  (and also Xorg) is running in user-mode and user space.


text:
Q: XML PATH Concatenate Syntax I use a nested query to concatenate row data for an aggregate.  The syntax I use within the nested query is
for XML PATH ('')

Can someone explain what is supposed to go between the quotes above?  I did some tests and it looks like it just encloses my row data in start and ending HTML like tags.

A: I'm not 100% sure what you mean, but if your query is similar to the following then that might help you:
SELECT    R.RegionID  AS [@RID],
          R.Enabled   AS [@Enabled],
          (
          SELECT      ST.TypeID  AS [@TID],
                      QT.[Name] AS [@QTName],
          FROM        Type ST
          INNER JOIN  QuarryType QT ON ST.QuarryTypeID = QT.QuarryTypeID
          WHERE       R.RegionID = ST.RegionID
          FOR XML PATH ('QuarryType'), TYPE
          )
FROM      Region R
FOR XML PATH ('Region'), ELEMENTS, ROOT('root')

As you can see the text in each FOR XML PATH ('') block is nothing special, not related to the data anyway. It is used for element names in your XML output like this:
<root>
    <Region RID="123" Enabled="true">
        <QuarryType TID="4" QTName="Quarry 1"/>
        <QuarryType TID="7" QTName="Quarry 2"/>
        <QuarryType TID="9" QTName="Quarry 5"/>
    </Region>
</root>

If you need more help, just ask!

A: The empty string ('') is a special case. Your observation is correct in that whatever you put there will surround your row with open and close XML tags of whatever you put in there. For instance, if you say "for xml path ('a')", it will surround your results with <a> </a>.


text:
Q: Symfony 3 - undefined method named "getResult" /**
    * Search result information between two dates
    *
*@Route("/search/{startDate}/{endDate}/{type}", name="maintenance_search_result")
    *@Method("GET")
    */
    public function searchResultAction($startDate, $endDate, $type)
    {
      $em = $this->getDoctrine()->getManager()->getRepository('CarMaintenanceBundle:Maintenance');
      $query = $em->createQueryBuilder('c')
        ->select('c.id')
        ->addSelect('c.type')
        ->addSelect('c.date')
        ->addSelect('c.cost')
        ->addSelect('c.remark')
        ->where('c.date > :SDATE')->setParameter('SDATE', $startDate)
        ->andWhere('c.date < :EDATE')->setParameter('EDATE', $endDate);

        if ("All" != $type){
            $query->andWhere('c.type = :TYPE1')->setParameter('TYPE1', $type);
        }

        $query->orderBy('c.date', 'DESC')
          ->getQuery();

        $SearchRes = $query->getResult();

        return $this->render('maintenance/search_result.html.twig', array(
          'SearchResults'=> $SearchRes,));
}

I have the following error:

Attempted to call an undefined method named "getResult" of class
  "Doctrine\ORM\QueryBuilder".

When I write this way, there is no problem. It displays the search result.
public function searchResultAction($startDate, $endDate, $type)
    {
      $em = $this->getDoctrine()->getManager()->getRepository('CarMaintenanceBundle:Maintenance');

        if ("All" != $type){
          $query = $em->createQueryBuilder('c')
            ->select('c.id')
            ->addSelect('c.type')
            ->addSelect('c.date')
            ->addSelect('c.cost')
            ->addSelect('c.remark')
            ->where('c.date > :SDATE')->setParameter('SDATE', $startDate)
            ->andWhere('c.date < :EDATE')->setParameter('EDATE', $endDate)
            ->andWhere('c.type = :TYPE1')->setParameter('TYPE1', $type)
            ->orderBy('c.date', 'DESC')
            ->getQuery();
        } else {
          $query = $em->createQueryBuilder('c')
            ->select('c.id')
            ->addSelect('c.type')
            ->addSelect('c.date')
            ->addSelect('c.cost')
            ->addSelect('c.remark')
            ->where('c.date > :SDATE')->setParameter('SDATE', $startDate)
            ->andWhere('c.date < :EDATE')->setParameter('EDATE', $endDate)
            ->orderBy('c.date', 'DESC')
            ->getQuery();
        }
        $SearchRes = $query->getResult();
        return $this->render('maintenance/search_result.html.twig', array(
          'SearchResults'=> $SearchRes,));
    }

What is wrong with the shortest code?

A: You're not assigning the result of getQuery() anywhere:
    $query->orderBy('c.date', 'DESC')
      ->getQuery();

This is gonna do the trick:
    $query = $query->orderBy('c.date', 'DESC')
      ->getQuery();


text:
Q: CSS - floating divs align left I have 6 floating divs (align to left) on a page. These divs has 2 different widths (depending the image () ). One div has 295px and the another has 216px. The height is calculated automatically by HTML. The container has 1050px, so in one "line" of the container I can insert 3 divs, and the another 3 on the second "line".
The CSS rule is working, all divs are floating to the left, each div has 20px margin, but the problem is the alignment of them.  I want to align these divs proportional. At the moment if some pictures has different heights, on the second "line" are some blank spaces (because the height of the pictures above).
I want something to float these divs on the Y coordinate (proportional).
Look at this pictures:

A: Make a jsfiddle for people to play with.
But, you will probably want to make a container div for each row. This encapsulates the 3 inner divs, being as high as them and allowing the next container to fit nicely underneath
See my fiddle: http://jsfiddle.net/TJxmT/

A: Wouldn't a min-height at the floating divs solve the problem?

A: Try to use jQuery plugin called Masonry to fix that layout... You will be surprised!
EDIT:
You can always clear the 1st item in the row and every third item using css :
li:nth-child(3n+4) { clear:left; }

A: Have you tried putting a clear: both; on every first div of a new line?


text:
Q: Obtaining Distinct values from mongodb as list of dictionaries using pymongo I have a mongodb collection data in the following format
[{"name":"axe1","base-url":"www.example1.com","date":"2022-06-22 11:20", "ml_pred":"Invalid","hum_pred":"valid"},
 {"name":"axe2","base-url":"www.example2.com","date":"2022-06-22 12:20", "ml_pred":"Valid","hum_pred":"null"},
 {"name":"axe1","base-url":"www.example1.com","date":"2022-06-22 22:20", "ml_pred":"Invalid","hum_pred":"valid"},
 {"name":"axe3","base-url":"www.example3.com","date":"2022-06-22 02:20", "ml_pred":"Valid","hum_pred":"null"},
 {"name":"axe2","base-url":"www.example2.com","date":"2022-06-22 06:20", "ml_pred":"Invalid","hum_pred":"valid"},
 {"name":"axe1","base-url":"www.example1.com","date":"2022-06-22 14:20", "ml_pred":"Invalid","hum_pred":"null"},
 {"name":"axe1","base-url":"www.example1.com","date":"2022-06-22 10:20", "ml_pred":"Invalid","hum_pred":"invalid"},
 {"name":"axe1","base-url":"www.example1.com","date":"2022-06-22 01:20", "ml_pred":"Invalid","hum_pred":"null"}]

I am trying to get unique base-url and name as a response. For that I use pymongo distinct like below
filter_stuff = {'base-url': 1, 'name':1,'_id': 0}
data = list(crawlcol.find({},filter_stuff).distinct("base-url"))

which returned me a list of base urls. But I am expecting an output like
[{"name":"axe1","base-url":"www.example1.com"},
 {"name":"axe2","base-url":"www.example2.com"},
 {"name":"axe3","base-url":"www.example3.com"}]

How this can be obtained

A: This will give the result as required
result = list(crawlcol.aggregate(
            [
                {"$group": { "_id": { "base-url": "$base-url", "name": "$name" } } }
            ]
        ))


text:
Q: The data types float and int are incompatible in the modulo operator I can do this:
SELECT CAST(1.21 * 100 % 100 AS int)

to get the part after the decimal point.
But it won't let me do this:
DECLARE @f float;
SET @f = 1.21;
SELECT CAST(@f * 100 % 100 AS int)

I get the following error:

The data types float and int are incompatible in the modulo operator

What am I missing here?


text:
Q: Symfony 2 : Redirect a user to a page if he has a specific role I have a little question.
I want that wherever is the user on my website, if he have the role "ROLE_DEGRADE", he is redirected on a specific page.
How I can do that, I have to use firewall ?
I don't want to redirect the user to a form login, just to a simple page.
I want that everywhere on my website, without put a "if role degrade..." everywhere, in all my controllers...
Thanks for your help ;)

A: Something like this should do it ...
Create a new listener :
class AccessListener
{
    private$security;
    private $router;

    public function __construct($security, $router)
    {
        $this->security = $security;
        $this->router = $router;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        if ($this->security->isGranted('ROLE_DEGRADE')) {
           $url = $this->router->generate('<route name>');
           $event->setResponse(new RedirectResponse($url));
        }
    }
}

Add it to your services.yml :
services:
  access_listener:
    class: Acme\DemoBundle\Listener\AccessListener
    arguments: [ @security.context, @router ]
    tags:
      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Docs :

*

*Checking roles

*Event Listeners

*Generating URLs


text:
Q: TypeError: 'str' does not support the buffer interface in html2text I'm using python3 to do some web scraping. I want to save a webpage and convert it to text using the following code:
import urllib
import html2text
url='http://www.google.com'
page = urllib.request.urlopen(url)
html_content = page.read()
rendered_content = html2text.html2text(html_content)

But when I run the code, it reports a type error:
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/html2text-2016.4.2-py3.4.egg/html2text/__init__.py", line 127, in feed
    data = data.replace("</' + 'script>", "</ignore>")
TypeError: 'str' does not support the buffer interface

Could anyone tell me how to deal with this error? Thank you in advance!

A: I took the time to investigate this, and it turns out to be easily resolved.
Why You Got This Error
The problem is one of bad input: when you called page.read(), a byte string was returned, rather than a regular string.
Byte strings are Python's way of dealing with unfamiliar character encodings: basically there are characters in the raw text that don't map to Unicode (Python 3's default character encoding).
Because Python doesn't know what encoding to use, Python instead represents such strings using raw bytes - this is how all data is represented internally anyway - and lets the programmer decide what encoding to use.
Regular string methods called on these byte strings - such as replace(), which html2text tried to use - fail because byte strings don't have these methods defined.
Solution
html_content = page.read().decode('iso-8859-1')

Padraic Cunningham's solution in the comments is correct in its essence: you have to first tell Python which character encoding to use to try to map these bytes to correct character set.
Unfortunately, this particular text doesn't use Unicode, so asking it to decode using the UTF-8 encoding throws an error.
The correct encoding to use is actually contained in the request headers itself under the Content-Type header - this is a standard header that all HTTP-compliant server responses are guaranteed to provide.
Simply calling page.info().get_content_charset() returns the value of this header, which in this case is iso-8859-1. From there, you can decode it correctly using iso-8859-1, so that regular tools can operate on it normally.
A More Generic Solution
charset_encoding = page.info().get_content_charset()
html_content = page.read().decode(charset_encoding)

A: The stream returned by urlopen is indicated as being a bytestream by b as the first character before the quoted string.  If you exclude it, as in the appended code it seems to work as input for html2txt.
import urllib
import html2text
url='http://www.google.com'
with urllib.request.urlopen(url) as page:
    html_content = page.read()
charset_encoding = page.info().get_content_charset()
rendered_content = html2text.html2text(str(html_content)[1:], charset_encoding)

Revised using suggestions about encoding. Yes, it's a hack, but it runs. Not using str() means the original TypeError problem remains.


text:
Q: Artifacts in Azure Devops Pipelines I have an azure devops pipeline that publishes output like this:
steps:
- script: ./something.sh
  displayName: build
- publish: $(System.DefaultWorkingDirectory)/app/build
  artifact: MyPackage

This works, and publishes a build artefact, but it's not available in the Artifacts page of Azure devops, and the only way to get to it is through an http url. Is there some way to publish the artefact to the Artifacts page? In addition, the url to the artefact has the buildid in it. Is there a way I can specify semver version numbers?

A: If you want to have your package available in Azure Artifacts you should publish it to feed. Here you have an example with Universal Package.
Speaking about SemVer (from link above):

In Universal Packages, a particular package is identified by its name and version number. Currently, Universal Packages require Semantic Versioning. Semantic version numbers have three numeric components, Major.Minor.Patch. When you fix a bug, you increment the patch (1.0.0 to 1.0.1). When you release a new backward-compatible feature, you increment the minor version and reset the patch version to 0 (1.4.17 to 1.5.0). When you make a backward-incompatible change, you increment the major version and reset the minor and patch versions to 0 (2.6.5 to 3.0.0).
The Universal Packages task automatically selects the next major, minor, or patch version for you when you publish a new package. Just set the appropriate option.

And you build/pipeline artifact you will find here:


text:
Q: Package to read in last excel file in a directory in r I have a directory where all the excel files resides. I want to pick the last file in that directory in r.
Is it possible to achieve the same ?

A: Assuming you mean last in lexicographic order, and assuming that your working directory is set appropriately,
ff <- list.files()
lastfile <- ff[length(ff)]  ## or tail(ff,1)
x <- read.csv(lastfile)


text:
Q: Convert Language name to Language Code / Country Code in JavaScript I have been working on an application where i need to redirect user to the selected pages that are translated in the respective locale. I have been getting a list of languages from the backend. I need to convert the languages in the language code.
For example:
var languageName = ['English', 'Japnese', 'Chinese'];

Need to convert them to
 ['en-us','ja-jp','zh-cn'];

How can i convert the language name to language locale or country code..

A: A simple solution with a mapping object :

const mappings = {
  'English' : 'en-us',
  'Japanese' : 'ja-jp',
  'Chinese' : 'zh-cn'
};

const languageName = ['English', 'Japanese', 'Chinese'];

const output = languageName.map(lang => mappings[lang]);

console.log(output);

A: You can use an object as a mapping and then use a languege you want to get a locale for as a key:
const mapping = {
  'English' : 'en-us',
  'Japanese' : 'ja-jp',
 ...
};

const desiredLanguage='English';

console.log(mapping[desiredLanguage]) // outputs "en-us"


text:
Q: Is it acceptable for a Domain Entity to implement an interface? Please see the question here: https://stackoverflow.com/questions/2352654/should-domain-entities-be-exposed-as-interfaces-or-as-plain-objects
The general consensus is that Domain Models should not contain interfaces.  Now see here: https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Member.cs and specifically this code:
public Offer AssignOffer(OfferType offerType, IOfferValueCalculator valueCalculator)
        {
            DateTime dateExpiring = offerType.CalculateExpirationDate();
            int value = valueCalculator.CalculateValue(this, offerType);

            var offer = new Offer(this, offerType, dateExpiring, value);

            _assignedOffers.Add(offer);

            NumberOfActiveOffers++;

            return offer;
        }

The author if this blog writes a lot about DDD.
Notice that an interface is injected into the method here instead of a concrete type i.e. IOfferValueCalculator implements OfferValueCalculator.
I am talking from the perspective of a DDD purist.  Is it acceptable for domain entities to implement interfaces? If the answer is yes, then in what circumstances would it be acceptable to inject an IOfferCalculator into a Domain Entity: Member?
Once again I realise that the DDD approach is not a one size fits all and that an Anemic Domain model is suitable in a lot of cases.  I am just trying to improve my knowledge of this specific area.

A: IOfferValueCalculator is not a domain entity. It is a service. So it is perfectly fine for it to be an interface.
And there is some nuance in the "Should entities implement interfaces" question. While it is true that creating interface only for it to be implemented by single entity is useless complexity. There is nothing wrong with multiple entities implementing single interface, as those entities might be interchangeably used in code, that runs same logic on all of entities.


text:
Q: How to display SQL query of a CursorLoader I would like to display in the Log.d the current SQL query being generated by a CursorLoader in the onCreateLoader method such as:
                        return new CursorLoader(
                            getActivity(),          // Parent activity context
                            WifiEntry.CONTENT_URI,  // Provider content URI to query
                            projection,             // Columns to include in the resulting Cursor
                            null,                   // No selection clause
                            null,                   // No selection arguments
                            WifiEntry.COLUMN_WIFI_NAME + " ASC");

I have looked at the Android docs, and in here, but no success. It is useful to debugging purposes to be able to visualize the SQL string.
Thanks!
UPDATE. I am adding the ContentProvider query method, anybody can answer how to display in the Log the resulting SQL query?
Thanks.
@Override
public Cursor query(Uri uri, String[] projection, String selection,
                    String[] selectionArgs, String sortOrder)
{
    // Get readable database
    SQLiteDatabase database = mDbHelper.getReadableDatabase();
    // This cursor will hold the result of the query
    Cursor cursor;

    // Figure out if the URI matcher can match the URI to a specific code
    int match = sUriMatcher.match(uri);
    switch (match)
    {
        case WIFIS:
            // For the WIFIS code, query the wifi table directly with the given
            // projection, selection, selection arguments, and sort order. The cursor
            // could contain multiple rows of the pets table.
            cursor = database.query(WifiEntry.TABLE_NAME, projection, selection, selectionArgs,
                    null, null, sortOrder);
            break;
        case WIFI_ID:
            // For the WIFI_ID code, extract out the ID from the URI.
            // the selection will be "_id=?"
            selection = WifiEntry._ID + "=?";
            selectionArgs = new String[] { String.valueOf(ContentUris.parseId(uri)) };
            cursor = database.query(WifiEntry.TABLE_NAME, projection, selection, selectionArgs,
                    null, null, sortOrder);
            break;
        default:
            throw new IllegalArgumentException("Cannot query, unknown URI " + uri);
    }
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    // Return the cursor
    return cursor;
}


text:
Q: Leading dot in json key Most (if not all) of the json strings returned by the Dropbox API include the .tag key.
I wonder why not simply use tag, does the leading dot have a meaning in json syntax?

A: There's some discussion about this in this forum thread:

It was meant to be in a namespace that would never cause collisions


text:
Q: Printing a char* in C++ I'm writing a simple program. There is only one class in it. There is a private member 'char * number' and two function (there will be more, but first these should work correctly :) ).
The first one should copy the 'source' into 'number' variable (and I suppose somewhere here is the problem):
LongNumber::LongNumber(const char * source ){
        int digits = strlen(source);

        char* number = new char[digits+1];
        strcpy( number, source );
        //  cout<<number<<endl; - if the line is uncommented,
        //  the output is correct and there isn't a problem

}

And a print function:
void LongNumber::print(){
    cout<<number<<endl;
    // when I try to print with the same line of code here..it crashes
}

Sure, I'm missing something...but what?
(As this is my first post...do you think the tags are corrected..how would you tagged the post?)
Thank you in advance :)

A: Your number char* array would be out of scope when it exits the constructor. When you reach the print(), since the program no longer has access to the memory that *number is originally pointing to, it would crash (i.e. segmentation fault). To solve this problem do this instead:
class LongNumber
{
     char *number;
     LongNumber(const char *source);
     ~LongNumber();
     void print();
};

LongNumber::LongNumber(const char * source ){
        int digits = strlen(source);

        number = new char[digits+1];
        strcpy( number, source );
}

void LongNumber::print(){
    cout<<number<<endl;
}

Don't forget to do the following:
LongNumber::~LongNumber()
{
    delete [] number;    // to avoid memory leaks
}

I would also highly recommend using STL::string rather than using char* for your *number variable, as you won't have to deal with memory management overhead yourself, and copying the string would be easier too.

A: In the LongNumber constructor you declare a new local variable named number and initialize it with a new char array:
char* number = new char[digits+1];

Instead you should leave out the char*, so that it doesn't look like a new variable declaration and uses the object member variable:
number = new char[digits+1];

With the current code, the member variable number never gets initialized and using it later in print leads to an error.

A: Your problem is in your constructor:
LongNumber::LongNumber(const char * source )
{
  ...
  // you are declaring a new local variable called `number` here
  char* number = new char[digits+1];
  strcpy( number, source );
  ...
}

You are not copying into the class member variable called number, you are declaring a new local variable in the body of the constructor and using that. The class member variable is unused, and probably is undefined. For a pointer member, this means the value could be any invalid value - then when you call print:
void LongNumber::print()
{
  cout<<number<<endl;
  // when I try to print with the same line of code here..it crashes
}

The number you are using here, is the class member variable, which as we said is undefined. The call to cout will then crash since it tries to use that invalid pointer.
The fix is to make the constructor use the correct class member variable:
LongNumber::LongNumber(const char * source )
{
  ...
  // use the class member variable `number` here
  number = new char[digits+1];
  strcpy( number, source );
  ...
}

A: It looks to me like your declaring number as a local variable. If you want to be able to call it again in another function, you have to declare it in the class definition... like so:
class LongNumber{
public:
        int digits;
        char* number;
        LongNumber(const char * source );
        void print();
}

LongNumber::LongNumber(const char * source ){
        digits = strlen(source);
        number = new char[digits+1];
        strcpy( number, source );
        //  cout<<number<<endl; - if the line is uncommented,
        //  the output is correct and there isn't a problem
}

void LongNumber::print(){
    cout<<number<<endl;
    // when I try to print with the same line of code here..it crashes
}

Hope that helps!!!


text:
Q: locationInNode returning erroneous results I have a subclass of SKNode called Player which pretty much consists of this: http://hub.ae/blog/2014/03/26/soft-body-physics-jellyusing-spritekit/ converted to swift (With a few changes). I've allowed the user to move the player node with his finger with the following code:
    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    player.runAction(SKAction.moveTo(touch.locationInNode(world), duration: 1))
}

override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
    let touch = touches.first as! UITouch
    player.runAction(SKAction.moveTo(touch.locationInNode(world), duration: 1))
}

override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
    player.removeAllActions()
}

override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
    player.removeAllActions()
}

*As a note, the 'world' var you see is just another SKNode. 'player' is a child of this node.
This looks like it should work, however the node moves in very strange directions. This is an example of how it looks:
http://gyazo.com/87b0d09101bbbfd3ac0f2a3cdbf42e4c
How can I fix this? I found that settings the anchor point of the scene to 0.5 fixes this issue, however then the physics body of 'player' node gets messed up.

A: I had same problem but i can not remember if it is how i fixed it. Try changing this:

world > self

player.runAction(SKAction.moveTo(touch.locationInNode(world), duration: 1))

To:
player.runAction(SKAction.moveTo(touch.locationInNode(self), duration: 1))

If i am wrong let me know :)
EDIT
set anchor point to (0.5,0.5) and write those 2 methods to center on your node.
override func didSimulatePhysics() {
    camera.position = CGPointMake(player.position.x, player.position.y);
    centerOnNode(camera)
}

func centerOnNode(node: SKNode){
    var positionInScene : CGPoint = convertPoint(node.position, fromNode: node.parent)
    world.position = CGPointMake(world.position.x - positionInScene.x, world.position.y - positionInScene.y)
}


text:
Q: Win32 API Child window doesn't appear in parent's area I am trying to write a simple app in Win32 API. The goal is to create a parent window with blue background and a child window (visible as a small red square)  inside it.
I define a parent and child windows:
    WNDCLASSEXW wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GAMEPRACTICE3));
    wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wcex.hbrBackground = CreateSolidBrush(RGB(0, 0, 255));
    wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_GAMEPRACTICE3);
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    RegisterClassEx(&wcex);
    HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_VISIBLE | WS_BORDER,
        0,0, 400, 600, HWND_DESKTOP, nullptr, hInstance, nullptr);

    if (!hWnd)
    {
        return FALSE;
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // Child window

    WNDCLASSEX wc;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.lpszClassName = childClass;
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.hInstance = hInst;
    wc.hbrBackground = CreateSolidBrush(RGB(255, 0, 0));
    wc.lpfnWndProc = WndProc;

    RegisterClassEx(&wc);

    HWND hwnd_child = CreateWindow(childClass, NULL,
        WS_CHILD | WS_VISIBLE | WS_OVERLAPPEDWINDOW,
        0, 0, 32, 32,
        hWnd, 0, hInst, 0);

    ShowWindow(hwnd_child, nCmdShow);
    UpdateWindow(hwnd_child);

When I launch the app I get the following output:

It seems that the child window is not displaying at all.
I tried to search similar problems on the Internet but none of the solutions worked for me so far.
Source code:

#include "stdafx.h"
#include "GamePractice3.h"

#define MAX_LOADSTRING 100

HINSTANCE hInst;
WCHAR szTitle[MAX_LOADSTRING];
WCHAR szWindowClass[MAX_LOADSTRING];
WCHAR childClass[MAX_LOADSTRING];
LRESULT CALLBACK    WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK    About(HWND, UINT, WPARAM, LPARAM);

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    UNREFERENCED_PARAMETER(hPrevInstance);
    UNREFERENCED_PARAMETER(lpCmdLine);

    LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
    LoadStringW(hInstance, IDC_GAMEPRACTICE3, szWindowClass, MAX_LOADSTRING);

    WNDCLASSEXW wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_GAMEPRACTICE3));
    wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
    wcex.hbrBackground = CreateSolidBrush(RGB(0, 0, 255));
    wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_GAMEPRACTICE3);
    wcex.lpszClassName = szWindowClass;
    wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    RegisterClassEx(&wcex);

    HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_GAMEPRACTICE3));

    MSG msg;

    hInst = hInstance;

    HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_VISIBLE | WS_BORDER,
        0,0, 400, 600, HWND_DESKTOP, nullptr, hInstance, nullptr);

    if (!hWnd)
    {
        return FALSE;
    }

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    WNDCLASSEX wc;

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.lpszClassName = childClass;
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.hInstance = hInst;
    wc.hbrBackground = CreateSolidBrush(RGB(255, 0, 0));
    wc.lpfnWndProc = WndProc;

    RegisterClassEx(&wc);

    HWND hwnd_child = CreateWindow(childClass, NULL,
        WS_CHILD | WS_VISIBLE | WS_OVERLAPPEDWINDOW,
        0, 0, 32, 32,
        hWnd, 0, hInst, 0);

    ShowWindow(hwnd_child, nCmdShow);
    UpdateWindow(hwnd_child);

    while (GetMessage(&msg, nullptr, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_COMMAND:
        {
            int wmId = LOWORD(wParam);
            switch (wmId)
            {
            case IDM_ABOUT:
                DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
                break;
            case IDM_EXIT:
                DestroyWindow(hWnd);
                break;
            default:
                return DefWindowProc(hWnd, message, wParam, lParam);
            }
        }
        break;
    case WM_PAINT:
        {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);

            EndPaint(hWnd, &ps);
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
    UNREFERENCED_PARAMETER(lParam);
    switch (message)
    {
    case WM_INITDIALOG:
        return (INT_PTR)TRUE;

    case WM_COMMAND:
        if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
        {
            EndDialog(hDlg, LOWORD(wParam));
            return (INT_PTR)TRUE;
        }
        break;
    }
    return (INT_PTR)FALSE;
}

Any help would be appreciated :).

A: I managed to resolve the issue.

*

*I removed WS_OVERLAPPEDWINDOW from the creation of the child window

*I added seperate Window Procedure for the child window with
DefWindowProc

*I created a string for childClass and loaded it (LoadStringW)

*I initialized all 11 fields of WNDCLASSEXW structure (not sure if it's necessary)

Hope it helps.

A: For Child window doesn't appear in parent's area issue, in addition to @daniel_p's answer:

*

*WS_OVERLAPPEDWINDOW style is not relevant here. This style gives the window a title bar, a window menu, a sizing border, and minimize and maximize buttons.

*Error checking is necessary. You will find that register child window class failed and return 0.

*Specify a valid null-terminated string for class name. Class name is NULL is one of factors cause RegisterClassEx fail.

*Initialize WNDCLASSEX struct like: WNDCLASSEX wc = {0}; Without initialization, some value which you don't set explicitly later will be garbage value. This is another factor cause RegisterClassEx fail. Or you can set every value explicitly.
With the following editions your code will work:
    WCHAR childClass[MAX_LOADSTRING] = L"Child Window";
// ...
            WNDCLASSEX wc = {0};

Example for error checking of RegisterClassEx function:
DWORD errCode = 0;

ATOM childClassId = RegisterClassEx(&wc);
if (!childClassId)
{
    errCode = GetLastError();
    MessageBox(NULL, L"RegisterClassEx failed!", L"Error", MB_ICONERROR | MB_OKCANCEL);
    return 0;
}


text:
Q: Jquery Selectize Add "Clear All" link at the top of options from Ajax I am using Jquery's Selectize tagging library which works well for me so far.
Below is the code I have used.
Javascript Code:
$('#q').selectize({
    plugins: ['remove_button'],
    valueField: 'address',
    labelField: 'address',
    searchField: 'address',
    create: true,
    render: {
        item: function(data, escape) {
            return '
' + escape(data.address) + '
';
        }

    },
    onChange: function(value) {
      $(".selectize-input input[placeholder]").attr("style", "width: 100%;");
    },
    load: function(query, callback) {
        if (!query.length) return callback();
        $.ajax({
            url:  base_url + '/search-property-autocomplete',
            type: 'POST',
            dataType: 'json',
            data: {
                q: query,

            },
            error: function() {
                callback();
            },
            success: function(res) {
                console.log(res.properties);
                callback(res.properties);
            }
        });
    }
});

PHP Code:
/* API for autocomplete list of properties */
Route::post('/search-property-autocomplete', function () {
    if (!empty(trim($_POST['q']))) {
        $search_term = trim($_POST['q']);

        // getting Suburb State and Postcode of the properties based on search
        $query = Property::join('technobrave_suburbs_', function($join) {

                    $join->on('technobrave_properties_.suburb_id', '=', 'technobrave_suburbs_.id');
                });

        $query->join('technobrave_states_', function($join) {
            $join->on('technobrave_properties_.state_id', '=', 'technobrave_states_.id');
        });

        $query->select('technobrave_properties_.*', 'technobrave_suburbs_.suburb', 'technobrave_states_.state_name');

        $query->where(function($query) use ($search_term) {
            $query->where('technobrave_properties_.post_code', 'LIKE', '%' . $search_term . '%');
            $query->orwhere('technobrave_suburbs_.suburb', 'LIKE', '%' . $search_term . '%');
            $query->orwhere('technobrave_states_.state_name', 'LIKE', '%' . $search_term . '%');
        });
        $data = $query->take(8)->get(); // getting maximum 8 records only

        if ($data) {
            foreach ($data as $current_record) {
                $result[] = array(
                    'address' => $current_record->suburb . ' ' . $current_record->state_name . ' ' . $current_record->post_code
                );
            }
        }
    } else {
        $result = [];
    }
    echo json_encode(array('properties' => $result));
});

As you can see in above code, I am using Ajax to populate data and getting records by calling my php function which is working absolutely fine.
Now, I want to append one item as a hyperlink at the top of my all the results something like Clear All which will come every time I search or type in my input-box.
And IF I click on Clear All link, the results which appended below should be cleared.
To use the clearoptions() event provided by Selectize, I have updated my create: in my JavaScript code with:
create: function(input, callback) {

    $.ajax({
        url:  base_url + '/search-property-autocomplete',
        type: 'POST',
        dataType: 'json',
        data: {
            q: query,

        },
        error: function() {
            callback();
        },
        success: function(res) {

            return callback({ address: "Clear All" });

        }
    });

},

But it seems to be not working as I am unable to see my added option there. I am unable to see my Hyperlink after my results populate.
I already know using somethink like below code will remove my populated records after I search.
$('.my-hyperlink-custom-class').on('click', function() {
    control.clearOptions();
});

But I am stuck appending or pushing this new item to my code with the results I populate using Ajax.
Can someone guide me how can I achieve this.

A: Here is the script I wrote. This will change all the href attribute above the selected one with the javascript:; while the below one will remain the same.You can modify this as per your need.

$(".row").click(function(){
var present =  $(this).index();
console.log("present"+present)
 $(this).closest('.container').find('.row').each(function(index,element){
  console.log("eachindex"+$(this).index());
  if($(this).index()>=present) {

  }
  else {
   $(this).attr("href","javascript:;");
  }
 })
 $(".row").each(function(){
  $("#finalAttribute").append($(this).attr("href"));
 })
})

  R1

  R1

  R2

  R3

  R4

A: Can you try this method, I believe your issue is with DOM rendering and binding JS functions. since the element is not available on load, the element cannot by bind with javascript. below method will work.
$('body').on('click', '.my-hyperlink-custom-class', function() {
    control.clearOptions();
});

Here i have have bind the function to body, however im again checking if target element is .my-hyperlink-custom-class.

A: Forgive me, I don't have experience with Selectize but I did scan through their examples and noticed something that may be helpful:
$('#input-tags3').selectize({
    plugins: ['remove_button'],
    delimiter: ',',
    persist: false,
    create: function(input) {
        return {
            value: input,
            text: input
        }
    }
});

In this example, the create: has function prototype function(input) which only has one argument and no callback function. Your code is using the following prototype: create: function(input, callback). From the Selectize examples, I have only seen load: use function(input, callback).
I would suggest altering your create: to something along the lines of:
create: function(input) {
    // append "clear all" anchor to top of search div
    $("#searchDiv").append('Clear All')

    // perform autocomplete AJAX
    $.ajax({
        url:  base_url + '/search-property-autocomplete',
        type: 'POST',
        dataType: 'json',
        data: {
            q: query,

        },
        error: function() {
            // add text
            return input;
        },
        success: function(res) {
            // TODO: do something to display the autocomplete results
            // e.g. create a dropdown with autcomplete suggestions
            // TODO: handle user selecting one of the suggestions

            // add text
            return input;
        }
    });

},

and fill out the necessary TODOs to get the functionality you desire.
HTH

A: What you are trying to achieve can be done a little differently.
Using create callback will create new items that aren't in the initial list of options when you select the add ... option shown on top. This is not what you want.
Just try:
var $select = $('#q').selectize({
    plugins: ['remove_button'],
    valueField: 'address',
    labelField: 'address',
    searchField: 'address',
    create: false,
    score: function() { return function() { return 1; }; },
    render: {
        item: function(data, escape) {
            return '
' + escape(data.address) + '
';
        }

    },
    onChange: function(value) {

      if(value == 'Clear All') {
          var control = $select[0].selectize;
          control.clearOptions();
      }
    },
    load: function(query, callback) {
        if (!query.length) return callback();
        $.ajax({
            url: base_url + '/search-property-autocomplete',
            type: 'POST',
            dataType: 'json',
            data: {
                q: query,

            },
            error: function() {
                callback();
            },
            success: function(res) {
                // add the clear All option  on top.
                res.properties.unshift({address: "Clear All" });
                callback(res.properties);
            }
        });
    }
});

This adds an extra option and uses onChange event to clear options when selected.
Also note the score option, so that the default filtering is disabled.

A: Thank you so much to all for help and support. And special thanks to @afeique's hint to implement this feature.
Here is the solution I eventually came up with.
$('#q').selectize({
    plugins: ['remove_button'],
    valueField: 'address',
    labelField: 'address',
    searchField: 'address',
    create: true,
    render: {
        item: function(data, escape) {
            return '
' + escape(data.address) + '
';
        }

    },
    onChange: function(value) {
      $(".selectize-input input[placeholder]").attr("style", "width: 100%;");
    },
    load: function(query, callback) {
        if (!query.length) return callback();

        // Appending only if not exists
        if($('.clearAllSuggestions').length == 0) {
            $(".selectize-dropdown").append('Clear All');
        }
        $.ajax({
            url:  base_url + '/search-property-autocomplete',
            type: 'POST',
            dataType: 'json',
            data: {
                q: query,

            },
            error: function() {
                callback();
            },
            success: function(res) {
                console.log(res.properties);
                callback(res.properties);
            }
        });
    }
});

$('body').on('click', '.clearAllSuggestions', function() {

    var $select = $('#q').selectize({});
    var control = $select[0].selectize;
    control.clearCache('option');
    control.clearOptions();
    control.refreshOptions(true);
});

I modified my code a bit and put below code in my load event to append "Clear All" anchor tag in my suggestion tag options.
// Appending only if not exists
        if($('.clearAllSuggestions').length == 0) {
            $(".selectize-dropdown").append('Clear All');
        }

Then, I simply wanted to clear cache and options hence I put below code.
$('body').on('click', '.clearAllSuggestions', function() {

    var $select = $('#q').selectize({});
    var control = $select[0].selectize;
    control.clearCache('option');
    control.clearOptions();
    control.refreshOptions(true);
});

Hope this helps.