text:
Q: ENOTFOUND when extending mysql docker image I created the following dockerfile
FROM mysql:8.0
CMD ["mysqld", "--default-authentication-plugin=mysql_native_password"]

However when I try to connect to it after running, i get the following in my node application

Error: getaddrinfo ENOTFOUND mysql mysql:3306

Am I doing something wrong in my dockerfile? I just want to always add that argument when running that image. Using Gitlab CI which doesnt support passing command arguments through its interface nor can I directly use the docker run command.

A: Found my problem, was related to gitlab CI and not docker.
I tagged my image as mysql-native-auth which means in gitlab CI when specifying the host to connect to, you must use mysql-native-auth and not mysql, as apparently the service's image name is what determines this (unless you specify an alias)
Docs: https://docs.gitlab.com/ee/ci/docker/using_docker_images.html#accessing-the-services

services:
- tutum/wordpress:latest

If you don't specify a service alias, when the job is run, tutum/wordpress will be started and you will have access to it from your build container under two hostnames to choose from:

*

*tutum-wordpress

*tutum__wordpress

redpajama_set_name: RedPajamaStackExchange


text:
Q: Stuck into Ubuntu 20.04. Dual booting Windows 10 shows blank screen I am stuck in Ubuntu 20.04 because my Windows 10 can't start. When I click on Windows (UEFI) to boot windows, it shows a black blank screen and that's it forever. I have to shutdown from there to be able to access grub menu again and Ubuntu when I power on. I have tried upgrading grub and many other tricks that I don't remember, and nothing seems to work. I have installed grub2 and run sudo update-grub and sudo update-grub2, but it didn't seem to help.
Current grub boot menu:

A: Try this... In a terminal:

sudo grub_mkconfig

Reboot and try win...
Below you will find part of the terminal's "info grub" output... my research reference.
Good luck!!

6.1 Simple configuration handling
The program 'grub-mkconfig' (*note Invoking grub-mkconfig::) generates
'grub.cfg' files suitable for most cases.  It is suitable for use when
upgrading a distribution, and will discover available kernels and
attempt to generate menu entries for them.
'grub-mkconfig' does have some limitations.  While adding extra
custom menu entries to the end of the list can be done by editing
'/etc/grub.d/40_custom' or creating '/boot/grub/custom.cfg', changing
the order of menu entries or changing their titles may require making
complex changes to shell scripts stored in '/etc/grub.d/'.  This may be
improved in the future.  In the meantime, those who feel that it would
be easier to write 'grub.cfg' directly are encouraged to do so (*note
Booting::, and *note Shell-like scripting::), and to disable any system
provided by their distribution to automatically run 'grub-mkconfig'.
The file '/etc/default/grub' controls the operation of
'grub-mkconfig'.  It is sourced by a shell script, and so must be valid
POSIX shell input; normally, it will just be a sequence of 'KEY=value'
lines, but if the value contains spaces or other special characters then
it must be quoted.  For example:
end_______


text:
Q: Return Url in Paypal Not Working Even is Set Auto Return in my Paypal sandbox account on this link
https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_profile-website-payments

I am Setting Auto Return URL Entering as
http://prdemos.com/Web/ranch/pay.php

and AUTO RETURN option (Radio Button) set to ON but when i save settings it Shows me message
You have successfully saved your preferences.

when i process the transaction, and after 10 seconds,the redirected page opens the Paypal sandbox Log in https://www.sandbox.paypal.com/us/home Page not mine which i set.
Note: When i go to Setting again the auto return Option is Closed..
did i missing any option? please any one can HELP..!


text:
Q: NSInteger versus int What would be the reason to use an NSInteger vs an int in iPhone programming? Thanks.

A: An NSInteger is just a typedef with the following definition:
#if __LP64__ || NS_BUILD_32_LIKE_64
  typedef long NSInteger;
  typedef unsigned long NSUInteger;
#else
  typedef int NSInteger;
  typedef unsigned int NSUInteger;
#endif

As the typedef is defined differently basing on the platform, you can keep using NSInteger independently from the platform.


text:
Q: The Limits of Measurable Functions The question I have received is the following:
Consider R equipped with a lebesgue measure. Let $f_1, f_2, ...$ be measurable functions on R with $f_1(x)\leq f_3(x)$ for all $x,f_2(x)\leq f_4(x)$ for all $x$, $f_3(x)\leq f_5(x)$ for all $x$, and so forth. Is it the case that $$lim_{j\to +\infty}\int f_j\:{d\mu(x)}=\int lim_{j\to +\infty}\: f_j\:{d\mu(x)}\:?$$
Either give a prove or a counterexample. What positive conclusion can you draw from these hypotheses?

So I attempted this question by providing the following counterexample:

I constructed the sequence of functions such that all the functions with even subscripts are the constant function 0, and all the odd functions are the constant function 1. Clearly, then the equality does not hold, so the first part of the question is complete, it is not the case. However, I am not sure what positive conclusion I can draw from these hypotheses, I am not quite sure what is expected? Am I looking at the question in the wrong way?

A: Non-negativity is missing in the hypothesis. Even if $\lim f_n$ exist equality may not hold. Example: $f_n =-I_{(n,\infty)}$ The entire  sequence is increasing and $\lim f_n (x)=0$ for all $x$. But $\lim \int f_n =-\infty$ whereas $\int  \lim f_n =0$.


text:
Q: How to keep original values of an entity while reloading related entities using Entity Framework Core when ModelState is not valid? Using ASP.NET Core and Entity Framework Core.
When editing a record, I also load related "child" entities used for display purposes in the edit form.
If the user submits a form with missing required fields, then ModelState.IsValid is false. So far so good.
When returning the non-updated values to the user (with an error message), how can I keep the original values posted by the user and also reload related entities?
In the following simplified example the dbcontext queries the client record and includes the associated state table to display the state name.
If the ModelState is not valid, the client record is returned to the user with the values the user submitted - but all the related .Include entities are null at this point. How can I repopulate the .Include entities without overwriting the view model submitted?
// GET
public async Task<IActionResult> Edit(int clientId)
{
    var client = _context.Client
                         .Include(x => x.State)
                         .Where(w => w.client_id == clientId
                         .FirstOrDefault();
    return View(client);
}

// POST
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(clientModel)
{
   //verify: last_name
   if (clientModel.last_name == null)
   {
       ModelState.AddModelError(string.Empty, "Last name is required");
   }

   if (ModelState.IsValid)
   {
      // Update the record and redirect
      await _context.SaveChangesAsync();
      return RedirectToAction(nameof(Index), new { client_id = clientModel.client_id });
   }

   // model state is not valid! Return record submitted to the edit view
   // *** MISSING THE VALUES FROM THE RELATED ENTITY clientModel.State at this point
   return View(clientModel);
}

A: First the State navigation property should be virtual then you can load it using await _context.Entry(clientModel).Reference(x => x.State).LoadAsync();
if the related is a collection then you can use await _context.Entry(clientModel).Collection(x => x.Collection).LoadAsync();
another way is to get data from context and assign it
var client = _context.Client
                         .Include(x => x.State)
                         .Where(w => w.client_id == clientId
                         .FirstOrDefault();

 //or just get the state .. var state = _context.State..
clientModel.State = client.State;
return View(clientModel);


text:
Q: Data Explorer Feature Request: Allow Results Pane to Grow Apologies if this is a duplicate, I couldn't find it at all.
I agree with the SO/SE layouts being fixed width, the code formatting, predictability, etc. make perfect sense.  However, I'm not sure this is the case with Data Explorer, I think the results pane should be allowed to expand to the width of the browser if needed.
When you're dealing with an unknown number of columns of tabular data, the fixed width seems like an unnecessary constraint that makes it a lot less usable in some cases.  It wouldn't be a huge layout change visually, but it would add a lot to the usability.  Expanding with the browser width as the maximum (horizontally scrolling the entire page would be undesirable), and the current width as the minimum I think would be a good set of limits for both look and maximizing usable real-estate.
Somewhat related: the date columns could have their extra width trimmed down as well to help on the horizontal scroll, this query is a good example.

A: This change went live this evening, @waffles pushed the updates (found here), the grid will now resize with the following behavior:

*

*Minimum width of 950px (what it was previously)

*Maximum width of either the browser window (with 40px on each side for aesthetics) or the width needed for the current columns

*Resize happens when you:

*

*Fetch Data

*Resize the window

*Added: the width will recalc but not resize when changing (dragging) column widths...to do it while re-sizing is very counter-intuitive and really just frustrating, (this addition should go live in the next few pushes).


text:
Q: Влияние  на тэг  Заметил одну особенность. Есть нормальная страница с <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">.
Продублировал страницу на другой проект, выставил уже <!doctype html> и дизайн повело! Все
 как-то выросли по дикому! Т.е. если использовать
, то вроде нормально, но если использовать связку

 интервал между строк увеличивается в примерно 1,5 раза от того, когда если не использовать <!doctype html>.
Считаю это некорректной интерпретацией тэга. Дизайн страдает, визуализация восприятия при чтении текста тоже.
С чем это может быть связано? И как этот "баг\не баг" обойти?


text:
Q: nobody Vs anybody Vs. nobody in a specific context How to ask from a friend to not tell something / to keep something something in secret?
If I want to choose between these two, which is natural or idiomatic?

Please, don't tell it to anybody.
Please, don't tell it to anyone.
Please, tell it to nobody.

A: All of these sentences read fine (natural and idiomatic). They differ slightly in formality and register. "Anyone" and "anybody" are interchangeable in most cases, with "anyone" being a little more formal-sounding than "anybody". Also in certain phrases one sounds better than the other. For example, people say "anyone else" more commonly than "anybody else".

Please, tell it to nobody.

This sounds more emphatic. In certain contexts "nobody" is considered informal.


text:
Q: Single Instance Application - Passing commands I'm using wxPython, and I'm trying to make a single instance application. As far as this goes, there is no problem. My problem is passing commands to the already existing instance.
So lets say that when I double click a file that is associated with my application, it reads the file and displays, here is an example:
import wx
import sys
import os
import SocketServer
import socket
import threading
class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(320, 350))

        getfile = os.path.abspath(sys.argv[1])
        print getfile
        fopen = open (getfile, 'r')
        fread = fopen.read()

        panel = wx.Panel(self, -1)
        wx.StaticText(panel, -1, fread, (45, 25), style=wx.ALIGN_CENTRE)
        self.Centre()
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(1024)
        cur_thread = threading.currentThread()

        # do something with the request
        print "work"
        # could instead of the length of the input, could return error codes, more
        # information (if the request was a query), etc.  Using a length function
        # as a simple example
        response = 'string length: %d' % len(data)

        print 'responding to',data,'with',response
        self.request.send(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    stopped = False
    allow_reuse_address = True

    def serve_forever(self):
        while not self.stopped:
            self.handle_request()

    def force_stop(self):
        self.server_close()
        self.stopped = True

def client(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    sock.send(message)
    response = sock.recv(1024)
    print "Received: %s" % response
    sock.close()

def start_server(host, port):

    server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
    ip, port = server.server_address

    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target=server.serve_forever)
    # Exit the server thread when the main thread terminates
    server_thread.setDaemon(True)
    server_thread.start()

    return server
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'test')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

def main():
    app = MyApp(0)
    app.MainLoop()

if __name__ == '__main__':
    HOST, PORT = socket.gethostname(), 61955

    server = None
    try:
        client(HOST, PORT, ' '.join(sys.argv))
        sys.exit()
    except socket.error:
        server = start_server(HOST, PORT)
        main()

This works just fine, but now I want to make it a single instance application. And I know that there are several ways to accomplish this, and in my case, I found that listening to a defined port is probably the best option. But even using such option, I have no idea on how I could pass the information of the file or, atleast, the name to the original instance and display it.
So the application should be:

*

*A single instance application.

*It should be able to read the double-clicked files.

*If an instance is already open, then pass the information or file name to the original instance so it can refresh and display the file's data automatically.

Also, I didn't include any code for listening to a defined port because I really don't know much about it, so any help on this subject is also greatly appreciated.
EDIT: Code edited with "listening to a defined port", it is taken from an example. Note that print "work" does send to the running instance, I just don't know how to make it work in my occasion (because of my plain ignorance).

A: A "Single Instance" application has two parts.
A "client", which is double-clicked and starts running.  If the server is not running, it starts the server.  It passes commands to the server.  And stops.  Leaving the server running.
A "server", which is started by each client.   It  does the "listening to a defined port".  Or perhaps reading from a named pipe (which works out better sometimes).
The server does the real work.  The client passes commands to it.

A: This is the solution:
import wx
import sys
import os
import SocketServer
import socket
import threading
class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(320, 350))

        getfile = os.path.abspath(sys.argv[1])
        print getfile
        fopen = open (getfile, 'r')
        fread = fopen.read()

        panel = wx.Panel(self, -1)
        self.static = wx.StaticText(panel, -1, fread, (45, 25), style=wx.ALIGN_CENTRE)
        self.Centre()
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        data = self.request.recv(1024)
        cur_thread = threading.currentThread()

        data = data.split()
        gfile = os.path.abspath(data[-1])
        fopen = open(gfile, 'r')
        fread = fopen.read()
        self.server.app.static.SetLabel(fread)
        #Note to the self.server.app
        response = 'string length: %d' % len(data)

        print 'responding to',data,'with',response
        self.request.send(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    stopped = False
    allow_reuse_address = True

    def serve_forever(self):
        while not self.stopped:
            self.handle_request()

    def force_stop(self):
        self.server_close()
        self.stopped = True

def client(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    sock.send(message)
    response = sock.recv(1024)
    print "Received: %s" % response
    sock.close()

def start_server(host, port):

    server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
    ip, port = server.server_address

    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target=server.serve_forever)
    # Exit the server thread when the main thread terminates
    server_thread.setDaemon(True)
    server_thread.start()

    return server
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'test')
        frame.Show(True)
        server.app = frame
        #Note the server.app
        self.SetTopWindow(frame)
        return True

