text:
Q: how to make clock hands move/rotate (html, css) i tried making an easy working clock but i have no idea how to get the clock hands to rotate. i tried to use "@keyframes" to try to get it working but i dont know what to put in "before". is there a way to make it rotate using only css or will using javascript be easier. the link below shows my work but you can also look below and see my code.
https://codepen.io/dior44/pen/GRZMZdy

h1 {
  margin: -40px 0 0 0;
  font-size: 50px;
  position: relative;
  top: 100px;
}
div {
  margin: 0 auto;
}
.clock {
  height: 400px;
  width: 400px;
  border-radius: 400px;
  background: #cccc;
}
.dot {
  height: 60px;
  width: 60px;
  border-radius: 60px;
  background: #aaa;
  position: relative;
  top: 120px;
  left: -27px;
  z-index: -1;
}
.hours {
  width: 7px;
  height: 90px;
  background: blue;
  position: relative;
  top: 100px;

}
.minutes {
  width: 5px;
  height: 170px;
  background: black;
  position: relative;
  top: -50px;

}
.seconds {
  width: 3px;
  height: 220px;
  background: red;
  position: relative;
  top: -10px;
  animation-name: second;
  animation-duration: 1s;
}

@keyframes second {
  from {

  }
}

h2 {
  position: relative;
  top: 45px;
  left: 738px;
  font-size: 35px;
  margin: -20px 0 0 0;
}
h3 {
  margin: -140px 0 0 0;
  font-size: 35px;
  position:relative;
  top: 310px;
  left: 920px;
}
h4 {
  margin: 3px 0 0 0;
  position: relative;
  top: 268px;
  left: 570px;
  font-size: 35px;
}
h5 {
  margin: 20px 0 0 0;
  position: relative;
  top: 400px;
  left: 738px;
  font-size: 35px;
}

Clock

12

3

9

6

A: Pure HTML/CSS second hand:

#clock_container {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 150px;
  height: 150px;
  border-radius: 50%;
  border: 2px solid black;
}

#seconds {
  height: 50%;
  width: 0px;
  box-sizing: border-box;
  border: 1px solid black;
  top: 0%;
  left: 50%;
  position: absolute;
  transform-origin: bottom;
  /* of-course, would be 60s */
  animation: secondsMotion 10s infinite linear;
}

@keyframes secondsMotion {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

If you wanted to start with the correct time - with a little JS early on:
var sec = new Date().getSeconds();
var sec_start = (sec/60) * 360 + 'deg';
var sec_end = (sec/60) * 360 + 360 + 'deg';
document.documentElement.style.setProperty("--sec-rot-start", sec_start);
document.documentElement.style.setProperty("--sec-rot-end", sec_end);

and then, in the keyframes:
@keyframes secondsMotion {
  0% {
    transform: rotate(var(--sec-rot-start));
  }

  100% {
    transform: rotate(var(--sec-rot-end));
  }
}


text:
Q: How do I use NoteIntents? I am trying to access NoteIntents.CREATE_NOTE. But neither does Android Studio recognize it nor does it let me import com.google.android.gsm.actions.NoteIntents;
I am trying to create an implicit intent receiver for creating notes. I have been referring to Google Developer Documentation.
Link to New Note Intent Section.
Please help

A: This is because your project is not setup with google play services. You can follow this document which indicates how to setup the project with google play services.
Do take a note in the document:

Be sure you update this version number each time Google Play services is updated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Virtual LANs in memory for several virtual machines on one host Suppose I have host machine with no NIC.
I would like to run several virtual machines on it and connect them with totally virtual LANs in between. I want many machines and many LANs.
I would like to experiment with network configs this way.
What tools allow me to do this?

A: In most cases, unless you need actual isolation of groups of machines, you shouldn't need to do anything special.  The standard approach of using a bridge interface to connect virtual machines to the host network works just fine in most cases even without needing actual networking hardware on the host.  In fact, the bridge interface in this standard setup exists solely so that the virtual machine manager has something to connect the virtual network interfaces for the virtual machines to, because it's kind of hard to directly expose a VM to the network without some kind of intermediary layer.
As a more concrete example, here's an excerpt from the output of ip link show on one of my systems where I run a bunch of virtual machines:
6: br0: <BROADCAST,MULTICAST,PROMISC,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default qlen 1000
    link/ether fe:20:b5:bd:42:4b brd ff:ff:ff:ff:ff:ff
7: tap0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast aster br0 state UNKNOWN mode DEFAULT group default qlen 1000
    link/ether fe:98:c5:54:95:2a brd ff:ff:ff:ff:ff:ff
8: tap1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast aster br0 state UNKNOWN mode DEFAULT group default qlen 1000
    link/ether fe:97:56:bf:0c:81 brd ff:ff:ff:ff:ff:ff

On this system, the software bridge interface br0 serves as a network segment that all the VM's connect to, providing functionality equivalent to a hardware network switch.  Each of the tap interfaces is automatically created by QEMU for each virtual machine I run (I've only listed two such interfaces here, but I regularly have at least a dozen) when I use the -net bridge option for QEMU, and acts like the cable connecting the (virtual) NIC in the VM to the bridge interface.  In this particular case, I actually don't have any physical hardware connected to this bridge interface (so it's what's sometimes called a 'floating' or 'virtual' bridge), and instead use routing rules on the host system to provide external network access for the virtual machines.  If I wanted to isolate a couple VM's from the rest, I could easily create a new bridge interface, and tell QEMU to hook them up to that instead of br0.
In your case, based on the tags for the question, you appear to want to use VirtualBox, which has similar functionality to this with it's 'Internal Network' and 'Host-only' adapters.  The first one works just like the bridge setup I talked about above, except VirtualBox itself provides the bridge instead of the OS doing so, and it provides the option of acting as a DHCP server.  The second one is literally a point-to-point link between the VM and the Host system.  it's not very useful for low-level configuration experiments, but is wonderfully useful for experimenting with VPN's (because the link only goes to the host, you can be certain that any two VM's are only talking over a VPN link).
Now, while all this will work just fine for experimenting with networking configuration, it isn't exactly the most efficient option.  Depending on the exact specifics of the type of experimentation you want to do, you may find that either Open vSwitch or ns-3 are a better fit for what you want to do.

A: VirtualBox will do that nicely.  You'll want to use "host only" network type or "internal only".
Host only - creates a virtual NIC on your machine, attaches it to a virtual switch that the VM(s) attach to as well.  You can have multiples on different subnets, etc.
Internal only - creates a virtual switch that the VM(s) connect to.  No connection to your host.  You can create multiple, and they aren't connected to each other, can be same subnet or different subnets.
What I would recommend is a VM with 2+ interfaces on it, one on a host-only network (so your desktop/laptop can connect to it) and the others on different internal-only networks.  Set the VM up as a router/bridge between your host and the internal-only network(s), create multiple machines on each internal only network.
I've done this (using a bridge interface instead of host only so my private networks could use internet) and have had 12 vms going on 3 different subnets with routing between them all and fake DNS and email and ... all set up.  Great way to learn and experiment.


text:
Q: .Net Core 3.1 Controller result ignore certain properties if null and not requested Lets say we have a data structure like this:
public class Foo
{
  public string Name {get; set;}
  public Bar Bar {get; set;}
}
public class Bar
{
  public string Data {get; set;}
  public string Format {get; set;}
}

Now in controller trough the API the end user can request Bar data but it's not mandatory (lets say its super expensive to retrieve).
if Bar isn't requested I want the result to be like this
{
  "Name": "Test"
}

If we were to request also Bar in the result and lets say it is null, I would like to return something like this.
{
  "Name": "Test",
  "Bar": {
     "Data": null,
     "Format": null
  }
}

Is this possible in .Net Core 3.1?

A: 1 way is to use custom converter for your Foo class. example something like this
public class FooJsonConverter : JsonConverter<Foo>
{
    public override Foo Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }

    public override void Write(Utf8JsonWriter writer, Foo value, JsonSerializerOptions options)
    {
        writer.WriteStartObject();

        writer.WriteString("Name", value.Name);
        writer.WritePropertyName("Bar");
        if (value.Bar == null)
        {
            value.Bar = new Bar();

        }
        JsonSerializer.Serialize(writer, value.Bar, options);
        writer.WriteEndObject();
    }
}

then you can use the custom converter in mvc with these option
services.AddControllers().AddJsonOptions(options => {
            options.JsonSerializerOptions.Converters.Add(new FooJsonConverter());
        });

A: You will have to use jtoken , Convert the object into JToken, RemoveEmptyChildren function will recursive called to find out empty properties and only load properties with value in jobject link