def main():
    app = MyApp(0)
    app.MainLoop()

if __name__ == '__main__':
    HOST, PORT = socket.gethostname(), 61955

    server = None
    try:
        client(HOST, PORT, ' '.join(sys.argv))
        sys.exit()
    except socket.error:
        server = start_server(HOST, PORT)
        main()

Essentially I had to bind the server.app with my frame:
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'test')
        frame.Show(True)
        server.app = frame
        #Note the server.app

So I could call later on:
data = self.request.recv(1024)
cur_thread = threading.currentThread()

data = data.split()
gfile = os.path.abspath(data[-1])
fopen = open(gfile, 'r')
fread = fopen.read()
self.server.app.static.SetLabel(fread)

The important here is the self.server.app, although what I wanted was to pass the commands to the running instance. And the data does this for me. Let's say I open up the already open application with the file test.app then the data value will be:
\pathtoyourapplication\application.py test.app

So I grabbed its location and read, and that's pretty much it for my stupidity, hope this might be helpful for someone, in some way.


text:
Q: Permutation of a sequence, such that $y_i+y_{i+1}$ are all distinct
The sequence $x_1, x_2, ..., x_n$ of positive integers contains at least $\frac {2n}{3}+1$ distinct numbers and each of them appears at most three times. How to prove that there is a permutation $y_1, y_2, ..., y_n$ of $x_1, x_2, ..., x_n$ such that the $n$ sums $y_i+y_{i+1}$ are all distinct, where $1\le i\le n$ and $y_{n+1}=y_1$?

This problem was proposed on a math contest and as far as I'm concerned nobody managed to solve it, moreover the official solution was flawed. Or maybe this is false? In case it's true, can it be generalized?
Any reference or help would be appreciated.


text:
Q: Will be "Domain Shared contacts API" turned down like Contacts API on June 2021? We received from google-developer email asking us to "Migrate your Contacts API to People API before June 15, 2021, to ensure error-free API calls; API calls will otherwise return 100% errors by December 15, 2021.".
Contacts Api (https://developers.google.com/contacts/v3) needs the following scope:
https://www.google.com/m8/feeds/
and the support asked to abandon it.
But this is the same https://www.google.com/m8/feeds/contacts/ of the Domain Shared Contact API.
So my question is: can we continue to use Domain Shared Contact API?
thk Federica

A: Unlike the Contacts API documentation:

Warning: The Shared Contacts API is intended only for external contacts. Using this API to create contact information for domain users or groups can result in duplicate contact information for those users and groups, which may lead to unexpected behavior.

The docs on Domain Shared Contacts don't mention anything about deprecation. THe Domain Shared Contacts API is a part of the Admin SDK which is a completely different API, so I think it's safe to assume this will continue to work without issue.


text:
Q: Does reading an elastic document by _id count as a search for the `refresh_interval` In the write tuning section, Elastic recommends to Increase the Refresh Interval
We're doing document ingestions where during ingestion we may do reads, essentially like,
GET /my-index/_doc/mydocumentid

that is, a read of the document by its _id, as opposed to a search.  Some descriptions suggest that the document id is just added to the Lucene index like other attributes.  Does this mean that the read by id would still reset the refresh_interval and force a re-index instead of allowing it to wait for the full refresh_interval?

A: This is actually a tricky one:
You are correct that a GET on an _id works right away (unlike a multi-document operation like a search, which need to wait for an explicit ?refresh from you or the refresh_interval). But the underlying implementation changed twice:

*

*Initially the GET on an _id read the data right from the translog, so it didn't need a refresh / the creation of a segment.

*The code was complex and so we changed it in 5.0 that it would be read from a segment, but a GET on an _id would automatically trigger the _refresh. So it looked the same on the outside and the code was simpler.

*But for use-cases that did a lot of GETs on _id this was expensive, since it creates lots of tiny shards. So we changed it back in 7.6 to read again from the translog.

So if you are using a current version, it doesn't trigger a _refresh.

A: a get on the _id is not a search, so no


text:
Q: Temporarily disable ELB health check during backend deployment We are using ELB for SSL termination, with only ONE backend.
During deployment, the backend need to be restarted and it usually take several minutes to boot up.
My questions:

*

*As I only have one backend, so I cannot remove it from ELB, I just want to turn off ELB health check so traffic still go to the backend immediately when server restarted, is it possible?

A: You should either shorten or hugely lengthen the check times.
You can set your health check as high as once every 5 minutes, and the unhealthy threshold to 10. This would give you 50 minutes before an instance would be seen as unavailable.
You could also set it down to the minimum of 0.1 minutes and the threshold to 2, which would detect your server being back up in as few as 12 seconds once the health check URL is functioning again. This doesn't keep the ELB from flagging the instance as unhealthy, but it does allow it to come back up as quickly as possible.
I'd go with the second option, so users get a 503 rather than just sitting around wondering why the site is taking so long to load.

A: Another quick way, change the ping port in health check to others, for example, the original port is 443, change it to any un-listen port 1234. it goes to outofservice quickly.
After you did your change, confirmed, then remember to change it back.

A: A legit way around this is to use the API to change the ELB healthcheck timeouts. You can't disable or suspend it but you can change the path OR the timeout and interval.
If you are using Ansible you can use a task before and after deployment.
Here are modules to do this for an ELB and ALB (via Target Groups):
https://docs.ansible.com/ansible/latest/modules/ec2_elb_lb_module.html
https://docs.ansible.com/ansible/latest/modules/elb_target_group_module.html
This answer needs examples, I'll update with ours if we go this route.


text:
Q: How to save value on Readonly / editable false fields in odoo Models? I've a field which I want to compute it's value on change, but I don't want the user can modify it.
If I set the field as readonly=1 or editable=0 the value isn't store.
I'm trying to set a global discount on the invoice
class account_invoice(models.Model):
    _inherit = "account.invoice"

    global_discount_p = fields.Float('Descuento porcentaje')
    global_discount = fields.Float('Descuento')
    neto = fields.Float('Neto')

    @api.one
    @api.depends('invoice_line.price_subtotal', 'tax_line.amount','global_discount_p')
    def _compute_amount(self):
        ret = super(account_invoice,self)._compute_amount()
        if self.type == 'in_invoice':
            self.neto = self.amount_untaxed
            discount = self.global_discount_p/100
            self.global_discount = self.neto * discount
            self.amount_untaxed = self.neto - self.global_discount

            for line in self.tax_line:
                line.base = self.amount_untaxed
                line.amount = line.amount - (line.amount * discount)

            self.amount_tax = sum(line.amount for line in self.tax_line)
            self.amount_total = self.amount_untaxed + self.amount_tax

        return ret

And in the layout:
<xpath expr="//field[@name='amount_untaxed']" position="before">
                <field name="neto" readonly="1"/>
                <field name="global_discount_p" onchange="_compute_amount"/>
                <field name="global_discount" readonly="1"/>
            </xpath>

It work well, if I remove readonly="1" attrs from the fields

A: Try defining the fields as
neto = fields.Float('Neto', compute='_compute_amount', store=True)
global_discount = fields.Float('Descuento', compute='_compute_amount', store=True)

A: In odoo11 you can use force_save="1" in the xml file
Hope it will help you!!

A: Override this two methods in your account_invoice class and declare field like,
global_discount = fields.Float('Descuento', readonly=True)

@api.model
def create(self, vals):
    if vals['global_discount']:
        if vals['type'] == 'in_invoice':
        vals['neto'] = vals['amount_untaxed']
        discount = vals['global_discount_p']/100
        vals['global_discount'] = vals['neto'] * discount
        vals['amount_untaxed'] = vals['neto'] - vals['global_discount']

        for line in vals['tax_line']:
            line.base = vals['amount_untaxed']
            line.amount = line.amount - (line.amount * discount)

        vals['amount_tax'] = sum(line.amount for line in vals['tax_line'])
        vals['amount_total'] = vals['amount_untaxed'] + vals['amount_tax']
    res = super(PersonInformation, self).create(vals)
    return res

@api.multi
def write(self, vals):
    if vals['global_discount']:
        if vals['type'] == 'in_invoice':
        vals['neto'] = vals['amount_untaxed']
        discount = vals['global_discount_p']/100
        vals['global_discount'] = vals['neto'] * discount
        vals['amount_untaxed'] = vals['neto'] - vals['global_discount']

        for line in vals['tax_line']:
            line.base = vals['amount_untaxed']
            line.amount = line.amount - (line.amount * discount)

        vals['amount_tax'] = sum(line.amount for line in vals['tax_line'])
        vals['amount_total'] = vals['amount_untaxed'] + vals['amount_tax']
    res = super(PersonInformation, self).create(vals)
    return res

And in the layout:
<field name="global_discount" readonly="1"/>

I hope this will help you.


text:
Q: Django runserver not serving some static files My local testing server for Django v1.8.2 on Windows 8.1 is only serving certain static files. Others are giving a 404 error.
#urls.py - excerpt
urlpatterns = [
    url(r'^$', views.index)
] + staticfiles_urlpatterns()

#settings.py - excerpt
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'main',
    'users'
)

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

As far as I can tell the development server is configured to serve static files. When running runserver I get no warnings, and my code displays no syntax errors (import statements do exist and so forth). I did for testing purposes run collectstatic before starting the server just to be sure at least once.
My view template is:
{%  load staticfiles %}
<img src="{%  static 'main/img/ComingSoon.jpg' %}" alt="Coming Soon">

The link generated is /static/main/img/ComingSoon.jpg which looks correct, the file does exist in that location. What perplexes me is that this directory produces a 404 error, but other static files are served. The directory hierarchy is:
static/
  admin/
    css/
      ..
    js/
      ..
    img/
      ..
  main/
    img/
      ComingSoon.jpg

The URL localhost:8000/static/admin/img/ gives an expected message about indexes being not allowed. However, localhost:8000/static/main/img/ reports \main\img\ cannot be found. Both are 404 statuses. Images within static/admin/img/ do display correctly with the same links as what is giving an error. The Administration site for Django does display correctly.
Why would one directory within static/ not be indexed or accessible?

A: According to the Django documentation regarding static/:

This should be an initially empty destination directory for collecting
  your static files from their permanent locations into one directory
  for ease of deployment; it is not a place to store your static files
  permanently. You should do that in directories that will be found by
  staticfiles's finders, which by default, are 'static/' app
  sub-directories and any directories you include in STATICFILES_DIRS).

I moved the files to another directory such as:
myApp/
  main/
    static/
      main/
        img/
          ..
  static/
    ..

After running collectstatic I noticed the script created the subdirectories in myApp/static/ as expected and it must have generated the URLs needed because it now properly serves the files.


text:
Q: Locking mechanism on Neo4J I found a concurrent issue on my application where there are two threads that try to do write operation in same time on same node or relationship in Neo4J v2.2.5.
I managed to reproduce the issue using simple way:

*

*Download and import example neo4j movie database: http://example-data.neo4j.org/files/cineasts_12k_movies_50k_actors_2.1.6.zip
Since the database is old, so you have to add allow_store_upgrade=true in conf/neo4j.properties to enable auto database upgrade.

*Start the neo4j and run this query on neo4jshell:
match (a:Actor {name: "Claude Jade"}), (m:Movie)
merge (a)-[:ACTS_IN]->(m);

This will create ACTS_IN relationship from the "Claude Jade" Actor to all Movie nodes. The reason of doing this is to make the delete "Claude Jade" Actor node process (see no. 4 below) more longer so the chance of concurrent issue happening is more bigger.

*Download curl command-line program if you don't have it yet. We will use curl to send query to neo4j.

*Create a bash script file (filename is up to you) with content:
#!/bin/bash

curl -XPOST http://localhost:7474/db/data/transaction/commit -H "Content-Type: application/json" -d '{"statements" : [ {"statement" : "MATCH (n:Actor {name: \"Claude Jade\"}) OPTIONAL MATCH (n)-[r]-() DELETE n, r"} ]}' &
curl -XPOST http://localhost:7474/db/data/transaction/commit -H "Content-Type: application/json" -d '{"statements" : [ {"statement" : "MATCH (n:Actor {name: \"Claude Jade\"}) CREATE (n)-[:ACTS_IN]->(m:Movie {title: \"Hello World\"}) RETURN m"} ]}' &

wait

This will run two curl process in parallel where the 1st process will try to delete the "Claude Jade" Actor and all of its relationships, and the 2nd process will try to create new ACTS_IN relationship to the "Claude Jade" Actor.