text:
Q: Что за ошибка Firefox can't establish a connection to the server? пытаюсь реализовать websocket для этого нашел вот это закачал запускаю получаю такой ответ Firefox can't establish a connection to the server at ws://127.0.0.1:8004/userId=2651.
 ws = new WebSocket("ws://127.0.0.1:8004/userId=" + Math.round(Math.random()*1000...

вот реализация
$
(function(){
                document.cookie = '';
                function wsStart() {
                    ws = new WebSocket("ws://127.0.0.1:8004/userId=" + Math.round(Math.random()*10000));
                    ws.onopen = function() { $("#chat").append("
система: соединение открыто
"); };
                    ws.onclose = function() { $("#chat").append("
система: соединение закрыто, пытаюсь переподключиться
"); setTimeout(wsStart, 1000);};
                    ws.onmessage = function(evt) { $("#chat").append("
"+evt.data+"
"); $('#chat').scrollTop($('#chat')[0].scrollHeight);};
                }
                wsStart();
                $('#chat').height($(window).height() - 80);
                $('#input').focus();

ругается на эту строку
ws = new WebSocket("ws://127.0.0.1:8004/userId=" + Math.round(Math.random()*10000));

вот картинка

A: Эта ошибка означает что Firefox не смог установить соединение. Причиной может быть либо то, что вы неверно указали порт, либо запрет на доступ к этому порту.
Соответственно вам нужно проверить что у вас сервер запущен именно на указаном порту и что ваш файрвол не запрещает вам обращаться к этому порту.


text:
Q: Triggering event after preventDefault() doesn't work as expected $(document).on('click', '[data-toggle="if-exist"]', function (e, options) {
    options = options || {};

    if (options.fileExist) {
        return true;
    }

    var target = e.currentTarget;
    var fileId = $(this).data('file');
    e.preventDefault();

    $.ajax({
        url: Routing.generate('checkFile', {file: fileId }),
        type: 'HEAD',
        statusCode: {
            404: function () {
                alert('File does not exist');
            },
            200: function () {
                $(target).trigger('click', { 'fileExist': true });
            }
        }
    });
});

When clicking the button the HEAD request is send and when I've got 200 response than the click event is triggered again but this time with fileExist option. Listener is called again (I checked this) but nothing happens, it's like e.preventDefault() would still working. Any ideas?
Solution
trigger() method will trigger jQuery event, but will not trigger default behaviour for a browser, which in my case is redirecting to another page. This code works:
$(document).on('click', '[data-toggle="if-exist"]', function (e) {
    var target = this;
    var fileId = $(this).data('file');
    e.preventDefault();

    $.ajax({
        url: Routing.generate('checkFile', { file: fileId }),
        type: 'HEAD',
        statusCode: {
            404: function () {
                alert('File does not exist');
            },
            200: function () {
                var event = document.createEvent('MouseEvents');
                event.initEvent('click', false, false);
                target.dispatchEvent(event);
            }
        }
    });
});

A: use e.stopImmediatePropagation(); to stop multiple calls of ajax.


text:
Q: Image preview before uploading image jquery Is there any way to implement the fileReader() in IE. i searched a lot but didn't find any solution. This my code where i am trying to implement it. It's working fine in firefox and in chrome but it isn't workink in IE8 and IE9.
<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
        <script>
        function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {
                    $('#img_prev')
                        .attr('src', e.target.result)
                        .width(150)
                        .height(200);
                };

                reader.readAsDataURL(input.files[0]);
            }
        }
        </script>

        <meta charset=utf-8 />
        <title>JS Bin</title>
        <!--[if IE]>
        <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <style>
        article, aside, figure, footer, header, hgroup,
        menu, nav, section { display: block; }
        </style>
    </head>
    <body>
        <input type='file' onchange="readURL(this);" />
        <img id="img_prev" src="#" alt="your image" />
    </body>
</html>

A: yeah i got only one solution. IE 9 don't support File Reader so we can disable image preview for file reader for rest browsers it will work perfectly.


text:
Q: Insert acontecendo várias vezes no banco de dados Tenho um código que faz uma inserção no banco de dados porém, no banco de dados está inserindo vários registros de uma vez só
Segue código:
if($_GET["act"] == ("cad_master")) {
  $startaction = 20;
}

 $pega_id_viagem_unique = $_GET['id_trip_unique'];
 $id_user_logado = $_SESSION['ID'];

if($startaction == 20){

  if($act = "cad_master") {
    $upper = implode('', range('A', 'Z')); // ABCDEFGHIJKLMNOPQRSTUVWXYZ
    $lower = implode('', range('a', 'z')); // abcdefghijklmnopqrstuvwxyzy
    $nums = implode('', range(0, 9)); // 0123456789

    $alphaNumeric = $upper.$lower.$nums; // ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
    $string = '';
    $len = 30; // numero de chars
    for($i = 0; $i < $len; $i++) {
            $string .= $alphaNumeric[rand(0, strlen($alphaNumeric) - 1)];
    }

    $master = $_POST['Master'];
    $booking = $_POST['Booking'];
    $direcao = $_POST['Direcao'];
    $pre_alerta = $_POST['Pre_alerta'];
    $tipo_documento = $_POST['Tipo_documento'];
    $local_emissao = $_POST['Local_emissao'];

    $select_trip = mysql_query("SELECT * FROM Viagens WHERE ID_Unique='$pega_id_viagem_unique'");
    while($ln = mysql_fetch_array($select_trip)) {
        $show_id_viagem = $ln['ID'];
    }
    $insert_master = mysql_query("INSERT INTO `Masters`(`ID_Unique`, `ID_User`, `Master`, `ID_Viagem`, `ID_Viagem_Unique`, `Booking`, `Direcao`, `Pre_alerta`, `Tipo_documento`, `Local_emissao`) VALUES('".$string."', '".$id_user_logado."', '".$master."', '".$show_id_viagem."', '".$pega_id_viagem_unique."', 'Booking', '".$direcao."', '".$pre_alerta."', '".$tipo_documento."', '".$local_emissao."')");

  }
}

Está inserindo 4 registros de uma vez só no banco de dados.


text:
Q: Return vector from function without it being destroyed I have come across an interesting problem. I have a function in C++ that returns a vector filled with classes. Once the vector is returned, it calls deconstructors for each class that is element in the vector.
The problem is an obvious one: the data is destroyed where a class points to the pointers, which get released when the object is destroyed. I can only assume the deconstructors are called because the vector is on the stack, and not on the heap.
So the question is:
Is there anyway to keep returning vector from a function, without it being destroyed? Or would I have to either pass a pointer to return vector as an input to the function?

A: You can create anything on heap with new. You shouldn't give out from the function the references to your stack objects, as they will be destroyed as soon as the function finishes.
If you prefer your function to return the vector by value, be sure that the objects inside the vector implement copy constructor (and perhaps assignment operator, too, not sure about that). Having that, please do not forget about the Rule of Three.

A: C++11 should solve your problem using rvalue references. Honestly, I haven't tried it myself, but from what I read it will do exactly what you are trying to do, return the vector without destroying and recreating it (by passing the memory allocated by that vector on to the new vector instead of having the new vector create its own memory and copy the contents over from the old one).

A: C++ vectors are allocated on the heap. When you return a vector by value a new one will be created with copies of all the elements, then the original elements will be destroyed.
It sounds like you haven't defined your copy constructors properly. For example:
class ThisIsWrong
{
public:
    ThisIsWrong()
    {
        i = new int;
        *i = rand();
    }
    ~ThisIsWrong()
    {
        delete i;
        i = nullptr;
    }

    int value() const
    {
        return *i;
    }

private:
    int* i;
};

void foo()
{
    vector<ThisIsWrong> wronglets;
    wronglets.push_back(ThisIsWrong());
    return wronglets;
}

void main()
{
    vector<ThisIsWrong> w = foo();
    w[0].value(); // SEGFAULT!!
}

You either need to delete the copy and assignment constructors (which will then turn this into a compilation error instead of runtime), or implement them properly.


text:
Q: Hide Dialog from inside in LWUIT I have created a Dialog with two buttons Yes, No, and then I have add action listener to them, my problem is that I want no button to hide the Dialog that I have created
the code is looks like:
dialog = new Dialog(title);
        dialog.setDialogType(Dialog.TYPE_CONFIRMATION);

        ta = new TextArea(text);
        ta.getStyle().setBorder(Border.createEmpty());
        ta.setEditable(false);
        yesCommand = new Button("YES");
        noCommand = new Button("NO");

        yesCommand.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                LGBMainMidlet.getLGBMidlet().notifyDestroyed();
            }
        });

        noCommand.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                Logger.Log("Bye Bye");
                dialog = null;
                System.gc();
            }
        });

        dialog.addComponent(ta);
        dialog.addComponent(yesCommand);
        dialog.addComponent(noCommand);
        dialog.show();

the code is not working for me, can anyone told me what is the problem?
B.N. I have used dialog.dispose(), but it exit the whole application

A: It is better to use
dialog.setTimeout(1000); the number show the time limit the dialog box wait in milliseconds. So by doing this you can exit the dialog form automatically.

A: Dialog.dispose() does not exit the whole application, it just closes the dialog.
If you have nothing in your application you might see nothing if you dispose the dialog.


text:
Q: Multi-tenancy with a separate database per customer, using Spring Data ArangoDB So far, the only way I know to set the name of a database, to use with Spring Data ArangoDB, is by hardcoding it in a database() method while extending AbstractArangoConfiguration, like so:
@Configuration
@EnableArangoRepositories(basePackages = { "com.company.mypackage" })
public class MyConfiguration extends AbstractArangoConfiguration {

  @Override
  public ArangoDB.Builder arango() {
    return new ArangoDB.Builder();
  }

  @Override
  public String database() {
    // Name of the database to be used
    return "example-database";
  }

}

What if I'd like to implement multi-tenancy, where each tenant has data in a separate database and use e.g. a subdomain to determine which database name should be used?
Can the database used by Spring Data ArangoDB be determined at runtime, dynamically?
This question is related to the discussion here: Manage multi-tenancy ArangoDB connection  - but is Spring Data ArangoDB specific.

A: Turns out this is delightfully simple:  Just change the ArangoConfiguration database() method @Override to return a Spring Expression (SpEL):
    @Override
    public String database() {
        return "#{tenantProvider.getDatabaseName()}";
    }

which in this example references a TenantProvider @Component which can be implemented like so:
@Component
public class TenantProvider {

    private final ThreadLocal<String> databaseName;

    public TenantProvider() {
        super();
        databaseName = new ThreadLocal<>();
    }

    public String getDatabaseName() {
        return databaseName.get();
    }

    public void setDatabaseName(final String databaseName) {
        this.databaseName.set(databaseName);

    }
}

This component can then be @Autowired wherever in your code to set the database name, such as in a servlet filter, or in my case in an Apache Camel route Processor and in database service methods.
P.s. I became aware of this possibility by reading the ArangoTemplate code and a Spring Expression support documentation section
 (via), and one merged pull request.