*Run the script file on bash, e.g. $ ./test.sh
Here is the result I got:
{
    "results" : [{
            "columns" : ["m"],
            "data" : [{
                    "row" : [{
                            "title" : "Hello World"
                        }
                    ]
                }
            ]
        }
    ],
    "errors" : []
} {
    "results" : [{
            "columns" : [],
            "data" : []
        }
    ],
    "errors" : [{
            "code" : "Neo.DatabaseError.Transaction.CouldNotCommit",
            "message" : "org.neo4j.kernel.api.exceptions.TransactionFailureException: Node record Node[3150,used=false,group=55,prop=-1,labels=Inline(0x0:[]),light] still has relationships",
            "stackTrace" : "java.lang.RuntimeException: org.neo4j.kernel.api.exceptions.TransactionFailureException: Node record Node[3150,used=false,group=55,prop=-1,labels=Inline(0x0:[]),light] still has relationships\r\n\tat org.neo4j.server.rest.transactional.TransitionalTxManagementKernelTransaction.commit(TransitionalTxManagementKernelTransaction.java:87)\r\n\tat org.neo4j.server.rest.transactional.TransactionHandle.closeContextAndCollectErrors(TransactionHandle.java:278)\r\n\tat
            ...

Note: if you don't see any transaction error, then you have to reimport again the movie database and re-run the steps above.
So from what I've seen, the deletion failed because it tried to delete the Actor node and its of all of ACTS_IN relationships, it did the MATCH query first (MATCH (n:Actor {name: \"Claude Jade\"}) OPTIONAL MATCH (n)-[r]-()) but before it executed the DELETE n, r, the 2nd process managed to insert the new ACTS_IN relationship to the Actor node so that's why the deletion failed because when it did try to execute the DELETE, the Actor already have one new relationship added.
I wonder if there is locking mechanism on Neo4J that can be used to prevent this issue?

A: You're observing a classic race condition. To prevent that you need to grab a lock on the Claude node. Cypher does not have a syntax for explicitly grabbing locks, so we just set a fake property as first action and delete that property in the end - this has the side effect of grabbing a lock. So change your two statements:
MATCH (n:Actor {name: "Claude Jade"})
SET n._fake = 1   // grabs the lock as first action
WITH n
OPTIONAL MATCH (n)-[r]-()
DELETE n, r

MATCH (n:Actor {name: "Claude Jade"})
SET n._fake = 1 // grab the lock early
CREATE (n)-[:ACTS_IN]->(m:Movie {title: "Hello World"})
REMOVE n._fake   // get rid of fake property
RETURN m


text:
Q: How to install Wine1.9 on Ubuntu 16.10 I have Ubuntu 16.10 64bit and I need to install wine1.9, but it is a 32 bit program.
I have already tried
sudo dpkg --add-architecture i386
but nothing changed. What should I do?

A: Installing WineHQ
sudo dpkg --add-architecture i386
sudo add-apt-repository ppa:wine/wine-builds
sudo apt-get update
sudo apt-get install --install-recommends winehq-devel

if it's not working, you can install wine-staging
sudo apt-get install winehq-staging

Source: https://wiki.winehq.org/Ubuntu

Another approach is to install PlayOnLinux
Installing PlayOnLinux
sudo apt-get install playonlinux

Then go to Tools > Manage wine versions and choose your wine version to install.


text:
Q: How to enable Security logging in WCF Service using auditLogLocation="Security" I am working on WCF Logging module. I want to enable all Security logging with WCF Service. like there are three options in auditLogLocation="Application | Security | Default. I have used Application but I want to enable Security option. I read this link Auditing Security Events.
All I want to know how to enable SeAuditPrivilege and SeSecurityPrivilege in WCF Service.

Here is my configuration

<behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
          <serviceSecurityAudit auditLogLocation="Application" suppressAuditFailure="true" serviceAuthorizationAuditLevel="SuccessOrFailure"
            messageAuthenticationAuditLevel="SuccessOrFailure" />
        </behavior>
      </serviceBehaviors>
    </behaviors>

A: You should be able to configure WCF Security Auditing, to log security events to the Windows event log, by specifying the following in the configuration file:
Service Behavior definition: (e.g.)
<behaviors>
   <behavior name="myAuditBehavior">
      <serviceSecurityAudit auditLogLocation="Application"
            suppressAuditFailure="false"
            serviceAuthorizationAuditLevel="None"
            messageAuthenticationAuditLevel="SuccessOrFailure" />
      </behavior>
</behaviors>

Service Behavior referenced in the service definition:
<services>
    <service behaviorConfiguration=" myAuditBehavior" ...
       <endpoint

Reference:  http://msdn.microsoft.com/en-us/library/ms734737(v=vs.110).aspx
Note: you do not show the service section of your configuration section, so you need to make sure the service is using correct behavior.
Regards,


text:
Q: Change text color of spinner as you can see from the code above, the color of the text is set to blue only when I open the drop-down menu while if the menu is not opened the spinner text remains white, I want to make sure that the color of the spinner text is blue even if it is not opened and not white, how can I go about implementing this? the code below is xml and kotlin

file.xml:
<Spinner
                    android:id="@+id/spinner"
                    android:layout_width="200dp"
                    android:layout_height="40dp"
                    android:layout_alignBottom="@id/textviewtipologia"
                    android:layout_marginLeft="100dp"
                    android:layout_marginTop="-40dp"
                    android:background="#F5F5F5"
                    android:popupBackground="#F5F5F5"
                    android:theme="@style/spinnerstyle" />

  <style name="spinnerstyle" parent="Base.Widget.AppCompat.Spinner">
        <item name="android:textColor">@color/customSpinner</item>
        <item name="android:textColorHighlight">@color/customSpinner</item>
        <item name="android:textColorHint">@color/customSpinner</item>
    </style>

file.kt
spinner = findViewById<Spinner>(R.id.spinner)
        var image: ImageView = findViewById<ImageView>(R.id.imgauto)
        var listaTipologia: List<TipologiaVeicolo> =
            APISupport.getListaTipologieVecioli(firebaseid, email, key)
        val tipologieAuto: ArrayList<String> = ArrayList()
        var count = 0
        for (i in listaTipologia.indices) {
            if (count == 0) {
                idVeicoloSelect = listaTipologia[i].ID
            }
            tipologieAuto.add(listaTipologia[i].DESCRIZIONE)
            count++
        }

A: You can try to create the spinner in the following way:

*

*First add the spinner in your layout file:

layout.xml
<Spinner
       android:id="@+id/spinner1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

*Now create an  spinner_item.xml layout file adding a TextView in that which will work as the selected item of the spinner:

spinner_item.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- You can change content of the textview as your need-->
<TextView
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:textColor="#F5F5F5"
  android:textSize="18sp"
  android:gravity="left"
  android:padding="5dip"
  />

*Now create a string-array in your strings.xml file which will be the content of the spinner:

strings.xml
<string-array name="languages">
    <item>Hindi</item>
    <item>English</item>
    <item>Spanish</item>
    <item>German</item>
    <item>Japanese</item>
</string-array>

*Now the final thing is to add code in your activity class:

activity.java
// call this method in onCreate() method of activity class
public void setSpinner(){
    Spinner spinner = findViewById(R.id.spinner1); // get the spinner in the layout file
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.languages,
    R.layout.spinner_item); // create adapter for spinner and set the item layout
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // set the drop down view to the adapter
    spinner.setAdapter(adapter); // set adapter to the spinner
    spinner.setOnItemSelectedListener((OnItemSelectedListener) this); // set listener to the spinner to get the data whenever item is selected from spinner

}

// override this method to get the selected item of the spinner whenever item of the spinner is selected
// also implements OnItemSelectedListener to your activity class
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    // this is the text selected from the spinner
    String text = parent.getItemAtPosition(position).toString();

    // do whatever you want from the text
    Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}

Hope this helps


text:
Q: How to store array in firestore database using Android? I want to create an firestore model like below:
attendance_log (root collection)
|
|--- 001 (document ID)
|    |
|    |--- date : 20190310
|    |--- time : 1025
|    |--- subject : "Android Programming"
|    |--- present : {"MCA01", "MCA03", "MCA04"}
|    |--- absent : {"MCA02, "MCA05"}

I could store date, time and subject by passing the value in a Map as below :
Map<String, Object> attend = new HashMap<>();
attend.put("date", d) ;
attend.put("time", t) ;
attend.put("subject", subject) ;

db.collection("attendance_log")
    .document(docID)
    .set(attend)
    .addOnSuccessListener(new OnSuccessListener<Void>() {
        @Override
        public void onSuccess(Void aVoid){
            Toast.makeText(TakeAttendance.this,"Attendance added sucessfully" , Toast.LENGTH_LONG).show();
        }
    }).addOnFailureListener(new OnFailureListener() {

    @Override
    public void onFailure(@NonNull Exception e) {
        Snackbar.make(findViewById(R.id.cdlayout) ,"Something went wrong!", Snackbar.LENGTH_LONG).show();
    }
});

But passing the array generates the error
java.lang.IllegalArgumentException: Could not serialize object. Serializing Arrays is not supported, please use Lists instead

A: The solution is in your error - you need to read your error and check what does it say - in your case, you will see that Arrays are not supported and you need to send list instead.
You can use Arrays.asList(yourArray) to convert your array and send it to your database.
Change this line:
attend.put("subject", subject) ;
To This line:
attend.put("subject", Arrays.asList(subject)) ;

A: No need to worry you are very near to the correct code. In firestore you can store array String[] instead you have to use List:
     //convert array to arraylist
      ArrayList<String> subjectsArrayList = getListOfSubjects(subjects);
      Map<String, Object> attend = new HashMap<>();
      attend.put("date", d) ;
      attend.put("time", t) ;
      attend.put("subject", subject) ;

      hashMap.put("subjects", subjectsArrayList);
      db.collection("attendance_log")
                .document(docId)
                .update(attend)
                .addOnCompleteListener(task -> {
                    //done
                });

Here is getListOfSubjects method
  public ArrayList<String> getListOfSubjects(String[] subjects){
        List<String> subjectsArrayList = new ArrayList<>();
        for (int i = 0; i < subjects.length; i++) {
            subjectsArrayList.add(subjects[i]);
        }
        return (ArrayList<String>) subjectsArrayList;
    }

Hope this will help you.


text:
Q: ADO.NET Entity Framework generates unexpected, problem INSERTs I need some help understanding the ADO.NET Entity Framework.
I'm trying to represent and manipulate hierarchical data in a WPF TreeView control with the ADO.NET Entity Framework.
ADO.NET Entity Framework Object with parent and children http://img14.imageshack.us/img14/7158/thingpi1.gif
Each of these Things has a single parent and zero or more children.
My "delete" button...

Private Sub ButtonDeleteThing_Click(...)
    db.DeleteObject(DirectCast(TreeViewThings.SelectedItem, Thing))
    db.SaveChanges()
End Sub

I'm monitoring the SQL Server Profiler while I debug my application:

*

*The first button click deletes just fine.

*The second button click inserts a duplicate parent (but with empty GUID uniqueidentifier primary key) and then performs the delete.

*The third button click fails (Violation of PRIMARY KEY constraint) because it cannot insert another row with an empty GUID primary key.

The unexpected, generated T-SQL duplication...

exec sp_executesql N'insert [dbo].[Thing]([Id], [ParentId], ...)
values (@0, @1, ...) ',N'@0 uniqueidentifier,@1 uniqueidentifier,...',
@0='00000000-0000-0000-0000-000000000000',
@1='389D987D-79B1-4A9D-970F-CE15F5E3E18A',
...

But, it's not just deletes.  My "add" button has similar behavior with unexpected inserts.  It follows the same pattern.
This makes me think there's a more fundamental problem with how I'm binding these entity classes to the WPF TreeView or with my data model itself.
Here's the relevant code...
XAML...
<TreeView Name="TreeViewThings"
          ItemsSource="{Binding}"
          TreeViewItem.Expanded="TreeViewThings_Expanded"
          TreeViewItem.Selected="TreeViewThings_Selected"
          ... >
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Thing}"
                                  ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Path=Title}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>
<Button Name="ButtonAddThing" Content="Add Thing" ... />
<Button Name="ButtonDeleteThing" Content="Delete Thing" ... />

Visual Basic...

Partial Public Class Window1

    Dim db As New ThingProjectEntities

    Private Sub Window1_Loaded(...) Handles MyBase.Loaded
        TreeViewThings.ItemsSource = _
            From t In db.Thing.Include("Children") _
            Where (t.Parent Is Nothing) _
            Select t
    End Sub

    Private Sub TreeViewThings_Expanded(...)
        Dim ExpandedTreeViewItem As TreeViewItem = _
            DirectCast(e.OriginalSource, TreeViewItem)
        LoadTreeViewChildren(ExpandedTreeViewItem)
    End Sub

    Sub LoadTreeViewChildren(ByRef Parent As TreeViewItem)
        Dim ParentId As Guid = DirectCast(Parent.DataContext, Thing).Id
        Dim ChildThings As System.Linq.IQueryable(Of Thing)
        ChildThings = From t In db.Thing.Include("Children") _
                      Where t.Parent.Id = ParentId _
                      Select t
        Parent.ItemsSource = ChildThings
    End Sub

    Private Sub ButtonAddThing_Click(...)
        Dim NewThing As New Thing
        NewThing.Id = Guid.NewGuid()
        Dim ParentId As Guid = _
            DirectCast(TreeViewThings.SelectedItem, Thing).Id
        NewThing.Parent = (From t In db.Thing _
                           Where t.Id = ParentId _
                           Select t).First
        ...
        db.AddToThing(NewThing)
        db.SaveChanges()
        TreeViewThings.UpdateLayout()
    End Sub

    Private Sub ButtonDeleteThing_Click(...)
        db.DeleteObject(DirectCast(TreeViewThings.SelectedItem, Thing))
        db.SaveChanges()
    End Sub

    ...

End Class

What am I doing wrong?  Why is it generating these strange inserts?

Update:
I've made a breakthrough.  But, I still can't explain it.
I'd gotten rid of the cause when I simplified my code for this question.
Rather than using Linq such as:

From t In db.Thing.Include("Children") Where ...

I've been using Linq such as:

From t In db.Thing.Include("Children").Include("Brand") Where ...

You see, My Thing entity is related to another Brand entity.
ADO.NET Entity Framework Object with parent and children and a related Object http://img25.imageshack.us/img25/3268/thingbrandct4.gif
I thought it was irrelevant, so I didn't include it in the question above.
Apparently this was the cause of my unexpected, problem inserts in my Thing table.
But, why?  Can anyone explain why this was happening?  I'd like to understand it better.

A: Why are you loading the parent again when adding a new child, when you already have the object? While this is no problem for the database, it will introduce inconsistencies on the object level. You can just use the existing parent like this:
Private Sub ButtonAddThing_Click(...)
    Dim NewThing As New Thing
    NewThing.Id = Guid.NewGuid()
    Dim Parent As Thing = DirectCast(TreeViewThings.SelectedItem, Thing)
    NewThing.Parent = Parent
    ...
    db.AddToThing(NewThing)
    db.SaveChanges()
    TreeViewThings.UpdateLayout()
End Sub

About the delete: have you specified cascading deletes in the database?