text:
Q: segfault at 0 ip (null) error 14 when trying to access an array of structs using copy_to_user function Please bear with it's been a while since I programmed in C.  I'm trying to move an array of structs from kernel space into user space.  Below is the error that I'm seeing in /var/log/kern.log:
userspace[5091]: segfault at 0 ip           (null) sp 00007fff21250d00 error 14 in userspace[400000+5000]`.

The flow of my code is declaring an array of structs on the user side passing that address to the kernel side.  From the kernel side using that user space address I copy an array of structs to that user space address.  Then back in user space I try to iterate through and print the values from that array of structs.  That's where I get a seg fault.
header.h
#define MAX_CONTS             100

typedef struct cont_struct {
   int id;
   u32 pid;
} __attribute__((packed)) cont_struct;

userspace.c
 include "header.h"

 cont_struct conts[MAX_CONTS];
 //cont_struct *conts = (cont_struct *)malloc(MAX_CONTS * sizeof(cont_struct));
 memset(conts, 0, sizeof(conts));

I pass the value of conts to the kernel side using the proc file system.  I have verified that it is correctly passed.  Below is the kernel code where I try to copy an array of structs to user space using the copy_to_user function.  conts is the user space address.
kernelspace.c
 include "header.h"

 cont_struct kern_conts[MAX_CONTS];
 kern_conts[0].pid = 111;
 kern_conts[0].id = 1;
 kern_conts[1].pid = 222;
 kern_conts[1].id = 2;

 // conts is the value passed from userspace
 if ( copy_to_user((void *)conts, kern_conts, sizeof(conts)) ){
     printk("error\n);
 }

Later on I call the code below in user space to iterate through array of structs to print off the values.  Even when I set the end condition of the for loop to lower than 100 it still seg faults.  It is also garbage values so I'm pretty sure it's not copying the data correctly.
userspace.c
//by this point I hope the array of structs has been properly copied from kernel space to user space
for (size_t i = 0 ; i < MAX_CONTS; i++)
    {
     fprintf(fout, "id: %u pid: %u\n", conts[i].id, conts[i].pid);
   }

My first question is that am I declaring the arrays of struct correctly?  I've seen stuff on this forum where people are using the malloc method when working with arrays of structs.  I've tried both ways of declaration on each side but that didn't work either.  The array of structs is populated/manipulated on the kernel side.  Later on in the client side when I try to iterate through and print the values, at the end of iterating through the array it throws the error mentioned above.  Any help is greatly appreciated!


text:
Q: How to keep the state of keyboard same of previous activity? In my activity I have a list of images and one EditText. When I click the image, I use intent to display image in fullscreen activity. when I press the back button the keyboard does not in the same state. I mean when hide the keyboard it displays on its own. Please help me how to maintain the state of keyboard. Thanks in advance.

A: Put focus on edit text again when activity resumes again after back press in full screen image view.

A: save the state of keyboard on a class field boolean. than onresume of the previous actvity you set the keyboard to shown or hidden depending on the saved value.


text:
Q: Django rest-framework + polymorphic: serialize a list of URLs The relevant parts of my model:
class Item(PolymorphicModel):
    rating = models.DecimalField(default=0.0, max_digits=5, decimal_places=2)
    picture = models.URLField(max_length=200)
    category = models.ForeignKey('Category', related_name='items')
    # url_list

class Movie(Item):
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=2000)
    ...

I would like to have a list of urls in the Item class. This list should be serialized in the movie object serializer.
So far I tried to create a model to represent a URL this way:
class Url(models.Model):
    url = models.URLField(max_length=200)
    item = models.ForeignKey('Item', related_name='pictures')

But I get an empty list when a movie is serialized. My Serializers are:
class UrlSerializer(serializers.ModelSerializer):

    class Meta:
        model = ScrollerPictureUrl
        fields = ('url',)

class MovieSerializer(serializers.ModelSerializer):
    urls = UrlSerializer(many=True)

    class Meta:
        model = Movie
        exclude = ('polymorphic_ctype', 'category')

I need to know how to serialize the url list for the Movie object so that it's not empty.

A: That's what I did finally:
class MovieSerializer(serializers.ModelSerializer):
    urls = serializers.SlugRelatedField(many=True, slug_field='url')

    class Meta:
        model = Movie
        exclude = ('polymorphic_ctype', 'category')


text:
Q: Public folder permission in Rails project In my Rails project, I noticed that when I put some files into my public folder, such as .html, .pdf, .jpg, they can be opened via a browser. But when I put other files, such as .txt or files with no file type, permission is denied.
Forbidden

You don't have permission to access /blog/public/test.txt on this server.

Where is this permission controlled?
Actually, it's interesting that the file robots.txt, which came automatically when the Rails project was set up, can be accessed! But test.txt, which I created, cannot be accessed.

A: I guess it is the asset pipeline which allows the html, css and js files only...

A: Try restart the server and see if it works. It usually works in rails 3 like breeze, but you might be on an older version of rails.


text:
Q: Execl error debuging Aim
My objective is to create a simple frontend to pandoc. I have learned that execl is a good way of calling executables in the system.
Note in the following code the function btn_pressed, that calls pandoc using the mentioned method.
[indent=4]
uses
    Posix
    Gtk

class TestWindow:Window
    _file_chooser:FileChooserButton
    _entry:Gtk.Entry
    _button:Gtk.Button
    _file:File

    construct()
        title = "Pandoc GUI"
        window_position = WindowPosition.CENTER
        destroy.connect( Gtk.main_quit )
        var folder_chooser = new FileChooserButton("Choose a Folder",FileChooserAction.SELECT_FOLDER)
        folder_chooser.set_current_folder( Environment.get_home_dir() )

        //I used selection_changed directly as per the question in stack_exchange
        //http://stackoverflow.com/questions/34689763/the-signal-connect-syntax
        folder_chooser.selection_changed.connect( folder_changed )

        _file_chooser = new FileChooserButton("Choose a File",FileChooserAction.OPEN)
        _file_chooser.set_current_folder( Environment.get_home_dir() )

        _file_chooser.file_set.connect( file_changed )
        _entry = new Gtk.Entry()
        _entry.set_text("Here the file name")

        _button = new Button.with_label("Convert to pdf")
        _button.set_sensitive(false)
        _button.clicked.connect(btn_pressed)

        var box = new Box( Orientation.VERTICAL, 0 )
        box.pack_start( folder_chooser, true, true, 0 )
        box.pack_start( _file_chooser, true, true, 0 )
        box.pack_start( _entry, true, true, 0 )
        box.pack_start( _button, true, true, 0 )
        add( box )

    def folder_changed( folder_chooser_widget:FileChooser )
        folder:string = folder_chooser_widget.get_uri()
        _file_chooser.set_current_folder_uri( folder )

    def file_changed ( file_chooser_widget: FileChooser )
        _file = File.new_for_uri(file_chooser_widget.get_uri())

        try
            info:FileInfo = _file.query_info (FileAttribute.ACCESS_CAN_WRITE, FileQueryInfoFlags.NONE, null)
            writable: bool = info.get_attribute_boolean (FileAttribute.ACCESS_CAN_WRITE)
            if !writable
                _entry.set_sensitive (false)
            else
                _button.set_sensitive (true)
        except e: Error
            print e.message

        _entry.set_text(_file.get_basename())

    def btn_pressed ()
        var md_name=_entry.get_text()+".md -s -o "+_entry.get_text()+".pdf"
        execl("/usr/bin/pandoc", md_name)
        _button.set_sensitive (false)

init
    Gtk.init( ref args )
    var test = new TestWindow()
    test.show_all()
    Gtk.main()

Error
At execution I get no response at all from my code, without any pdf being rendering as well.
Question

*

*How to debug the execution of a binary with execl?

A: I would use GLib.Subprocess to call external commands because it provides better control over the input to and output from the external command. Changing the example below to execl should be easy enough though.
The first thing is to de-couple your external command from your window object. This makes it more testable. To do this a separate object is used - a wrapper around the Subprocess call. Save this code as ToPDF.gs:
namespace FileConverters

    class ToPDF

        const _command:string = "pandoc"

        def async convert( source:string, output:string )
            try
                var flags = SubprocessFlags.STDOUT_PIPE \
                            | SubprocessFlags.STDERR_PIPE
                var subprocess = new Subprocess( flags,
                                                 _command,
                                                 source,
                                                 output
                                                )
                output_buffer:Bytes
                yield subprocess.communicate_async( null,
                                                    null,
                                                    out output_buffer,
                                                    null
                                                   )
                if ( subprocess.get_exit_status() == 0 )
                    debug( "command successful: \n %s",
                           (string)output_buffer.get_data()
                          )
                else
                    debug( "command failed" )
            except err:Error
                debug( err.message )

The ToPDF class is now de-coupled from the rest of your application. This means it can be re-used. To illustrate this an integration test is shown below that uses the class.
The ToPDF also uses asynchronous code. So I will explain that first. Making a method asynchronous means it will run concurrently with the main thread of the application. By have a call to an external program run concurrently it means the main thread doesn't lock up while it is waiting for the external program to finish. Using async means the function is split in two. The first part is called with convert.begin( source, output ) and will run up to the yield command. At that point the execution of the program splits in two. The main thread will return to the caller of convert.begin, but what has started in the background is the Subprocess. When the Subprocess finished it returns to convert and finishes the method call.
Save the integration test as ToPDFTest.gs:
uses FileConverters

init
    var a = new ToPDF()
    a.convert.begin( "source_file.md", "output_file.pdf" )

    var loop = new MainLoop()
    var loop_quitter = new LoopQuitter( loop )
    Timeout.add_seconds( 2, loop_quitter.quit )
    loop.run()

class LoopQuitter
    _loop:MainLoop

    construct( loop:MainLoop )
        _loop = loop

    def quit():bool
        _loop.quit()
        return false

Compile with valac --pkg gio-2.0 ToPDF.gs ToPDFTest.gs
Then run the test with G_MESSAGES_DEBUG=all ./ToPDFTest
The test uses MainLoop, which is the base class of Gtk.Main. To simulate a long running program a two second timeout is set then MainLoop.quit() is called to end the test. Unfortunately MainLoop.quit() doesn't have the right function signature for a Timeout callback so a wrapper class, LoopQuitter is used.
Integration tests like this are often kept and run before a software release to ensure the application is working with other software modules.
To integrate ToPDF with your window you need to change
execl("/usr/bin/pandoc", md_name)
to something like
var to_pdf = new Fileconverts.ToPDF()
to_pdf.convert.begin( md_name, pdf_name )

You may also want to wrap it in a command pattern similar to Avoiding global variables in Genie . You may also want to modify it to provide better feedback to the user.


text:
Q: Where can I download truck dataset I am looking for truck GPS data. Could you please guide me on how I can download a free resource to download?
I need a dataset with at least 10000 records containing time, latitude, and longitude.


text:
Q: Identities for powers of functions based on generalization of Lagrange interpolation Lagrange polynomial can be used to obtain an identity:
$$(k+t)^n = \sum_{i=0}^n (k+d_i)^n \prod_{\substack{j=0\\ j\not=i}}^n \frac{t-d_j}{d_i-d_j},$$
which holds for any integer $n>0$, any real numbers $k,t$, and any distinct real numbers $d_0,\dots,d_n$. The key idea is that the difference between the left-hand and right-hand sides represents a polynomial of degree $\leq n$ in $t$, while it has $n+1$ zeros $d_0,\dots,d_n$. The fundamental theorem of algebra then implies that this polynomial is zero.
The same identity can restated in terms of function $f(t)=t$ as
$$(\star)\qquad f(k+t)^n = \sum_{i=0}^n f(k+d_i)^n \prod_{\substack{j=0\\ j\not=i}}^n \frac{f(t-d_j)}{f(d_i-d_j)}.$$

Recently I learned that the identity $(\star)$ holds for (non-polynomial) function $f(t)=U_t=U_t(P,Q)$ being Lucas sequence (equivalently, $U_t=\frac{a^t-b^t}{a-b}$, where $a,b$ are the zeros of the characteristic polynomial, which enables real values for $t$). That is,
$$U_{k+t}^n=\sum_{i=0}^{n} U_{k+d_i}^n\prod_{\substack{j=0\\ j\not=i}}^{n}\frac{U_{t-d_j}}{U_{d_i-d_j}},$$
where again $n>0$ is integer, $k,t$ are any real numbers, and $d_0,\dots,d_n$ are any  distinct real numbers.
What would be the analog of the fundamental theorem of algebra here?
As pointed out by Fedor Petrov, the difference here represents a polynomial of degree $\leq n$ in $(a/b)^t$, and the same arguments hold.

What would be other interesting examples of $f(t)$, for which the identity $(\star)$ holds?


text:
Q: An unhandled exception occurred while processing the request in ASP Net. Core while trying to access the page which controller created I get this error:

InvalidOperationException: Unable to resolve service for type 'CRM.Models.CRMDBContext' while attempting to activate 'CRM.Controllers.KontaktiesController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method10(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0.<CreateActivator>b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.<Invoke>g__AwaitMatcher|8_0(EndpointRoutingMiddleware middleware, HttpContext httpContext, Task<Matcher> matcherTask)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)


text:
Q: Group contours with the same y value I have been following a tutorial about computer vision and doing a little project to read the time from a game. The game time is formatted h:m. So far I got the h and m figured out using findContours, but I'm having trouble isolating the colon as the character shape is not continuous. Because of this when I try to matchTemplate the code freaks out and starts to use the dot to match to all the other digits.
Are there ways to group the contours by X?
Here are simplified code to get the reference digits, the code to get digits from the screen is basically the same.
    refCnts = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    refCnts = imutils.grab_contours(refCnts)
    refCnts = contours.sort_contours(refCnts, method="left-to-right")[0]

    digits = {}

    # loop over the OCR-A reference contours
    for (i, c) in enumerate(refCnts):
        # compute the bounding box for the digit, extract it, and resize
        # it to a fixed size
        (x, y, w, h) = cv2.boundingRect(c)

        roi = ref[y:y + h, x:x + w]
        roi = cv2.resize(roi, (10, 13))
        digits[i] = roi

Im new to python and opencv. Apologies in advance if this is a dumb question.
Here is the reference image I'm using:

Here is the input image I'm trying to read:

A: Do you have to use findCountours? Because there are better suited methods for such problems. For instance, you can use template matching as shown below:
These are input, template (cut out from your reference image), and output images:

import cv2
import numpy as np

# Read the input image & convert to grayscale
input_rgb = cv2.imread('input.png')
input_gray = cv2.cvtColor(input_rgb, cv2.COLOR_BGR2GRAY)

# Read the template (Using 0 to read image in grayscale mode)
template = cv2.imread('template.png', 0)

# Perform template matching - more on this here: https://docs.opencv.org/4.0.1/df/dfb/group__imgproc__object.html#ga3a7850640f1fe1f58fe91a2d7583695d
res = cv2.matchTemplate(input_gray,template,cv2.TM_CCOEFF_NORMED)

# Store the coordinates of matched area
# found the threshold value of .56 using trial & error using the input image - might be different in your game
lc = np.where( res >= 0.56)

# Draw a rectangle around the matched region
# I used the width and height of the template image but in practice you need to use a better method to accomplish this
w, h = template.shape[::-1]
for pt in zip(*lc[::-1]):
    cv2.rectangle(input_rgb, pt, (pt[0] + w, pt[1] + h), (0,255,255), 1)

# display output
cv2.imshow('Detected',input_rgb)
# cv2.imwrite('output.png', input_rgb)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

You may also look into text detection & recognition using openCV.


text:
Q: how to change code from onOpen with menu to onEdit I am trying to change the following code so that it operates onEdit instead of onOpen and creating a menu.  I just want the information auto populated when ISBN is entered into the "A" column.
s = SpreadsheetApp.getActiveSheet();

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Book Menu')
      .addItem('Get Book Details', 'getBookDetails')
      .addToUi();
}

function getBookDetails(isbn) {

  // Query the book database by ISBN code.
  activeCell = s.getActiveCell();
  value = activeCell.getValue();
  isbn = isbn || value.toString(); // Steve Jobs book

  // Not a valid ISBN if not 13 or 10 digits long.
  if(isbn.match(/(\d{13}|\d{10})/) == null){
    throw new Error( "Not a valid ISBN: " + isbn);
  }
  var url = "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn;
  var response = UrlFetchApp.fetch(url);
  var results = JSON.parse(response);
  if (results.totalItems) {

    // There'll be only 1 book per ISBN
    var book = results.items[0];

    var title = (book["volumeInfo"]["title"]);
    var subtitle = (book["volumeInfo"]["subtitle"]) || "*No Subtitle";
    var authors = (book["volumeInfo"]["authors"]);
    var printType = (book["volumeInfo"]["printType"]);
    var pageCount = (book["volumeInfo"]["pageCount"]);
    var publisher = (book["volumeInfo"]["publisher"]);
    var publishedDate = (book["volumeInfo"]["publishedDate"]);
    var webReaderLink = (book["accessInfo"]["webReaderLink"]);

    //Logger.log(book);
    results = [[title, subtitle, authors, printType, pageCount, publisher, publishedDate, webReaderLink]];

  }else{
    results = [["-", "-", "-", "-", "-", "-", "-", "-"]];
  }
  s.getRange(activeCell.getRow(), activeCell.getColumn() + 1, 1, results[0].length).setValues(results);
}


text:
Q: Average non-null values I have the following query:
>>> ItemMaster.objects.all()[:3].values_list('rt_rating', 'imdb_rating')
[(None, None), (None, Decimal('6.3')), (Decimal('7.6'), Decimal('7.4'))]

What would be the best way to get the average of the above non-null values? For the above it would be (6.3 + 7.6 + 7.4) / 3.

A: You can filter your result with a list comprehension, then use sum and len to calculate the average :
>>> li=[(None, None), (None, Decimal('6.3')), (Decimal('7.6'),
>>> nums=[j for tup in li for j in tup if j]
>>> av=sum(nums)/len(nums)

A: You can do it all in python3 using filter, chain and statistics.mean:
from decimal import Decimal
from statistics import mean
from itertools import chain

l = [(None, None), (None, Decimal('6.3')), (Decimal('7.6'), Decimal('7.4'))]

print(mean(filter(None.__ne__,chain.from_iterable(l))))
7.1

None.__ne__ would mean you keep Decimal('0') which may or may not be what you want.

A: You can user itertools.chain to get all the non-Null items and then filter to remove the Null items --
from itertools import chain

items = filter(None, list(chain(*ItemMaster.objects.all()[:3].values_list('rt_rating', 'imdb_rating'))))
==> [Decimal('6.3'), Decimal('7.6'), Decimal('7.4')]
sum(items)/len(items)
==> Decimal('7.1')


text:
Q: Default Wordpress WP Editor removing style tags and html tag I am working inside the WP Admin area and there is a textarea that is using the default WP Editor, not TinyMCE.  The WP Editor is removing the <style> tag and also other HTML tags.  I am calling it WP Editor, but maybe it's official know as something different?  It's the editor with the two tabs in the right corner (Visual,Text)
Is there a way to prevent this Editor from removing all HTML tags?
The content I am adding in the WP Editor is being used in outgoing emails so it's really a full HTML document which is why I am trying to preserve the formatting and html tags.
I notice when I switch from the "Text" tab to the "Visual" tab many HTML tags are stripped.

A: WordPress has a user capability called unfiltered_html. Any user with the unfiltered_html capability can post any HTML they want, including <script> tags.
Due to security concerns, the unfiltered_html capability is—by default—only granted to Administrators (in WordPress Multisite, it's only granted to Super Administrators).
If you need to add the unfiltered_html capability to a non-(Super-)Admin user, you can use WP_User::add_cap() to add it to a user:
add_action( 'admin_init', 'wpse_393657_grant_user_unfiltered_html' );
function wpse_393657_grant_user_unfiltered_html() {
    $user = get_user_by( 'login', 'my_username' );
    if ( ! user_can( $user, 'unfiltered_html' ) ) {
        $user->add_cap( 'unfiltered_html', true );
    }
}

...or WP_Role::add_cap() to add it to a Role (eg, Editor).
add_action( 'admin_init', 'wpse_393657_grant_role_unfiltered_html' );
function wpse_393657_grant_role_unfiltered_html() {
    $role = get_role( 'editor' );
    if ( ! $role->has_cap( 'unfiltered_html' ) ) {
        $role->add_cap( 'unfiltered_html', true );
    }
}

(These code snippets are untested, and are meant to provide a starting point for you.)
Note that the capability assignments are permanent (ie, written to the database), and that the user or role will retain the unfiltered_html capability until/unless you revoke it.


text:
Q: Reading unique data from mysql table Let's say I have a table which can contains data like this:
id     name      class
--     ----      ------
 1    Joshua      math
 2     Mary      history
 3     Mary      chemistry
 4     Matt      physics

As you can see, for "Mary", we have two classes "history" and "chemistry". How do I (with php or and SQL statement) get the data for "Mary" and return it like this:
Mary, history, chemistry

In other words, I want to get all the data in the table and return them like this:
Josuha, math
Marry, history, chemistry
Matt, physics

So whenever a user appears multiple times in the table, I get all his/her data in one line.

A: Use MySQL's GROUP_CONCAT() aggregate function.


text:
Q: obtain the matrix in protege My work is about library book of recommendation systems . that as input I need book Classification ontology . in my ontology classify library books. this classification has 14 categories, beside the sibling classes Author, book, Isbn. Individuals in book class are book's subject(about 600 subjects) , and individuals in author class are name's author and also isbn class. I design this ontology with protege 4.1.
also I collected and Have got in part of belong book to categories manually. That a object properties is name "hasSubject" related individual book class with categories. Example book "A" hasSubject Categories "S" and "F" and... As result I want to get the matrix belonging to Book Categories. This is the way that if the book belongs to a categories then get 1 and Otherwise Takes the value 0. Like this:
     cat1   cat2   cat3
book1   1      0      0
book2   1      0      1
book3   1      1      0

In this example Expresses that book1 belong to category 1 and Does not belong category 2 and 3. How can I do this work with sparql in protege?

A: Handling a fixed number of categories
Given data like
@prefix : <http://example.org/books/> .

:book1 a :Book, :Cat1 .
:book2 a :Book, :Cat1, :Cat3 .
:book3 a :Book, :Cat1, :Cat2 .

you can use a query like
prefix : <http://example.org/books/>

select ?individual
       (if(bound(?cat1),1,0) as ?Cat1)
       (if(bound(?cat2),1,0) as ?Cat2)
       (if(bound(?cat3),1,0) as ?Cat3)
where {
  ?individual a :Book .
  OPTIONAL { ?individual a :Cat1 . bind( ?individual as ?cat1 ) }
  OPTIONAL { ?individual a :Cat2 . bind( ?individual as ?cat2 ) }
  OPTIONAL { ?individual a :Cat3 . bind( ?individual as ?cat3 ) }
}
order by ?book

in which certain variables are bound (the particular value to which they are bound doesn't really matter though) based on the whether certain triples are present to get results like these:
$ arq --data data.n3 --query matrix.sparql
-----------------------------------
| individual | Cat1 | Cat2 | Cat3 |
===================================
| :book1     | 1    | 0    | 0    |
| :book2     | 1    | 0    | 1    |
| :book3     | 1    | 1    | 0    |
-----------------------------------

Handling an arbitrary number of categories
Here's a solution that seems to work in Jena, though I'm not sure that the specific results are guaranteed. (Update: Based on this answers.semanticweb.com question and answer, it seems that this behavior is not guaranteed by the SPARQL specification.) If we have a little bit more data, e.g., about which things are categories and which are books, e.g.,
@prefix : <http://example.org/books/> .

:book1 a :Book, :Cat1 .
:book2 a :Book, :Cat1, :Cat3 .
:book3 a :Book, :Cat1, :Cat2 .

:Cat1 a :Category .
:Cat2 a :Category .
:Cat3 a :Category .

then we can run a subquery that selects all the categories in order, and then for each book computes a string indicating whether or not the book is in each category.
prefix : <http://example.org/books/>

select ?book (group_concat(?isCat) as ?matrix) where {
  {
    select ?category where {
      ?category a :Category
    }
    order by ?category
  }
  ?book a :Book .
  OPTIONAL { bind( 1 as ?isCat )              ?book a ?category . }
  OPTIONAL { bind( 0 as ?isCat ) NOT EXISTS { ?book a ?category } }
}
group by ?book
order by ?book

This has the output:
$ arq --data data.n3 --query matrix2.query
--------------------
| book   | matrix  |
====================
| :book1 | "1 0 0" |
| :book2 | "1 0 1" |
| :book3 | "1 1 0" |
--------------------

which is much closer to the output in the question, and handles an arbitrary number categories.  However, it depends on the values of ?category being processed in the same order for each ?book, and I'm not sure whether that's guaranteed or not.
We can even use this approach to generate a header row for the table.  Again, this depends on the ?category values being processed in the same order for each ?book, which might not be guaranteed, but seems to work in Jena.  To get a category header, all we need to do is create a row where ?book is unbound, and the value of the ?isCat indicates the particular category:
prefix : <http://example.org/books/>

select ?book (group_concat(?isCat) as ?matrix) where {
  {
    select ?category where {
      ?category a :Category
    }
    order by ?category
  }

  # This generates the header row where ?isCat is just
  # the category, so the group_concat gives headers.
  {
    bind(?category as ?isCat)
  }
  UNION
  # This is the table as before
  {
    ?book a :Book .
    OPTIONAL { bind( 1 as ?isCat )              ?book a ?category . }
    OPTIONAL { bind( 0 as ?isCat ) NOT EXISTS { ?book a ?category } }
  }
}
group by ?book
order by ?book

We get this output:
--------------------------------------------------------------------------------------------------------
| book   | matrix                                                                                |
========================================================================================================
|        | "http://example.org/books/Cat1 http://example.org/books/Cat2 http://example.org/books/Cat3" |
| :book1 | "1 0 0"                                                                                |
| :book2 | "1 0 1"                                                                                |
| :book3 | "1 1 0"                                                                                |
--------------------------------------------------------------------------------------------------------

Using some string manipulation, you could shorten the URIs used for the categories, or widen the array entries to get correct alignment.  One possibility is this:
prefix : <http://example.org/books/>

select ?book (group_concat(?isCat) as ?categories) where {
  {
    select ?category
           (strafter(str(?category),"http://example.org/books/") as ?name)
     where {
      ?category a :Category
    }
    order by ?category
  }

  {
    bind(?name as ?isCat)
  }
  UNION
  {
    ?book a :Book .
    # The string manipulation here takes the name of the category (which should
    # be at least two character), trims off the first character (string indexing
    # in XPath functions starts at 1), and replaces the rest with " ". The resulting
    # spaces are concatenated with "1" or "0" depending on whether the book is a
    # member of the category.  The resulting string has the same width as the
    #  category name, and makes for a nice table.
    OPTIONAL { bind( concat(replace(substr(?name,2),"."," "),"1") as ?isCat )              ?book a ?category . }
    OPTIONAL { bind( concat(replace(substr(?name,2),"."," "),"0") as ?isCat ) NOT EXISTS { ?book a ?category } }
  }
}
group by ?book
order by ?book

which produces this output:
$ arq --data data.n3 --query matrix3.query
-----------------------------
| book   | categories       |
=============================
|        | "Cat1 Cat2 Cat3" |
| :book1 | "   1    0    0" |
| :book2 | "   1    0    1" |
| :book3 | "   1    1    0" |
-----------------------------

which is almost exactly what you had in the question.


text:
Q: Using a default in a case statement in Haskell I am trying to create a new data declaration called place.
It looks like this:
data place = United States | France | England | Germany | Mexico | Canada
My hope is to then use a function called cap to take the place to its capital like so:
cap :: place -> String
cap a = case a of

            Spain           -> "Madrid"
            France          -> "Paris"
            England         -> "London"
            Germany         -> "Berlin"
            Mexico          -> "Mexico City"
            Canada          -> "Ottawa"
            _               -> undefined

However the last case, where I am attempting to catch all other entries that may not exist in the data declaration does not work. If I enter capital Wales for instance in GHCI, I don't get an undefined response. Instead I get a not in scope error. Can someone help me with my confusion and perhaps provide a legitimate way of trying to catch other cases?

A: When you enter capital Wales, there is no Wales in scope.  It is not possible for you to construct a value that does not exist.  If you have covered every possible case, then you do not need a default case.

A: To riff on sepp2k's and singpolyma's answers, the point here is that Haskell's union types are exhaustive.  When you define a union type with n cases, you are telling Haskell that those n cases are the only cases that exist for your type.  As singpolyma points out, you've told Haskell that other cases don't even exist.
This has benefits and drawbacks.  Exhaustiveness means that you and the compiler can guarantee that your functions are handling all possible inputs that they will be given.  The drawback is that the set of cases is fixed at compilation time.
The simplest alternative here is two-part:

*

*Use an "open" type—one for which you can create arbitrarily many different instances at runtime—to represent nations and capitals.  Strings are a good one here; there is an infinite number of different strings that you can construct at runtime.  But you can also use a record type with a string member.

*Use key/value assignment data structures to represent the association between the countries and the capitals.

So you could represent nations and cities like this:
-- Since there are infinitely many different strings you could construct at runtime,
-- there are also infinitely many different Cities and Nations...
data City = City String deriving (Eq, Ord, Show)
data Nation = Nation String deriving (Eq, Ord, Show

The simplest key/value mapping type is [(k, v)], often known as an association list.  It has of course an O(n) lookup time.  A better one is to use Data.Map, which comes with the Haskell Platform.

A: The problem isn't with how you handle missing cases - how you're doing it is fine. The problem is that the Wales constructor simply does not exist. So just like when you try to use a variable or function that has not been defined, you get a compilation error. Your cap function never even gets called, so no changes you could do to it, would affect this behaviour. There's nothing you can do to make code that uses non-existing constructors compile.


text:
Q: How to use line that read from file in grep command I'm sorry for my poor English, first.
I want to read a file (tel.txt) that contains many tel numbers (a number per line) and use that line to grep command to search about the specific number in the source file (another file)!
I wrote this code :
dir="/home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A"
file="$dir/tel.txt"
datafile="$dir/ADSL_CDR_Like_Tct4_From_960501_to_97501_Part0.txt"

while IFS= read -r line
do
    current="$line"
    echo `grep -F $current "$datafile" >> output.txt`
done < $file

the tel file sample :
44001547
44001478
55421487

but that code returns nothing!
when I declare 'current' variable with literals it works correctly!
what happened?!

A: Your grep command is redirected to write its output to a file, so you don't see it on the terminal.
Anyway, you should probably be using the much simpler and faster
grep -Ff "$file" "$datafile"

Add | tee -a output.txt if you want to save the output to a file and see it at the same time.
echo `command` is a buggy and inefficient way to write command.  (echo "`command`" would merely be inefficient.)  There is no reason to capture standard output into a string just so that you can echo that string to standard output.

A: Why don't you search for the line var directly? I've done some tests, this script works on my linux (CentOS 7.x) with bash shell:
#!/bin/bash
file="/home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A/tel.txt"

while IFS= read -r line
do
    echo `grep "$line" /home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A/ADSL_CDR_Like_Tct4_From_960501_to_97501_Part0.tx >> output.txt`
done < $file

Give it a try... It shows nothing on the screen since you're redirecting the output to the file output.txt so the matching results are saved there.

A: You should use file descriptors when reading with while loop.instead use for loop to avoid false re-directions
dir="/home/mujan/Desktop/data/ADSL_CDR_Text_Parts_A"
file="$dir/tel.txt"
datafile="$dir/ADSL_CDR_Like_Tct4_From_960501_to_97501_Part0.txt"

for line in `cat $file`
do
    current="$line"
    echo `grep -F $current "$datafile" >> output.txt`
done


text:
Q: SQL Dynamically generate columns based on a map table I would like to dynamically generate a table based on other mapping table. I have a map table that looks like, this map table is connected to an excel and can be modified by the users adding as many rows as they wish:

Name
ColumnName

banner
banner_flag

pop_up
pop_up_flag

Then I have a source table that looks like:

id
language
transactions
action

01
es-es
0
banner

02
es-mx
0
loggin

03
es-es
1
pop_up

03
es-es
1
banner

03
es-es
1
loggin

03
es-es
1
back_home

04
es-es
0
loggin

04
es-es
0
banner

04
es-es
0
banner

05
es-es
1
loggin

06
es-es
2
loggin

Then the final output would look like:

id
language
transactions
banner_flag
pop_up_flag

01
es-es
0
1
0

02
es-mx
0
0
0

03
es-es
0
1
1

04
es-es
0
2
0

05
es-es
0
0
0

06
es-es
0
0
0

Where the columns associated to the map table are calculated fields that in pseucode would look like:
for x in map_table.ColumnName:
  if x in sourceTable.Column:
    return 1
  else:
    return 0

A: Consider below approach
execute immediate (select '''select * from (
  select id, language, sum(if(action = Name, 0, transactions)) as transactions, ColumnName, countif(action = Name) as flag
  from source_table s
  cross join map m
  group by id, language, ColumnName
)
pivot (sum(flag) for ColumnName in ("''' || list || '''"))
order by id
'''
from (select string_agg(distinct ColumnName, '","') as list from map)
)

if applied to sample data in your question - output is


text:
Q: nav>button - phrasing content where flow content is expected As I've understood from spec, button element can be used, where phrasing content is expected. And content model of nav element is flow content. So why the following markup is valid?
<nav>
    <button class="prev"></button>
    <button class="next"></button>
</nav>

A: Because flow content includes phrasing content; the definition explicitly includes button element.
In HTML 4 (and even in HTML 2), the "strict" version requires that text-level content be wrapped in block-level containers, and "text-level" meant roughly the same as phrasing content. But there is no such requirement in HTML5.


text:
Q: Is there a way to calculate small distances with CoreMotion? Is it possible to calculate small distances with CoreMotion?
For example a user moves his iOS device up or down, left and right and facing the device in front of him (landscape).

A: EDIT
Link as promised...
https://www.youtube.com/watch?v=C7JQ7Rpwn2k position stuff starts at about 23 minutes in.
His summary...

The best thing to do is to try and not use position in your app.

There is a video that I will find to show you. But short answer... No. The margin for error is too great and the integration that you have to do (twice) just amplifies this error.
At best you will end up with the device telling you it is slowly moving in one direction all the time.
At worst it could think it's hurtling around the planet.
2020 Update
So, iOS has added the measure app that does what the OP wanted. And uses a combination of accelerometer and gyroscope and magnetometer in the phone along with ARKit to get the external reference that I was talking about in this answer.
I'm not 100% certain but if you wanted to do something like the OP was asking you should be able to dig into ARKit and find some apis in there that do what you want.


text:
Q: Copying C++ array as a vector of Eigen's matrix I have an Eigen matrix:
Eigen::Matrix<double, Eigen::Dynamic, VECTOR_SIZE> my_matrix(num_vectors, VECTOR_SIZE);

And I have a double array with VECTOR_SIZE elements:
double my_vector_data[VECTOR_SIZE];

I want to copy the data from the array my_vector_data into some row in my_matrix.
How can assign such a C++ vector into a specific row (vector) in the Eigen Matrix?

A: If you want it more sophisticated than in the answer of @MichaelSmith, this should work for a std::array or raw array data of size VECTOR_SIZE:
using FixedSizeRowVector = Eigen::Matrix<double, 1, VECTOR_SIZE>;

size_t some_number = 10;
my_matrix.row(some_number) = Eigen::Map<FixedSizeRowVector> v(data);

I can't test it however at the moment.

A: You could copy the data to the matrix by doing the following:
for (int i = 0; i < VECTOR_SIZE; i++)
{
    my_matrix(0, i) = my_vector_data[i];
}

You can find more information about coefficient accessors here: https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html#title4.


text:
Q: Putting cardView into tab fragment Here's a link to the project if you'd like, it's a little big for a post here.
https://drive.google.com/open?id=1cmbrJMUK56wCKdePiunXHoTRxwBj4tWy
I followed two tutorials. One was how to create a recycler with cards and another was to create a tab layout. I want to combine the two so that the cards are in a tab fragment.
This is my mainActivity:
package com.example.growdiary;

import android.net.Uri;
import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import com.google.android.material.tabs.TabLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager.widget.PagerAdapter;

public class MainActivity extends AppCompatActivity implements
        Tab1Fragment.OnFragmentInteractionListener,
        Tab2Fragment.OnFragmentInteractionListener,
        Tab3Fragment.OnFragmentInteractionListener,
        Tab4Fragment.OnFragmentInteractionListener {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    RecyclerView.Adapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        recyclerView = findViewById(R.id.recycler_view);

        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        adapter = new com.example.growdiary.RecyclerAdapter();
        recyclerView.setAdapter(adapter);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        configureTabLayout();
    }

    private void configureTabLayout() {
            TabLayout tabLayout = findViewById(R.id.tab_layout);

        tabLayout.addTab(tabLayout.newTab().setText("Tab 1 Item"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2 Item"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3 Item"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 4 Item"));

        final ViewPager viewPager = findViewById(R.id.pager);
        final PagerAdapter adapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

and this is 1 tab fragment
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Tab1Fragment">

    <TextView
        android:id="@+id/textView3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Tab 1 Fragment" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

I get this error output when I run
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.growdiary, PID: 24355
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.growdiary/com.example.growdiary.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3047)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6898)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setLayoutManager(androidx.recyclerview.widget.RecyclerView$LayoutManager)' on a null object reference
        at com.example.growdiary.MainActivity.onCreate(MainActivity.java:46)
        at android.app.Activity.performCreate(Activity.java:7149)
        at android.app.Activity.performCreate(Activity.java:7140)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1288)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3027)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3182)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1916)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6898)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

If I put the recycler xml in content_main.xml, it works, but my tabs no longer work. I'm learning how to do all these things in java, but it's a little hard to bring them all together, thanks.

A: Ok guys, I somehow figured it out on my own. I moved this out of the main java class
recyclerView = findViewById(R.id.recycler_view);

layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);

adapter = new com.example.growdiary.RecyclerAdapter();
recyclerView.setAdapter(adapter);

into the corresponding tab1 java class
I then was getting some errors and changed it a bit.
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab1, container, false);

        recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view); <-- added view to findViewById(R.id.recycler_view);

        layoutManager = new LinearLayoutManager(this.getActivity()); <--added getActivity
        recyclerView.setLayoutManager(layoutManager);

        adapter = new com.example.growdiary.RecyclerAdapter();
        recyclerView.setAdapter(adapter);

        // Inflate the layout for this fragment
        return view;
    }


text:
Q: run external command from vim, passing list of files from buffer In vim I have a list of files like this:
public/css/pure.min.css
public/css/trip.nodep.css
public/css/animate.min.css
public/css/admin-main.css
public/css/main.css
public/css/load-museo.css
public/css/upload-styles.css
public/css/pe-icon-social/css/pe-icon-social.css
public/css/pe-icon-social/css/helper.css
public/css/pe-icon-social/css/social-style.css
public/css/vex-theme-flat-attack.css
public/css/vex.css

How to pass those as args to an external command?
I tried :!cleancss -o output.min.css % but that didn't work.
EDIT:
Actually cleancss needs this form:
cat arg1 arg2 arg3... | cleancss -o minified.css

EDIT2:
While playing around, I found out that this worked well:
:!cat % | xargs cleancss -o minified.css

I don't know if there is some better(shorter) way of doing it.

A: You can join all lines first.
Keep the cursor on the desired first line and press v and then move using cursor till desired end line and then press J.
Press gv to reselect them and press y to copy.
Now, go to command line.
  Type
         :!cat

Then, press Ctrl and R and then ".
It will appear like
         :!cat file1 file2 file3....filen

Then, you can type | cleancss and finish off the command as you know about it.
Now, it will work.


text:
Q: How to make tomcat 5.5 to support servlet 3.0? Hi all i am developing a web app and deploy that in tomcat 7.0 and when i try to run the same thing in tomcat 5. i get the following exception while deploying itself.
Tomcat version 5.5 only supports J2EE 1.2, 1.3, and 1.4 Web modules

i think these cost the problem but not sure
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;

@WebServlet(urlPatterns = "/ReadEmployeeAttendance")
@MultipartConfig

how to solve this?

A: You can't do this. You need container with support for Servlet 3.0 spec, and if you want Tomcat that is only Tomcat 7. If you want your app to run in Tomcat 5.5, you cannot use Servlet 3.0 features (e.g. annotations, also your web.xml must have version="2.4" or earlier).

A: Yes you are correct that Tomcat 5.5 doesn't support Java EE 5 and above, you will have to upgrade to latest tomcat if you want servlet 3.
Every web server or application server implements specification provided by JCP, hence not all version of your server can run every version of specification, though on a general note they are backward compatible, meaning on Tomcat 7 you can run J2EE 1.4 but on tomcat 5.5 you cannot run Java EE5.


text:
Q: Retrieving some values in array Hi
I have an array of random question nos (ids). I have one form with a label for the question, a radiobutton list for their answers and a next button & checkbox to review that question. When I click the next button next(random from array) question appears. I want question id(array) those are checked for review.  How can I do this?
I used code as follows that calculates array (like this:10111) as i gives 1 value for checked & 0 for unchecked rather that this i want array of question ids those are checked :
//Code gives array of checked values in terms of 1 & o
            int g;
            if (chkmark.Checked == true)
            {
                g = 1;
            }
            else
            {
                g = 0;
            }
            int[] chkarray = new int[Convert.ToInt32(Session["Counter"]) - 1];
            int[] temp1 = (int[])Session["arrofchk"];
            int k, no;

            if (temp1 == null)
                no = 0;
            else
                no = temp.Length;
            for (k = 0; k < no; k++)
            {
           chkarray[k] = temp1[k];
            }
            chkarray[j] = g;

A: With the information you have given, this is the best I can do.  This will return a random number from your array which I assume to be of ints since it holds numbers (or IDs as you said).
        int[] questionIDs = new int[10];
        Random randomIndex = new Random(DateTime.Now.Millisecond);
        int nextQuestion = questionIDs[randomIndex.Next(questionIDs.Length - 1)];

A: I think you are generating the random questions correctly.
So when you click the next button you can check whether the checkbox for review question is checked or not. If its checked just save the corresponding id of question or save 0 into temp array and save it in session like you done.


text:
Q: iOS 14: How to open a URL in Safari app instead of user configured default browser? On iOS 14, when you open a URL via UIApplication.shared.open(…), the default browser configured in Settings is opened, and the default browser app can be some app other than Safari.
Is there a way to open URL in Safari app when the default browser is configured to another app (e.g. Google Chrome)?


text:
Q: Google.Script.Run - Not Initializing in Second Form I am trying to write a container-bound project for a Google Sheet.  It would allow me to search for a matching value in one column, and depending on the response, dictate that the record is full, allow me to fill in the missing values, or, if the value is not there at all, write a new row.
The actual HTML isn't an issue, and thanks to Stackdriver Logger, I know that the initial form values are being passed correctly, including setting a value as cache, which is used to decide what is the second HTML form for the sidebar.  The thing is that, when I submit either of the second forms, the function I'm attempting to call to add the values to the table are not initializing, even though the script should be the same.
For reference, this is the the contents of the <script>  tags in the initial HTML file:
document.querySelector("#cunyID").addEventListener("submit",
      function(e) {
        e.preventDefault();
        google.script.run.cunyIDQuery(this);
        google.script.run.newSidebar();
      }
      );

This is the contents of <script> in one of the second forms:
gpa.onchange = function setTwoNumberDecimal(event) {
        this.value = parseFloat(this.value).toFixed(2);
      };
      q1.onchange = function setWholeNumber(event) {
        this.value = parseFloat(this.value).toFixed(0);
      };
      q2.onchange = function setWholeNumber(event) {
        this.value = parseFloat(this.value).toFixed(0);
      };
      q3.onchange = function setWholeNumber(event) {
        this.value = parseFloat(this.value).toFixed(0);
      };
      document.querySelector("#noCUNYID").addEventListener("submit",
      function(e) {
        e.preventDefault();
        google.script.run.noCUNYIDSubmit(this);
        google.script.host.close();
      }
      );

And this is from the second of the second-level forms:
q1.onchange = function setWholeNumber(event) {
        this.value = parseFloat(this.value).toFixed(0);
      };
      q2.onchange = function setWholeNumber(event) {
        this.value = parseFloat(this.value).toFixed(0);
      };
      q3.onchange = function setWholeNumber(event) {
        this.value = parseFloat(this.value).toFixed(0);
      };
      document.querySelector("#yesCUNYID").addEventListener("submit",
      function(e) {
        e.preventDefault();
        google.script.run.yesCUNYIDSubmit(this);
        google.script.host.close();
      }
      );

Even though, theoretically, google.script.run should be calling for the functions, Stackdriver is not reporting the function opening, and google.script.host.close() is running correctly.  Does anyone know what might be going on?

A: It is likely that the script is closing before the script.run completes execution.
You should use the withSuccessHandler callback to run close when the script is completed.
    google.script.withSuccessHandler(function() {
       google.script.host.close();
    }).run.yesCUNYIDSubmit(this);


text: Q: Nvidia color correction settings go away when I launch CS:GO I'm using Ubuntu 20.04 KDE. I have applied some color correction settings in the Nvidia control panel (Nvidia X Server Settings); when I launch Counter Strike Global Offensive (CSGO) the corrections disappear. Any solution?


text:
Q: Accessing global variable via functions - different instances across namespaces I am working on an university assignment. The general idea is to make a library, written in c++, and expose its content in both C and C++ headers. We are supposed to have a global variable containing dictionary (unordered_map) of dictionaries storing telephone number changes and modify it with functions exposed in header. In other words we have unordered_map<id, unordered_map<old_phone_nr, new_phone_number>>. Here is my C++ header
namespace jnp1 {

extern "C" {
extern size_t TEL_NUM_MAX_LEN;

unsigned long maptel_create();
// create a dictionary of telephone number changes (old->new) and return its ID

void maptel_delete(unsigned long id);
// delete the dictionary ID

void maptel_insert(unsigned long id, char const *tel_src, char const *tel_dst);
// insert change into dictionary ID

void maptel_erase(unsigned long id, char const *tel_src);
// erase change from dictionary ID

void maptel_transform(unsigned long id, char const *tel_src, char *tel_dst, size_t len);
// follow chain of changes (nr1 -> nr2 -> ... -> final_number) and return final number
}
}

And we have a similar C header.
Our library has to conform to external tests - C version:
#include <assert.h>
#include <string.h>
#include "maptel.h" // our library C header

static const char t112[] = "112";
static const char t997[] = "997";

int main() {
  unsigned long id;
  char tel[TEL_NUM_MAX_LEN + 1]; /* +1 for terminal zero */

  id = maptel_create();
  maptel_insert(id, t112, t997);
  maptel_transform(id, t112, tel, TEL_NUM_MAX_LEN + 1);
  assert(strcmp(tel, t997) == 0);
return 0;

}
this works without any problems. However the C++ test case uses unnamed namespace like that
#include <cassert>
#include <cstddef>
#include <cstring>
#include "cmaptel" // our library C++ header

namespace {

  unsigned long testuj() {
    unsigned long id;

    id = ::jnp1::maptel_create();
    ::jnp1::maptel_insert(id, "997", "112");

    return id;
  }

  unsigned long id = testuj();

} // anonymous namespace

int main() {
  char tel[::jnp1::TEL_NUM_MAX_LEN + 1];

  ::jnp1::maptel_transform(id, "997", tel, ::jnp1::TEL_NUM_MAX_LEN + 1); // here it breaks
  assert(::std::strcmp(tel, "112") == 0);
  ::jnp1::maptel_delete(id);
}

On first access from outside the namespace an assertion we made inside the function breaks, because id is not in the dictionary. So, in other words, the anonymously namespaced maptel_create() creates the id dictionary in some other instance of the variable than the maptel_transform() in void main(){} tries to access it. We were not able to troubleshoot this issue, however moving our global unordered_map<unsigned long, unordered_map<string, string>> to heap (we made the variable a pointer, not an object, and allocated it in first call of maptel_create()) works - except specification of the task has no guarantee we can deallocate it, resulting in a memory leak.
I am looking for help/explanation of this phenomenon. Please don't tell me to use a class instead of global variables - while this is obviously the correct design choice, we have a specification we must conform to. Below I show heap and stack versions of the create/erase functions (in this matter erase works same as transform, it's just shorter so better as an example)
Stack:
#include "cmaptel"

typedef std::unordered_map<std::string, std::string> tel_book;
std::unordered_map<unsigned long, tel_book> books;

unsigned long id_counter;

extern "C" {
    size_t TEL_NUM_MAX_LEN = 22;

    unsigned long jnp1::maptel_create()
    {
        books.reserve(1);
        // without this for some reason we would get float arithmetic exception right here

        books[id_counter] = tel_book();
        return id_counter++;
    }

    void jnp1::maptel_erase(unsigned long id, char const *tel_src)
    {
        assert(books.count(id)); // this is the assertion that breaks
        std::string src(tel_src);
        int result = books[id].erase(src);

    }
}

Heap:
#include "cmaptel"

typedef std::unordered_map<std::string, std::string> tel_book;
std::unordered_map<unsigned long, tel_book> *books;

unsigned long id_counter;

extern "C" {
    size_t TEL_NUM_MAX_LEN = 22;

    unsigned long jnp1::maptel_create()
    {
        if (books == NULL) books = new std::unordered_map<unsigned long, tel_book>();
        (*books)[id_counter] = tel_book();
        return id_counter++;
    }

    void jnp1::maptel_erase(unsigned long id, char const *tel_src)
    {
        assert(books->count(id));
        std::string src(tel_src);
        int result = (*books)[id].erase(src);

    }
}

A: Initialization order for globals is not specified across multiple translation units. The problem is that id (and thus the call to maptel_insert) is being initialized before books. Since maptel_insert is operating on an uninitialized object, this is undefined behavior.
You've found one way to solve it: allocate the map dynamically on-demand, thus ensuring it gets allocated before use. Another slight variation would be to use a function-scoped static, as these have rules guaranteeing they are initialized before use:
std::unordered_map<unsigned long, tel_book>& books()
{
    static std::unordered_map<unsigned long, tel_book> instance;
    return instance;
}

C++11 also guarantees this initialization is done in a thread-safe manner.


text:
Q: Use Powershell to find and compare text in file to a folder name My apologies, but unfortunately my Powershell scripting is quite poor, however I'm trying to muddle on with this... The below is actually for a Nagios check, hence the defining the OK, WARNING etc
Summary
I have 2 small text files with specific text within that I need to check for a folder existing with the corresponding name.
In File 1 below, note the section that states "prod" on line 18, against this I am interested in the apples, pears and bananas data (that which is a date format, plus other text) within the speech marks, so for bananas it would be 20220817-1-64 only.

*

*The position within the text file of the "prod" line and subsequent data I'm
interested in can't be guaranteed.

*The data against apples, pears etc will change over time

file1.txt:
{
"default": "prod",
"pre": {
    "apples": "20220711-0",
    "pears": "20220711-0",
    "bananas": "20220711-1-64"
},
"test": {
    "apples": "20220920-0",
    "pears": "20220920-0",
    "bananas": "20220920-1-64"
},
"new": {
    "apples": "20220910-0",
    "pears": "20220910-0",
    "bananas": "20220910-1-64"
},
"prod": {
    "apples": "20220817-0",
    "pears": "20220210-0",
    "bananas": "20220817-1-64"
},
"old": {
    "apples": "20220601-0",
    "pears": "20220601-0",
    "bananas": "20220601-1-64"
}
}

File 2 has a similar principal, I am only interested in 20220923-0 next to the "prod" line (again, position within the file can't be guaranteed and the data will change over time)
File2.txt:
{
"default": "prod",
"pre": "20220917-0",
"test": "20220926-0",
"new": "20220924-0",
"prod": "20220923-0"
}

Each of the values would need to be compared against a directory, to see if a folder of the same name exists. If it matches, the result would be OK, if different then result in a WARNING, if missing the result would be CRITICAL.
What I have tried
Defining the result and folder to check against is straight forward enough:
# Result
$OK=0
$WARNING=1
$CRITICAL=2

# Folders to check
$apples_folder = (Get-Childitem c:\folder_path\apples\*).Name
$pears_folder = (Get-Childitem c:\folder_path\pears\*).Name

However the main part I'm struggling with is picking out the relevant text from the text file(s) against the prod line(s)
From what I have gathered, I suspect using regex or possibly grep commands may hold the answer, but I can't quite get my head around it.
Any pointers in the right direction would be appreciated.

A: Continuing from my comment, you can parse File1.txt as JSON, assuming that what you gave us as example is missing the final closing bracket '}' as a result of posting it here and that the json in the actual file is complete.
To work with that file type, you can do
$json = Get-Content -Path 'X:\somewhere\File1.txt' -Raw | ConvertFrom-Json
$prodFolder = $json.prod.bananas
# next test if you can find a folder with that name and do whatever you need to do then
if (Test-Path -Path "c:\folder_path\prod\$prodFolder" -PathType Container) {
    "OK"
}
else {
    "CRITICAL"
}

For File2.txt, things are quite different because that is a strange format..
What you can do is convert the data in there into a Hashtable using the ConvertFrom-StringData cmdlet.
In PowerShell 5.x you need to replace the colons that separate the names from their values into an equal sign (=)
$data = (Get-Content -Path 'X:\somewhereElse\File2.txt' -Raw) -replace '^(.*?):(.*)','$1=$2' -replace '[", ]' | ConvertFrom-StringData
$prodFolder = $data.prod
# next test if you can find a folder with that name and do whatever you need to do then
if (Test-Path -Path "c:\folder_path\prod\$prodFolder" -PathType Container) {
    "OK"
}
else {
    "CRITICAL"
}

In PowerShell 7.x you do not have to replace the colons:
$data = (Get-Content -Path 'X:\somewhereElse\File2.txt' -Raw) -replace '[", ]' | ConvertFrom-StringData -Delimiter ':'


text:
Q: Fetch and display image on click of a button I want to fetch an image on click of a button and display it in the same activity. This is what i have tried
public class MainActivity extends Activity {

    ImageView imView;
    String imageUrl="http://variable3.com/files/images/email-sig.jpg";
    Random r= new Random();
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle icicle) {
       super.onCreate(icicle);
       setContentView(R.layout.main);

       Button bt3= (Button)findViewById(R.id.get_imagebt);
       bt3.setOnClickListener(getImgListener);

       imView = (ImageView)findViewById(R.id.imview);
       Log.i("img already downloaded","img");
   }

   View.OnClickListener getImgListener = new View.OnClickListener()
   {

         public void onClick(View view) {
              // TODO Auto-generated method stub

              //i tried to randomize the file download, in my server i put 4 files with name like
                       //png0.png, png1.png, png2.png so different file is downloaded in button press
             int i =r.nextInt(4);
              downloadFile(imageUrl);
              Log.i("im url",imageUrl);
         }

   };

   Bitmap bmImg;
   void downloadFile(String fileUrl){
         URL myFileUrl =null;
         try {
              myFileUrl= new URL(fileUrl);
         } catch (MalformedURLException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         }
         try {
              HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
              conn.setDoInput(true);
              conn.connect();
              int length = conn.getContentLength();
              InputStream is = conn.getInputStream();

              Log.i("im connected","Download");
              bmImg = BitmapFactory.decodeStream(is);
              imView.setImageBitmap(bmImg);
         } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
         }
    }

}

A: Didn't understand your question, but if it's about that comment about randomizing the download, then just add your i variable to the downloadFile() method parameters:
void downloadFile(String fileUrl, int i)

Then add a switch block to the method's body and make it download the file you need for a current value of i. Hope this is what you needed.


text:
Q: Thread 1:EXC_BAD_ACCESS (code=1, address=0x70745092) So as the title said, I'm getting this error in my code. There's no output besides the usual (lldb) thing. The line it's pointing to is

0x10df051:  movl   8(%edx), %edi0x10df051:  movl   8(%edx), %edi

The code itself is
DeltaViewController *deltaview = [[DeltaViewController alloc] initWithNibName:@"DeltaViewController" bundle:nil];

It happened when I selected an object in my picker and it should add a subview.

A: deltaview is DeltaViewController type, so it's a controller, not a view. After you've added it as a subview of self.view ([self.view addSubview:deltaview.view];), you might release the deltaview. Then whenever you sent a method (which is implemented in DeltaViewController) to deltaview, you'll get this EXC_BAD_ACCESS error of course.
A simple solution: Just declare deltaview (actually, it should be deltaViewController instead) as an iVar instead of local variable.

EDIT:
Well, here's a simple code snippet:
YourViewController.h:
@interface YourViewController : UIViewController

@property DeltaViewController *deltaViewController;

@end

YourViewController.m:
@implementation YourViewController

@synthesize deltaViewController;
...

- (void)aMethod;

@end

- (void)dealloc {
  self.deltaViewController = nil; // set it to nil & release it after yourViewController dealloced.
  [super dealloc];
}

- (void)aMethod {
  DeltaViewController *deltaViewController = [[DeltaViewController alloc] initWithNibName:@"DeltaViewController" bundle:nil];
  // ...(setup deltaViewController)
  self.deltaViewController = deltaViewController; // it'll retain deltaViewController
  [deltaViewController release];

  ...
}


text:
Q: How To Use Getter Setter Method In Laravel? And How To Add Field Using Eloquent Model? This is my User.php Model
<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname','lastname', 'email','image', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

this is output
Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => admin
            [lastname] => Gomez
            [email] => admin@admin.com
            [image] => admin.png
            [created_at] => 2019-11-10 04:30:01
            [updated_at] => 2019-11-10 14:03:38
        )

)

I just want full path of url using getter setter method using eloquent Model
Like this
Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => admin
            [lastname] => Gomez
            [email] => admin@admin.com

            [image] => public/images/admin.png

            [created_at] => 2019-11-10 04:30:01
            [updated_at] => 2019-11-10 14:03:38
        )

)

I also i want add another field like fullname (Like [fullname] => admin gomez )
i want also this
Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => admin
            [lastname] => Gomez
            [email] => admin@admin.com
            [image] => admin.png
            [created_at] => 2019-11-10 04:30:01
            [updated_at] => 2019-11-10 14:03:38

            [fullname] => admin gomez
        )

)

Thank you

A: Please define these two methods in your model:
protected $append = ['full_name'];

/**
 * Get the user's full name.
 *
 * @return string
 */
public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

/**
 * Get full image path
 *
 * @return string
 */
public function getImageAttribute()
{
    if ($this->image) {
        return public_path($this->image);
    }

    return '';
}

A: The getter for image on the User model would look something like this:
public function getImageAttribute()
{
    return public_path('images') . $this->image;
}

The full name one would be exactly what is in the documentation minus the underscores in your case:
public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}";
}

If you're trying to make sense of how or why this works it is because Laravel makes use of PHP's magic methods. In this case the __get. So the model basically looks for any gets and uses the 'getFieldNameAttribute' method instead if it exists.
https://laravel.com/docs/6.x/eloquent-mutators#defining-an-accessor
https://www.php.net/manual/en/language.oop5.overloading.php#object.get