A: I haven't had a detailed look at the code but the first thing to consider is that you shouldn't need to call DeleteObject at every level of your hierarchy. EF like other O/RMs tracks objects and their associations for you.
Let's say, for example, that you have a parent->child 1..* relationship. If you query the parent, remove a child object from the parents Children collection and then call SaveChanges(), EF will generate the appropriate DELETE SQL statements for you - You do not need to track this yourself.
So, a better way to achieve your scenario would be to do this:

*

*Query the object hierarchy out of EF.

*Bind that to your UI. Let your UI modify the in-memory objects as you see fit.

*When you are done, call SaveChanges and let the EF figure out what to do.

Let me know if that helps.

A: There are two things going on here. I don't completely understand the relationship between them, but I think I can get you on your way.
The first thing that you need to understand is that the Entity Framework does not deal well with deleting a less-than-fully-materialized instance. That is why Include changes the behavior that you see. So if you have an entity that aggregates a list of children, you need to load those children before calling delete. Only if the child instances are in memory will they be deleted before the parent. So, with or without Include, you need to do something like this before calling Delete.
if (!thing.BrandReference.IsLoaded) thing.BrandReference.Load();

If you've called Include on the relationship, then this will do nothing if you haven't, then it will ensure that everything is materialized before you
The second thing that unique understand is that inserting a new entity with a relationship to an existing entity is conceptually two different inserts. This is a consequence of the fact that relationships are first-class in the Entity Framework. The first insert is the entity itself, the second is the relationship. In this case, there is no separate table for the relationship, so only one actual insert to the database as needed. However, the Entity Framework can only figure this out if it is mapped correctly.
So what is going on in this case? What follows is my speculation based on some of the things I see going on here. But I think the situation is even more complicated than I'm describing, so I believe what follows is incorrect in some of the details. It may be close enough to help you solve the actual problem, though.

*

*You had an instance that was less-than-fully-materialized before you tried to delete it.

*When you tried to delete something else, the framework tried to look into the same relationship. It found things out of whack and tried, unsuccessfully, to put things back into a good state.

*Then you tried to delete again, 2 repeats, only this time it is even less successful, due to the database constraint.

*Using Include fixes the issue in 1.


text:
Q: Best way to store 3 values? I need to store 3 values for my program.
The first value is a byte, the second is a another byte and last is a string.
And once I have used the values, I want to be able to remove them.
Should I store this by creating a object and give those 3 values as parameters?
Or creating a 3-dimensional list?

A: Create a type that holds those three values.
class SomeData
{
    private readonly byte _firstByte;
    private readonly byte _secondByte;
    private readonly string _stringData;

    public byte FirstByte { get { return _firstByte; }  }
    public byte SecondByte { get { return _secondByte; }  }
    public string StringData { get { return _stringData; } }

    public SomeData(byte first, byte second, string data)
    {
        _firstByte = first;
        _secondByte = second;
        _stringData = data;
    }
}

The class as it is written is immutable, but you can progressively open it up to modification depending on your needs.
Regarding removing the values once you've use them: any instances of SomeData you no longer have a reference to are automatically cleaned up by the GC.

A: A simple solution might be to use a Tuple, if this is suitable for your needs, e.g.
var tuple = Tuple.Create(someBytes, moreBytes, myString);

You can access the values using tuple.Item1, tuple.Item2, and tuple.Item3.

You can of course also use multiple Tuples if you require this, e.g.
var list = new List<Tuple<byte, byte, string>> {
    tuple,
    anotherTuple,
    thirdTuple,
    etc
};

As others have mentioned though, if you're referencing "like" data, you should create a class instead.

A: If they are related, put them in a class and have the values as fields or properties.
Once they object is no longer used, it will be garbage collected, so it will be automatically removed.

A: If you want a halfway point between a Tuple and a class, try a struct.
    struct MyStruct
    {
        private byte _byte1;
        private byte _byte2;
        private string _string1;

        public byte Byte1 { get { return _byte1; } }
        public byte Byte2 { get { return _byte2; } }
        public string String1 { get { return _string1; } }

        public MyStruct(byte byte1, byte byte2, string string1)
        {
            _byte1 = byte1;
            _byte2 = byte2;
            _string1 = string1;
        }

    }

Usage:
    MyStruct thisthing = new MyStruct((byte)1, (byte)0, "Howdy!");

    Debug.WriteLine(string.Format("{0},{1},{2}", thisthing.Byte1, thisthing.Byte2, thisthing.String1));

Output:
1,0,Howdy!

A: It depends how related your items are.  If they relate to the same parent (e.g. you are modelling a Car, and you are storing TransmissionType, Proce and Make), it would make sense to store the variables in a class.
If they are only 'working values', e.g. ones required to calculate some proble, I would store them as three variables.
My reasoning is that in months time, a well-names variable (possibly in a well-named class) will make it obvious what they are used for, without having to trawl the codebase for clues.


text:
Q: d3.js label inside path deformed i added a label inside a path successfully but when i try to center this label by changing manually x and dy attributes. the label deforms in the center.
here is some picture and its corresponding code.
before changing the x attributes its value 135:

<svg width="1306" height="628">
<g>
<path name="cf40" d="M590.3383838385344,295.20151514932513L756.3916666656733,317.13308080658317L878.5818181820214,279.5361111164093L822.186363636516,527.0494949556887L728.1939393933862,555.2472222223878Z" id="polygon2" style="fill: steelblue;"></path>
</g>
<text x="135" dy="105"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
</svg>

after changing the x attributes new value is 145:

<svg width="1306" height="628">
<g>
<path name="cf40" d="M590.3383838385344,295.20151514932513L756.3916666656733,317.13308080658317L878.5818181820214,279.5361111164093L822.186363636516,527.0494949556887L728.1939393933862,555.2472222223878Z" id="polygon2" style="fill: steelblue;"></path>
</g>
<text x="145" dy="105"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
</svg>

A: There is nothing "deformed" here. That's the expected behaviour: you're using a textPath to position the text, and the path you're referencing changes orientation at the first L command.
You can clearly see that there is nothing wrong when we draw some (red) lines, showing this "bend":

<svg width="400" height="300">
<g>
<path name="cf40" d="M590.3383838385344,295.20151514932513L756.3916666656733,317.13308080658317L878.5818181820214,279.5361111164093L822.186363636516,527.0494949556887L728.1939393933862,555.2472222223878Z" id="polygon2" style="fill: steelblue;" transform="translate(-500,-260)"></path>
</g>
<text x="145" dy="105"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
<line x1="756.3916666656733" y1="317.133080" x2="728.1939393933862"
 y2="555.2472222223878" stroke="red" transform="translate(-500,-260)"
></line>
<line x1="756.3916666656733" y1="317.133080" x2="822.186363636516"
 y2="527.049" stroke="red" transform="translate(-500,-260)"
></line>
</svg>

And you can see that even better if we create several texts, increasing the dy up to your value (105):

<svg width="400" height="300">
<g>
<path name="cf40" d="M590.3383838385344,295.20151514932513L756.3916666656733,317.13308080658317L878.5818181820214,279.5361111164093L822.186363636516,527.0494949556887L728.1939393933862,555.2472222223878Z" id="polygon2" style="fill: steelblue;" transform="translate(-500,-260)"></path>
</g>
<text x="145" dy="15"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
<text x="145" dy="40"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
<text x="145" dy="60"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
<text x="145" dy="80"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
<text x="145" dy="105"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
<line x1="756.3916666656733" y1="317.133080" x2="728.1939393933862"
 y2="555.2472222223878" stroke="red" transform="translate(-500,-260)"
></line>
<line x1="756.3916666656733" y1="317.133080" x2="822.186363636516"
 y2="527.049" stroke="red" transform="translate(-500,-260)"
></line>
</svg>

Possible solution: alternatively, you can draw a curve. That way, the text will follow the path without breaks:

<svg width="400" height="300">
<g>
<path name="cf40" d="M590.3383838385344,295.20151514932513 C 756 327,756 327, 878.5818181820214,279.5361111164093L822.186363636516,527.0494949556887L728.1939393933862,555.2472222223878Z" id="polygon2" style="fill: steelblue;" transform="translate(-500,-260)"></path>
</g>
<text x="145" dy="105"><textPath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#polygon2">CF40</textPath></text>
</svg>


text:
Q: Is an NVD3 Line Plot with Markers Possible? I'm making an NVD3 line plot that will have significantly improved clarity if I can get markers to show for each data point instead of just the line itself. Unfortunately, I haven't been able to find an easy way to do this with NVD3 yet. I also considered using a scatter plot, but I couldn't figure out how to show connecting lines between the points. A third option I considered was to overlay a line and scatter plot, but this would show each series twice in the legend and may cause other unnecessary visual complications.
Is there a way to elegantly pull this off yet? Sample code of my formatting technique is listed below, but the 'size' and 'shape' attributes in test_data have no effect on the line plot with the current code.
test_data = [ {     key: 'series1',
            values: [
                { x: 1, y: 2.33, size:5, shape:"circle" },
                { x: 2, y: 2.34, size:5, shape:"circle" },
                { x: 3, y: 2.03, size:5, shape:"circle" },
        ] } ];

nv.addGraph(function() {
  var test_chart = nv.models.lineChart();
  test_chart.xAxis.axisLabel('Sample Number');
  test_chart.yAxis
        .axisLabel('Voltage (V)')
        .tickFormat(d3.format('.02f'));

  d3.select('#test_plot')
      .datum(test_data)
    .transition().duration(500)
      .call(test_chart);

  nv.utils.windowResize(test_chart.update);
  return test_chart;
});

A: The current version of nvd3 use path instead of circle to draw markers. Here is a piece of css code that i used to show markers.
#chart g.nv-scatter g.nv-series-0 path.nv-point
{
    fill-opacity: 1;
    stroke-opacity: 1;
}

And I also write something about this in https://github.com/novus/nvd3/issues/321, you could find that how i change the shape of makers.
I don't know how to change the size of markers. Trying to find a solution.

A: Selectively enable points to some series using the following logic in nvd3.
//i is the series number; starts with 0

var selector = 'g.nv-series-'+i+' circle';
d3.selectAll(selector).classed("hover",true);

However an additional parameter( like say 'enable_points':'true') in the data would make better sense. I will hopefully push some changes to nvd3 with this idea.

A: For current version of NVD3 (1.8.x), I use this D3-based solution (scripting only, no CSS file or style block required):
nv.addGraph(function() {
  // ...
  return chart;
},
function() {
  // this function is called after the chart is added to document
  d3.selectAll('#myChart .nv-lineChart .nv-point').style("stroke-width",
    "7px").style("fill-opacity", ".95").style("stroke-opacity", ".95");
}
);

The styles used are exactly the styles added by NVD3 by applying the "hover" class to each point (when hovered). Adjust them to your needs.

A: I also wanted to add markers in a project I was working on. Here is a solution my partner and I found.
First, you have to select all of the points in your chart and set the fill-opacity to 1:
#my-chart .nv-lineChart circle.nv-point
{
    fill-opacity: 1;
}

Now your points will be visible. To adjust the size of each point you need to modify each one's "r" (for radius) attribute. This isn't a style so you can't do it with css. Here is some jQuery code that does the job. The 500 millisecond delay is so the code will not run before the chart is rendered. This snippet sets the radius to 3.5:
        setTimeout(function() {
            $('#my-chart .nv-lineChart circle.nv-point').attr("r", "3.5");
        }, 500);

A: This puzzled me until I got help from the community:
css styling of points in figure
So here is my solution, based on css:
.nv-point {
    stroke-opacity: 1!important;
    stroke-width: 5px!important;
    fill-opacity: 1!important;
}

If anyone has come here from rCharts, below is a rmarkdown template to create an nPlot with both lines and markers:
 ```{r 'Figure'}
require(rCharts)
load("data/df.Rda")
# round data for rChart tooltip display
df$value <- round(df$value, 2)
n <- nPlot(value ~ Year, group = 'variable', data = df, type = 'lineChart')
n$yAxis(axisLabel = 'Labor and capital income (% national income)')
n$chart(margin = list(left = 100)) # margin makes room for label
n$yAxis(tickFormat = "#! function(d) {return Math.round(d*100*100)/100 + '%'} !#")
n$xAxis(axisLabel = 'Year')
n$chart(useInteractiveGuideline=TRUE)
n$chart(color = colorPalette)
n$addParams(height = 500, width = 800)
n$setTemplate(afterScript = '<style>
  .nv-point {
    stroke-opacity: 1!important;
    stroke-width: 6px!important;
    fill-opacity: 1!important;
  }
</style>'
)
n$save('figures/Figure.html', standalone = TRUE)
```


text:
Q: Table next to figure with table caption on top but figure caption on bottom I use the following code, which I modified from the code I found here (second example), to place a table next to a figure.
However, in comparison to the example linked above, I would like to have the figure caption be placed on the bottom of the figure and the table caption on the top of the table, while both should be aligned correctly at the bottom. So the figure caption should be aligned with the bottom of the table.
Unfortunatly, the following code shifts the table and the figure vertically, such that they are not aligned.
How can I fix that?
\documentclass[11pt,a4paper,english]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage[font=small,labelfont=bf,tableposition=top]{caption}

\begin{document}
  \begin{minipage}{\textwidth}
  \begin{minipage}[b]{0.49\textwidth}
    \centering
    \rule{6.4cm}{2.6cm} % Height changed from 3.6cm to 2.6cm
    \captionof{figure}{A table beside a figure}
  \end{minipage}
  \hfill
  \begin{minipage}[b]{0.49\textwidth}
    \centering
    \captionof{table}{A table beside a figure}
    \begin{tabular}{cc}\hline
      Table head & Table head \\ \hline
        Some values & Some values \\
        Some values & Some values \\
        Some values & Some values \\
        Some values & Some values \\
        Some values & Some values \\
        Some values & Some values \\ \hline
      \end{tabular}
    \end{minipage}
  \end{minipage}
\end{document}

Edit: Changed height of figure.

A: Set the tabular to be aligned at the [b]aseline as well:

\documentclass{article}

\usepackage[
  font = small,
  labelfont = bf,
  tableposition = top
]{caption}

\begin{document}

\noindent
\begin{minipage}{\textwidth}
  \begin{minipage}[b]{0.49\textwidth}
    \centering
    \rule{5.5cm}{2.6cm} % Height changed from 3.6cm to 2.6cm
    \captionof{figure}{A table beside a figure}
  \end{minipage}
  \hfill
  \begin{minipage}[b]{0.49\textwidth}
    \centering
    \captionof{table}{A table beside a figure}
    \begin{tabular}[b]{cc}
      \hline
      Table head & Table head   \\
      \hline
      Some values & Some values \\
      Some values & Some values \\
      Some values & Some values \\
      Some values & Some values \\
      Some values & Some values \\
      Some values & Some values \\
      \hline
    \end{tabular}
  \end{minipage}
\end{minipage}

\end{document}

A: I was able to crack this in one of my own documents and wanted to post it here. The part that took me a long time to figure out was the H tag on the figure.
\begin{table*}
    \begin{minipage}{0.65\linewidth}
        \caption{Table Caption.}
        \label{table:mytable}
        \centering

\begin{tabular}{|l|l|l|l|l|}
\hline
(TABLE GOES HERE)
\end{tabular}

    \end{minipage}
    \begin{minipage}{0.4\linewidth}
    \begin{figure}[H]
        \centering
            \includegraphics[width=.9\textwidth]{figs/myfig.png}

    \caption{Figure caption goes here.}
    }
    \label{fig:label}
    \end{figure}
    \end{minipage}

\end{table*}


text:
Q: Enter terminal mode with bash command Is there a possibility to enter the terminal mode accessible with Ctrl+Alt+F1 with a bash command so that I can tell a script to do so?

A: Command for changing virtual terminals is named chvt. In gnome-terminal:
$ sudo chvt 1

Here is an exmplanation why do you need sudo: https://superuser.com/questions/69807/why-does-chvt-work-fine-as-a-regular-user-on-a-virtual-terminal-but-not-under-x
In a virtual terminals 1-6 root privileges aren't needed.
To run a command on another virtual terminal you can use openvt:
$ sudo openvt -s pwd

More examples and explanation here: http://www.ae.iitm.ac.in/pipermail/ilugc/2008-December/045004.html

A: Since you intend to use a command in a script, you probably want to use something that doesn't need root privileges to be ran as 'chvt' or 'openvt' .
That's why you may prefer xdotool . After you have installed, you can use the following command to simulate this shortcut input Ctrl+Alt+F1:
xdotool key Ctrl+Alt+F1


text:
Q: animating cards enter in grid in swiftUI I have a custom Grid that I have built it in SwiftUI and I have 12 cards in the model. When iPhone launches the grid loads up these 12 cards onto the screen. However, I want the cards to slide in from random positions into their respective position. I am new to SwiftUI and I'm having trouble understanding animation and transition. If I have to use @State then how do I sync that to some variable in the model.
Here is the code, this is the main view. I have omitted var body for easier focus:
Grid(self.setGameViewModel.playingTwelveSetCards) { setCard in
    SetCardView(setCard: setCard)
        .onTapGesture {
            withAnimation(.easeInOut(duration: 0.3)) {
                self.setGameViewModel.choose(setCard: setCard)
            }
         }
}

here is CardView:
ZStack {
    RoundedRectangle(cornerRadius: cornerRadius)
        .stroke(isSelected ? Color.black : Color.gray, lineWidth: lineWidth)
    VStack {
        ForEach(0..<count) { _ in
            self.getShapes(color: color)
        }
    }
}
.padding(5)
.scaleEffect(isSelected ? 1.07 : 1)

self.setGameViewModel.playingTwelveSetCards contains 12 set cards extracted from the viewModel, as soon as the app launches playingTwelveSetCards is populated with 12 set cards and Grid just gets drawn but I don't want cards just to appear I want them to slide from random positions for that I have this little helper function
func generateRandomNumberForOffset() -> CGFloat {
    CGFloat(arc4random_uniform(201) + 100)
}

Where should I apply transition and animation?


text:
Q: Can we do the same type of operation in vectors like we do in complex numbers and vice-versa? We know that e^itheta in complex numbers is very special because it makes the complex numbers to rotate some angle about origin . Is there a similar thing present in vectors too which rotate a vector by some angle? And what about the cross product in vectors , can we be able to find a complex number which is perpendicular to plane formed by some two complex numbers and the origin?

A: Operation  $z \to e^{i \alpha}z$ has a close equivalent in 3D.
Indeed, the rotation with angle $\theta$ about unit vector $V_0:= \begin{pmatrix}a\\b\\c \end{pmatrix}$ is
$$R_{\theta,V_0}=\exp(\theta [V_0]_{\times})\tag{1}$$
where $\exp(M)=I+M+\frac12 M^2+ \frac{1}{3!} M^3+\cdots$ is the matrix exponential and $[V_0]_X$ is the antisymmetric matrix defined by
$$[V_0]_{\times}=\begin{pmatrix}0&-c&b\\c&0&-a\\-b&a&0\end{pmatrix}\tag{2}$$
Important remark: One could define $[V_0]_{\times}$ by the following formula :
$$[V_0]_{\times}V=V_0 \times V\tag{2}$$
In detail:
$$\begin{pmatrix}0&-c&b\\c&0&-a\\-b&a&0\end{pmatrix}\begin{pmatrix}x\\y\\z \end{pmatrix}=\begin{pmatrix}-cy+bz\\ \ \ cx-az\\-bx+ay \end{pmatrix}$$

A: The quaternions may be used in place of complex numbers to describe three dimensional rotations. See here.
Let $\vec{u}$ be a unit vector (the rotation axis) and consider the quaternion $q = \cos \frac{\alpha}{2} + \vec{u} \sin \frac{\alpha}{2}$. Then
$$\vec{v'} = q \vec{v} q^{-1} = \left( \cos \frac{\alpha}{2} + \vec{u} \sin \frac{\alpha}{2} \right) \, \vec{v} \, \left( \cos \frac{\alpha}{2} - \vec{u} \sin \frac{\alpha}{2} \right)$$
yields the vector $\vec{v}$ rotated by an angle $\alpha$ around the axis $\vec{u}$.


text:
Q: How to change position of jQuery Draggable Component by clicking (no dragging) on area? I'm having a little trouble with jQuery UI Draggable component and hoping for your help.
I have a square box with 200x200px dimensions.
In that box I have 100x100px of size draggable component, which is "snapped" to it's parent element.
When I drag that little box, it snaps by 100px to x or y axis.
What I wanna to do, is that when I click on some other place of that draggable area, the draggable component to go there.
Here's a Demo: http://jsbin.com/iPURAjUk/3/edit
As you can see, I have 4 places where that draggable component can be.
By Default it's on 1st place, and I want to, if I click on 4th place, that component go to there.
I count find similar problem here or related methods on jquery ui documentation, so I was hoping you could help me.
Thank you!

A: If you just need to click on areas, you don't really need of draggable.
Try this instead: http://jsbin.com/iPURAjUk/4/edit

A: @gtournie
That's not exactly what I wanted.
But I figured it out by myself.
Here's the result of what I was trying to get.
http://jsbin.com/iPURAjUk/8/edit?js,output


text:
Q: Query who will output ONLY numbers in field1 who exceeded a specific threshold I have to make a "simple" query on ORACLE DB who will output ONLY numbers in field1 who exceeded a specific threshold.
In other words, assuming I have the following data in database.
FIELD1               FIELD2
=========            ==============
3291234567           333991123456789
3277654321           333011123456789
3481234567           333101123456789
3291234567           333991123456789
3291234567           333011123456789
3277654321           333015123456789
3277654321           333103123456789
3277654321           333201123456789
3481234567           333112123456789

I want to output only number in field1 with occurrences >= 3, so the query output will be:
FIELD1        FIELD2
=========     ==============
3277654321    333011123456789
3277654321    333015123456789
3277654321    333103123456789
3277654321    333201123456789
3291234567    333991123456789
3291234567    333991123456789
3291234567    333011123456789

Please help!!!!
Thanks
Lucas

A: This should work for you (using COUNT(*) as a window function) - I assume you want Oracle even though the question is tagged mysql:
SELECT field1, field2 FROM (
    SELECT field1, field2, COUNT(*) OVER ( PARTITION BY field1 ) field1_cnt
      FROM mytable
) WHERE field1_cnt >= 3;

Accomplishing this in MySQL is a bit trickier since MySQL doesn't have window functions.

A: SELECT * FROM db_table WHERE field1 IN
( SELECT field1 FROM db_table GROUP BY field1 HAVING count(*) >= 3 )

I believe this will work in Oracle and MySQL.  Using a subquery, you list all the field1 entries that have three occurrences, then the original query is run to match field1 entries in that list.

A: UPDATE
Referring to additional information from your comments:
Since subquery in this very case is a set of grouped information serving for identification which FIELD1 values satisfy the condition of having more than 3 occurences in yourtable and because of the fact that this additional info is INNER JOIN-ed to yourtable, it should be enough if you added field filtering with WHERE clause in the top-most query.
So the query with WHERE clause should look like:
     SELECT  A.FIELD1,  A.FIELD2
        FROM
        yourtable A
        INNER JOIN
        (
         SELECT FIELD1, COUNT (1)
         FROM yourtable
         GROUP BY FIELD1
         HAVING COUNT (1) >= 3
       ) B
       ON A.FIELD1 = B.FIELD1
     WHERE
       A.FIELD1 = 'some_value'

Again, by your last comment, if you have more fields in yourtable that you need to filter by, you may add them like:
     ..................
     WHERE
       A.FIELD1 = 'some_value'
       AND A.FIELD5 = 'some_field5_val'
       AND (...)


text:
Q: RestTemplate RestClientException Could not extract response: no suitable HttpMessageConverter found I am getting this error when calling the RestTemplate method
GetStatusRestfulResponse response = restTemplate.getForObject(restRequest.getUrl(), GetStatusRestfulResponse.class,restRequest.getParams());

>org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [class GetStatusRestfulResponse] and content type [application/json]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:108)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:550)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:511)
at org.springframework.web.client.RestTemplate.getForObject(RestTemplate.java:248)

RestTemplate restTemplate = new RestTemplate();
    HttpClient httpClient   = HttpClientBuilder.create().setDefaultCredentialsProvider(setupAuthentication(restRequest)).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    requestFactory.setReadTimeout(restRequest.getReqTimeOut());
    restTemplate.setRequestFactory(requestFactory);
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
response = restTemplate.getForObject(restRequest.getUrl(),     GetStatusRestfulResponse.class,restRequest.getParams());

A: I was able to solve the issue . the culprit was the java object I was using GetStatusRestfulResponse.
I took the following steps to debug the issue.

*

*Got the source codes for spring-web and jackson-databind.

*on debugging in the spring and jackson source code, realized that the issue was with the ObjectMapper not able to deserialize the java object.

*The issue was that my Java object had inner classes .

in order to fix the problem with ObjectMapper not able to deserialize the java object , I had to

*

*Add default no parameter constructors for the main java class and inner classes.

*Made the inner classes static.
this solved the issue :)


text:
Q: How to get Vue 3 render function h() to output html I am using Vue 3 render function and cannot work out how to render HTML in the template.
I have tried this:
h('span', {}, 'Bold');

But it outputs the html tags Bold on the page rather than Bold.
Does anyone know how to get the render function to render HTML?

A: According to h() arguments,I think the render function could not render HTML directly in the children argument, you need to transfer to another render function like
return h('span', {}, [h('strong', 'Bold')]);

But you could set innerHTML in the props argument to make it:
return h('span', {

    innerHTML:'Bold'

},[]);


text:
Q: How to make a button shows up under certain condition? I am student learning JavaScript.
For my private project, I am trying to create a survey that links to Google review page if clients chose good or very good. If client chose average or below, it goes to next step where people can fill out a form.
However, I am having trouble on the button function. I tried to "Next" button and depends on the clients' answer, the button do one the the above with if and else.

function buttonConditions() {
  var x = document.getElementsByName("question_1");
  var y = document.getElementsByName("process");
  var z = document.getElementsByName("forward");
  if (x === "good_1"
    or "very_good_1") {
    y.style.display = "block";
  } else {
    z.style.display = "block";
  }
}

How was the service provided?

        <input type="radio" id="very_bad_1" name="question_1" class="required" value="Very bad" onchange="getVals(this, 'question_1');">
        Very bad

        <input type="radio" id="bad_1" name="question_1" class="required" value="Bad" onchange="getVals(this, 'question_1');">
        Bad

        <input type="radio" id="average_1" name="question_1" class="required" value="Average" onchange="getVals(this, 'question_1');">
        Average

        <input type="radio" id="good_1" name="question_1" class="required" value="Good" onchange="getVals(this, 'question_1');">
        Good

        <input type="radio" id="very_good_1" name="question_1" class="required" value="Very Good" onchange="getVals(this, 'question_1');">
        Very Good

  <button type="submit" name="process" class="submit" style="display:none">Submit</button>

  <button> type="button " name="forward " class="forward " style="display:none ">Next</button>

I am okay with php part and others, but it is just those buttons don't work out as I expected.

A: The code you attached had the button tag opened, does this fix it?

function buttonConditions() {
  var x = document.getElementsByName("question_1");
  var y = document.getElementsByName("process");
  var z = document.getElementsByName("forward");
  if (x === "good_1"
    or "very_good_1") {
    y.style.display = "block";
  } else {
    z.style.display = "block";
  }
}

How was the service provided?

        <input type="radio" id="very_bad_1" name="question_1" class="required" value="Very bad" onchange="getVals(this, 'question_1');">
        Very bad

        <input type="radio" id="bad_1" name="question_1" class="required" value="Bad" onchange="getVals(this, 'question_1');">
        Bad

        <input type="radio" id="average_1" name="question_1" class="required" value="Average" onchange="getVals(this, 'question_1');">
        Average

        <input type="radio" id="good_1" name="question_1" class="required" value="Good" onchange="getVals(this, 'question_1');">
        Good

        <input type="radio" id="very_good_1" name="question_1" class="required" value="Very Good" onchange="getVals(this, 'question_1');">
        Very Good

  <button type="submit" name="process" class="submit" style="display:none">Submit</button>

  <button type="button " name="forward" class="forward" style="display:none">Next</button>

A: Is this what you are trying to achieve?

How was the service provided?

        <input
          type="radio"
          id="very_bad_1"
          name="question_1"
          class="required"
          value="Very bad"
          onchange="setVisibility(this);"
        />
        Very bad

        <input
          type="radio"
          id="bad_1"
          name="question_1"
          class="required"
          value="Bad"
          onchange="setVisibility(this);"
        />
        Bad

        <input
          type="radio"
          id="average_1"
          name="question_1"
          class="required"
          value="Average"
          onchange="setVisibility(this);"
        />
        Average

        <input
          type="radio"
          id="good_1"
          name="question_1"
          class="required"
          value="Good"
          onchange="setVisibility(this);"
        />
        Good

        <input
          type="radio"
          id="very_good_1"
          name="question_1"
          class="required"
          value="Very Good"
          onchange="setVisibility(this);"
        />
        Very Good

  <button type="submit" id="submit-button" class="hode" style="display:none ">
    Submit
  </button>

  <button id="next-button" type="button " name="forward " style="display:none ">
    Next
  </button>

https://stackblitz.com/edit/js-vm1c7z?file=index.html

A: Try this:

function getRadioGroupValue(radioGroupName) {
    let selectedOption = Array.from(document.getElementsByName(radioGroupName))
    .find((option) => option.checked);

  if (selectedOption) {
    return selectedOption.value;
  } else {
    return "";
  }
}

function buttonConditions() {
  var x = getRadioGroupValue("question_1");
  var y = document.getElementsByName("process")[0];
  var z = document.getElementsByName("forward")[0];

  if (x === "good_1" || x === "very_good_1") {
    y.style.display = "block";
  } else {
    z.style.display = "block";
  }
}

How was the service provided?

        <input type="radio" id="very_bad_1" name="question_1" class="required" value="Very bad" onchange="buttonConditions();">
        Very bad

        <input type="radio" id="bad_1" name="question_1" class="required" value="Bad" onchange="buttonConditions();">
        Bad

        <input type="radio" id="average_1" name="question_1" class="required" value="Average" onchange="buttonConditions();">
        Average

        <input type="radio" id="good_1" name="question_1" class="required" value="good_1" onchange="buttonConditions();">
        Good

        <input type="radio" id="very_good_1" name="question_1" class="required" value="very_good_1" onchange="buttonConditions();">
        Very Good

  <button type="submit" name="process" class="submit" style="display:none">Submit</button>

  <button type="button " name="forward" class="forward " style="display:none ">Next</button>

jsfiddle

Explanations
This condition:
if (x === "good_1"
  or "very_good_1") {
    y.style.display = "block";
} else {
    z.style.display = "block";
}

which produces this error in the console:
Uncaught SyntaxError: missing ) after condition

does not follow Javascript's syntax: the or operator is done with symbol || (see here for more information). Also, you can't write
if (x == y || z)

to check if x is equal to y or to z. Instead, you should write
if (x == y || x == z)

document.getElementsByName("...") does not return a single element, but instead it returns a NodeList. So to get your elements y and z, you should take the first element of that array:
var y = document.getElementsByName("process")[0];
var z = document.getElementsByName("forward")[0];

(note the trailing [0]).
Also note that question_1 is a radio group. To get the value of a radio group (in vanilla Javascript) you cannot simply do
let x = document.getElementsByName("myRadioGroup");
console.log(x.value);

instead you should check every single element of the NodeList and get the value of the checked element (if any). You can use this function:
function getRadioGroupValue(radioGroupName) {
    let selectedOption = Array.from(document.getElementsByName(radioGroupName))
    .find((option) => option.checked);

  if (selectedOption) {
    return selectedOption.value;
  } else {
    return "";
  }
}

let x = getRadioGroupValue("question_1");

You have also some errors in your HTML code too. The  tag is not correctly closed and you have a missing  tag.
Also you are invoking a function which has not been defined in our onchange="..." event.

EDIT
To navigate user to the next step, you should replace your <button name="forward"> with an anchor (e.g. a link to the next page):
Next

See here for the updated fiddle.

A: Here is also working solution. You can use JS filter to search for the checked element inside the array. In this case it is the radio button, so we can use [0] index. Having the point we can get its value by adding .value at the end.
Also, it is very helpful to listen on the change event. You can do this using for example addEventListener.

function buttonConditions() {
  var x = document.getElementsByName("question_1");
  var y = document.getElementById("process");
  var z = document.getElementById("forward");

  let valueChecked = [...x].filter(v => v.checked)[0].value
  if (valueChecked === "Good" || valueChecked === "Very Good")   {
      y.style.display = "block";
    } else {
      z.style.display = "block";
    }

}

(function () {

    var x = document.getElementsByName("question_1");
    x.forEach(e => {
        e.addEventListener("change", buttonConditions)
    })

})()
<!DOCTYPE html>

    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />

How was the service provided?

        <input type="radio" id="very_bad_1" name="question_1" class="required" value="Very bad">
        Very bad

        <input type="radio" id="bad_1" name="question_1" class="required" value="Bad">
        Bad

        <input type="radio" id="average_1" name="question_1" class="required" value="Average">
        Average

        <input type="radio" id="good_1" name="question_1" class="required" value="Good">
        Good

        <input type="radio" id="very_good_1" name="question_1" class="required" value="Very Good">
        Very Good

  <button id="process" type="submit" name="process" class="submit" style="display:none">Submit</button>
  <button id="forward" type="button " name="forward " class="forward" style="display:none">Next</button>


text:
Q: Returning a value after checking which button is checked and grabbing a value from a field I'm fairly new to JavaScript and I'm having trouble with an assignment. I need to grab the user input from 2 text fields and either add, substract, multiply, or divide them, then display the answer. I'm also not sure on how to display the answer, I've been trying to get it to show up on the paragraph but I can't seem to get it to work. Thanks in advance!
JavaScript

HTML form

<form id="form1" name="form1" method="post" action="">

Input the two numbers that you wish to calculate!

    First Number!
      <input type="text" name="Num1" id="Num1" />

    Second Number!
      <input type="text" name="Num2" id="Num2" />

Please choose what you wish to do with the numbers!

      <input type="radio" name="Add" value="Add" id="Add" />
      Add

      <input type="radio" name="Multiply" value="Multiply" id="Multiply" />
      Multiply

      <input type="radio" name="Substract" value="Substract" id="Substract" />
      Substract

      <input type="radio" name="Divide" value="Divide" id="Divide" />
      Divide

Click Submit to get your answer!

    Click me!
       <input type="submit" name="Button" id="Button" value="Submit" onclick="processData('Num1','Num2')" />

Your answer is :

</form>

A: First provide your radio buttons same name, So It denotes to a group which make sure that only one radio button will be checked. lets say it to 'Operation' like

  <input type="radio" name="Operation" value="Add" id="Add" />
  Add

  <input type="radio" name="Operation" value="Multiply" id="Multiply" />
  Multiply

  <input type="radio" name="Operation" value="Substract" id="Substract" />
  Substract

  <input type="radio" name="Operation" value="Divide" id="Divide" />
  Divide

Now change your js code to
var number=new Object();
number.Num1= 0;
number.Num2= 0;

function processData(Num1,Num2) {

    // get all the fields' values
    // parse your fields value to number
    number.Num1 = Number(document.getElementById(Num1).value);
    number.Num2 = Number(document.getElementById(Num2).value);

    // a variable to hold the answer
    var answer = 0;

    //Check which radio button is checked
    if (document.getElementById('Add').checked) {
        answer = number.Num1 + number.Num2;
    } else if (document.getElementById('Multiply').checked) {
        answer = number.Num1 * number.Num2;
    } else if (document.getElementById('Subtract').checked) {
        answer = number.Num1 - number.Num2;
    } else if (document.getElementById('Divide').checked) {
        // if number.Num2 =0 then it will product Divide by Zero error
        // So We are checking if number.Num2 === 0 then display 0 else perform the operation.

        answer = number.Num2 === 0 ? 0 : (number.Num1 / number.Num2);

        // You can also change this ternary operation to if..else condition like
        /*
         if(number.Num2 !== 0){
            answer = number.Num1 / number.Num2;
         }
        */

    }

    document.getElementById("Answer").innerHTML = answer;

    return false;
 }

You need to make change in your button markup to prevent form submittion, you can change it to (change type to button so It not submit the form)
<input type="button" name="Button" id="Button" value="Submit" onclick="processData('Num1','Num2')" />

or (place return false in end to js function and change onclick to onclick="return processData('Num1','Num2')" so It does not submit the form.
<input type="submit" name="Button" id="Button" value="Submit" onclick="return processData('Num1','Num2')" />

A: You can do this by the following code:

And you have to change your input type to button instead of submit button
by the following code:
<input type="button" name="Button" id="Button" value="Submit"
onclick="processData('Num1','Num2')" />


text:
Q: Printing the ASCII value (not character) in x86 Assembly I'm a newbie with assembly language and I'd like to display the ASCII value of a character which I have stored in register CX.
Any ideas how to do it? Thank you in advance for your answers.


text:
Q: separate auth for firebase multiple sites I am using firebase to host 3 different sites. The idea is to have 2 different admin sites that would be managed by 2 different admins. Is there a way I can make admin user to only access admin-site-1 and not admin-site-2?

A: You could deploy multiple sites on firebase hosting (2 admins + 1 client), but keep in mind that since all sites belong to the same project, they will still connect to the same Firestore database and/or the same Authentication service. You won't have separate resources per site.
I would approach this requirement by using custom roles along with security rules to control admin access on each site. Look for Firebase CodeLab and YouTube channel, there is ton of content out there on how to code this.


text:
Q: Only one of the ear buds playing Bluetooth audio at a time when using bluetoothctl I am trying to pair my OnePlus Buds Z2 with my Ubuntu 20.04 device. When I tried pairing in the GNOME desktop environment the pairing was successful and works as intended. The problem arises when I use bluetoothctl. When I am in i3 desktop environment, I use bluetoothctl commnad line tool to connect to my bluetoothe device.
I follow these steps:
bluetoothctl devices

I note down the MAC address of my ear-buds and then:
bluetoothctl pair <MAC-ADDRESS-OF-DEVICE>

I get the following output:
[CHG] Device <MAC-ADDRESS-OF-DEVICE> Connected: yes

Now when I place my earbuds in my ear, I cannot hear audio from the earbud that was first placed. I tried placing both the buds in my ear at the same time but again only one of them play the audio. When I remove the bud that is playing the audio, the other bud now plays the audio. I am sure that both the buds do not act as separate devices as there is only one device listed when I bluetoothctl devices.
Edit:
I tried connecting using bluetoothctl from GNOME desktop environment and the same issue happened. Only one bud plays the audio. However, using the standard Settings>Bluetooth and then pairing the device plays the audio in both.


text:
Q: Area calculation in R So I haven been trying to calculate the total land loss due to climate change. The dataset that I use is from this website link
This dataset consists of the longitude and latitude of the place that will most likely be lost. I want to calculate the total area of such points. I know the geosphere packages has a function to calculate the area of the polygon created by a set of points. Still I worry that using this may overestimate the result by connecting points that are really far away from each other.
link to map
If you look at the Antarctica, simply connecting all the red points would overestimated the affected area.
My question is does the areapolygon() function accounts for that fact? If not is there a way to come up with a more precise estimate for the area in question? I was thinking about using the distance between points as a criteria. But I don't know how to implement that in R.
Thank you
This is the code i have been using so far
    library(rgdal)
    library(sp)
    library(geosphere)
    library(plyr)
    grid_file_6m <- new("GDALReadOnlyDataset","link_to_the_file")
    grid_6m <- asSGDF_GROD(grid_file_6m, output.dim=c(1000, 1000))
    plot(grid_6m,bg="black")
    grid_6m_df <- as.data.frame(grid_6m)
    grid_6m_df=grid_6m_df[,-1]
    grid_6m_df$id= coords2country(grid_6m_df)
    grid_6m_df<-grid_6m_df[!(is.na(grid_6m_df$id)==TRUE),]
   grid_6m_df<-grid_6m_df[!(is.na(grid_6m_df$x)==TRUE),]
   grid_6m_df<-grid_6m_df[!(is.na(grid_6m_df$y)==TRUE),]
   write.csv(grid_6m_df,"test.csv")
   grid_6m_df<- read.csv(file="test.csv", sep=",", header=TRUE )
   Allname<-levels(grid_6m_df$id)
  Country.df <- split(grid_6m_df[,-4],grid_6m_df$id)
  clean.up<- function(x)
  {
   x<-x[,2:3]
   }
   Country.df <-lapply(Country.df,clean.up)
   distm.km <-function (x)
  {
   distm(x)/1000
  }
   dis.table <-lapply (Country.df,distm.km)

The function coords2country() is from another post here to match which country a point belongs to.
Thank you


text:
Q: Can we have a FIMP (WIMP) dark matter produced via freeze-out(-in) mechanism? In general, we study dark matter production via freeze-out or freeze-in, for instance. The former produces thermal dark matter particles which correspond to a class of particle called Weakly Interacting Massive Particles (WIMPs). The later is related to non-thermal dark matter production, corresponding to Feebly Interacting Massive Particles (FIMPs). That's what one quickly finds in the literature.
My question instead goals to know whether is possible FIMPs (WIMPs) be (non-)thermally produced via freeze-out(-in) or not, and why.