text:
Q: Sort an ArrayList that contains two type of data classes so my problem is that I have an ArrayList that contains two types of data. The first one is the following class:
data class TextMessage (
    val content: String,
    val date: Date,
    val type: Int
)

The second class changes only the content type. So I'm creating a list that contains this two types of data and I want to sort it using the date value, that both of the types contains it, but I'm not finding any solution on internet that helps me, actually I don't know if it's possible to do that because I started to learn Kotlin a few days ago.
I hope someone can help me.
Thanks, see ya.

A: Preferably you want the two classes to share some super type. For example an interface. You could then have the common properties defined in the interface. Something like this:
interface Message {
    val date: Date
}

data class TextMessage (
    val content: String,
    override val date: Date,
    val type: Int
) : Message

data class OtherMessage (
    override val date: Date
) : Message

You could then sort a list of Message by doing this:
val sortedList = listOfMessages.sortedBy { it.date }

If you can't change your classes like this, you would have to rely on a check that might throw exceptions. Something like this:
val sortedList = listOfAny.sortedBy {
    when(it) {
        is TextMessage -> it.date
        is OtherMessage -> it.date
        else -> throw IllegalArgumentException("Unknown type for sorting!")
    }
}


text:
Q: Python storing and plotting data I am trying to categorize a csv data with 600000 rows and 2 columns into a few types of data. Is there any possible way that I could apply something like array in C so that I could use ply.scatter(x,y) , where x and y correspond to columns of each type, to plot them out?
The way I am currently using is to store them into different files and then open it with plt(float(row[0]), float(row[1])).

A: Use pandas, with x and y two different columns, and then use df.plot.scatter(...) as documented here.

A: check csv package in python standard library:
https://docs.python.org/3/library/csv.html
my sketched answer will be like
import csv
x, y = [], []

with open('your.csv', newline='') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        x.append(row[0])
        y.append(row[1])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any consequence to using "Try Again" after failing during court? Every game in the Ace Attorney series has featured a "strikes" or "life bar" system during courtroom phases, where you receive an instant Game Over if you present incorrect evidence or make mistakes too many times. In previous games in the series, you'd have to restart from your last save after earning a Game Over in this way, but in Dual Destinies, the Game Over screen is immediately followed by a "Try Again" option, which returns you to the exact spot you were just at, and refills your life bar to maximum.
Being that it seems like this sort of negates the life bar's reason for existing in the first place, is there any consequence at all to selecting Try Again? Does it affect anything differently later on in the case/game, or does it make no difference?

A: No, there is no penalty for using the Try Again feature.  The likely reason that this was incorporated is because Dual Destinies expands on the Bad Ending feature present in previous games by having several specific, detailed Game Over sequences that can be found.  The feature is simply to facilitate the ability to easily see all of the endings in a single run.


text:
Q: I have specific tabular data, how can I represent this with Polymer with 2 way binding? Are there any components built with polymer that allow displaying of tabular data? I would like something that compares with current UI grids out there.
I am interested in infinite scrolling and 2 way binding to json data in particular.

A: One good place to look for such things is the Component Kitchen
Looking there I found aha-table. It doesn't appear to have infinite-scrolling, but it lists pagination as a feature.

A: Not a completely useful answer but here's what I'm aware of:
Seems that the team plans to add what you're looking for - https://github.com/Polymer/core-list/issues/20
This might help you do something now - https://github.com/polymer/core-layout-grid


text:
Q: Сортировка чисел с разделителями в текстовом поле Исходные данные:

*

*MS SQl server

*Таблица с иерархическими данными, связи в которой обеспечены двумя полями: id и id_parent.

id_parent содержит id родителя.
Есть текстовое поле, где хранятся порядковые номера вида "1.1.2.3.".
Вопрос в том как отсортировать таблицу по возрастанию этих номеров, если они воспринимаются как текст.
Пример
НЕПРАВИЛЬНО:
1.
1.1.
10.1.
2.1.

ПРАВИЛЬНО
1.
1.1.
1.1.1.
2.1.
...
10.1.
10.2.

Рекурсивный запрос по 12тыс. строк выполняется более 5 минут и как действующее решение не подходит


text:
Q: C# creating an instance of a class and derived class I tried the below code in my c# program. This is just for learning the OOPs Concepts.
 class a
    {
        public void testa()
        {
        }
    }
    class b:a
    {
        public void testb()
        {
        }
    }

  a a1 = new b();

  b b1 = new a();

I have the following queries regarding the code mentioned above.

*

*Why Im getting error in 2nd line?

*what is meant by a a1=new b();

*why a1.testb() is not accessible even though constructor of b is assigned to a1?

*what is the difference between  a a1=new a() and a a1=new b()?

A: 1) if you mean this line:
b b = new a();

it is because every b is a but not every a is b
2-3) what is meant by a a1=new b();
     why a1.testb() is not accessible even though constructor of b is assigned to a1?
it means that you create object of b class but get reference to it as a(you can treat it trough this reference without casting only as a even it is b)

A: I change your class and method names to real world equivalents to better understanding. I name a as Animal, testa as Eat, b as Human, and testb as Talk. So we have:
class Animal {
    public void Eat() { }
}

class Human : Animal {
    public void Talk() { }
}

Animal a1 = new Human();

Human b1 = new Animal();

OK, return to your questions.
1) You get error on second line, because every animal is NOT a human. Is it?
2) a1=new b() according to our new naming conventions, turns to a1 = new Human which means Animal a1 = new Human. So, that's correct, because human is a kind of animal.
3) a1.testb() according to our new naming conventions, turns to a1.Talk(). Well, a1 is an animal (Animal a1), and we can not expect an animal to talk.
MORE:
Think a class is a group of attributes and behaviors. For example, we have a group named Animal that defines an Eat behavior. And another group named Human that extends Animal group and also it has its own behavior named Talk. As we know, Human has its super-group behaviors too -e.g. Eat in this example-.
When we have an instance of group Animal, we can expect it to eat. But we can not ask it to talk. It's not possible. In the other hand, every item that we choose from group Human, is actually an Animal. So we can ask him to eat.
When we have a Human instance, we can ask him to behave as a Human and as an Animal too. I mean, we can ask him to Talk and we can ask him to Eat too. Every Human can be located in human group, and in animal group.
1) When we say Human b1 = new Animal(); it says exactly: pick up an item from Animal group - right part - and put it in Human group - left part - which is not possible. Because there are a lot of animals which are not human.
2) When we say Animal a1 = new Human: pick up an item from Human group - right part - and put it in Animal group - left part - which is easily possible.
3) When we say a1.Talk(), we expect an Animal to talk. I mean we expect an Animal to act a Human behavior which is not possible.

A: Probably inheritance and polymorphism concepts are not so clear for you yet.
This article may help you.
If class b inherits from a, you can imagine it as a "specialization" of a.
So you can easily understand that b can be used/seen as an a instance, but the reverse is not true!

Why Im getting error in 2nd line?

because b b1 = new a(); is not a valid assignment. As explained, you can assign inherited class instance to base class variable, but not the contrary!

what is meant by a a1=new b();

this assignment is correct because you can surely use a more specific class instance as a base class instance.

why a1.testb() is not accessible even though constructor of b is assigned to a1?

when you inherit from a class, all the public and protected methods of this class are inherited and you can access or override that in the new class. but testb() is not an inherited method. is a new method defined inside class b so you can use it only if you do this assignment: b b1=new b();

A: If you defined a a1 = new b() ,  to use methods declared in b you can cast a1 as b
 a a1 = new b();
 ((b)a1).testb();

A: Think of your classes as a contract, guaranteeing the existence of certain operations.
Class a defines one operation, class b inherits all operations from a and defines another one of its own.
The first line:
a a1 = new b();

Declares a variable named a1 of type a, meaning whatever value you give this variable should have all the operations type a requires. new b() creates a new instance of class b, which is assigned to variable a1. Since class b inherits all operations from type a, a value of type b can be assigned to a variable of type a.
On the second line:
b b = new a();

Similarly, you define a variable which should have all the operations defined by type b. But since you put in a value of type a which doesn't define the testb operation type b requires, the compiler doesn't accept this.
As for your third question, the compiler only knows the type of your variable (a), not which value you actually assigned to it. You basically told the compiler "I guarantee this value will define the testa operation. Now let it do operation testb!" The compiler doesn't know the actual value of the variable, so as far as it's concerned, that's not possible.
As for the difference between a a1=new a() and a a1=new b():
In both cases, a variable of type a is created. In the first expression, the value assigned to this variable is a newly created instance of type a, while in the second, the value is a newly created instance of type b. Since type 'b' is basically an expanded version of type a, the compiler know that everything you could ask of an instance of type a can also be satisfied by an instance of type b, so it just treats the value as if it is of type a.

A: 1) Every b is an a but the converse is not true.
2) is an example of Polymorphism Polymorphism - Define In Just Two Sentences
3) a1.testb() is not accessible because you are treating it as an instance of a which has no definition for testb()


text:
Q: Android Firebase : Second Connected Database not allowing auth in rules I've connected two Databases from the same firebase project like below.
    //init the default db;
    FirebaseApp.initializeApp(this);

    //init the second db;
    FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
    builder.setApplicationId("id"); //Same as default
    builder.setApiKey("key"); //Same as default
    builder.setDatabaseUrl("https://second-db.firebaseio.com");

    try {
        FirebaseApp.initializeApp(this, builder.build(), "second-db");
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }

Getting Reference.
public static DatabaseReference getSecondDbRef(String child) {
    FirebaseApp app = FirebaseApp.getInstance("second-db");
    return FirebaseDatabase.getInstance(app).getReference(child);
}

With the above, it works, but the rules in the second database don't seem to be getting auth. if I do.
 {
   "rules":{
          "users":{
                 "$uid":{
                       ".read":"auth.uid !== null",
                       // ".read":true // This works, so the issue is auth
                  }
          }
   }
}

The read fails, even though the user is authenticated, also, this problem isn't there with the default database. Is there anything I'm missing with the init?
Ok, because of highlights below, here's the code as it is on the app.
    private static final String  TEAMS_BD_ID   = "second-db"

    public void initFirebase() {
        FirebaseApp.initializeApp(this);

        FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
        builder.setApplicationId("appId"); // //Same as default
        builder.setApiKey("key"); // //Same as default
        builder.setDatabaseUrl("https://teams-db.firebaseio.com");//Second Db

        try {
            FirebaseApp.initializeApp(this, builder.build(), TEAMS_BD_ID);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    public static FirebaseApp getTeamsApp() {
        return FirebaseApp.getInstance(TEAMS_BD_ID);
    }

    public static String getTeamsUserUid() {
        return FirebaseAuth.getInstance(getTeamsApp()).getCurrentUser().getUid();
    }

    public static DatabaseReference getTeamsRef(String child) {
        return FirebaseDatabase.getInstance(getTeamsApp()).getReference(child);
    }

    public static DatabaseReference getTeamsRef() {
        return FirebaseDatabase.getInstance(getTeamsApp()).getReference();
    }

Then trying to read.
DatabaseReference r = getTeamsRef().child("users/" + getTeamsUserUid() + "/teams")
// getTeamsUserUid()  This is null.

A: It is only a guess.
If you are using FirebaseAuth#getInstance() for getting auth instance, change it to FirebaseAuth#getInstance(FirebaseApp firebaseApp) with the second app instance.


text:
Q: C - error: incomplete definition of type 'struct name_s' I try to implement a bloom filter in C. I split the file in two header one public and one private. The first contain the function's signature e the typedef of the struct and the second the definition of the struct.
This is the code of the below heade:
bloom_filter_private.h
#ifndef BLOOM_FILTER_PRIVATE_H
#define BLOOM_FILTER_PRIVATE_H

#include <pds/bloom_filter.h>

struct bloom_filter_s {
    int *bit_vector;
    int dimension;
};

#endif /* BLOOM_FILTER_PRIVATE_H */

bloom_filter.h
#ifndef BLOOM_FILTER_H
#define BLOOM_FILTER_H

typedef struct bloom_filter_s* bloom_filter_t;

bloom_filter_t bloom_filter_create(int const dimension);

int bloom_filter_destroy(bloom_filter_t bloom_filter);

#endif /* BLOOM_FILTER_H */

In the end I have a file where I implemented the code of the create/destroy function:
bloom_filter.c
#include <stdio.h>
#include <stdlib.h>
#include "bloom_filter_private.h"

bloom_filter_t bloom_filter_create(int const dimension) {

    if ( dimension >= 0) {

        int i;
        bloom_filter_t bloom_filter = malloc(sizeof(struct bloom_filter_s));

        if ( bloom_filter == NULL) {
            perror("Unable to create a bloom filter");
            abort();
        }

        bloom_filter->bit_vector = NULL;

        if ( dimension > 0 ) {

            bloom_filter->bit_vector = (int *) malloc(dimension * sizeof(int));

            if ( bloom_filter->bit_vector == NULL ) {
                perror("Unable to create a bit vector");
                abort();
            }

            for ( i = 0; i < dimension; i++ )
                bloom_filter->bit_vector[i] = 0;
        }

        bloom_filter->dimension = dimension;
        return bloom_filter;
    }
    else return NULL;
}

int bloom_filter_destroy(bloom_filter_t bloom_filter) {

    if ( bloom_filter != NULL) {

        free(bloom_filter->bit_vector);
        free(bloom_filter);

        return 1;
    }

    return -1;
}

The file bloom_filter.c and bloom_filter.h are in the same folder called src. The file bloom_filter_private.h is in the subfolder pdf of the folder include.
The problem is that I try to create a empty bloom filter with the following simple code, I have this error:

error: incomplete definition of type 'struct bloom_filter_s'

Therefore I can't access to the structur's fileds.
main.c
#include <stdio.h>
#include <pds/bloom_filter.h>

int main(void) {

    int i;
    bloom_filter_t bloom_filter = bloom_filter_create(10);

    for ( i = 0; i < 10; i++ )
        printf("[%d] =: %d\n", i, bloom_filter->bit_vector[i]);

    return 0;
}

A: The whole point of putting the definition of the struct into a private file is so users can't see the contents.  If you want to give users access to these fields you need to create accessor functions in your library:
bloom_filter.c:
int get_vector_element(bloom_filter_t bloom_filter, int index)
{
     return bloom_filter->bit_vector[index];
}

bloom_filter.h:
int get_vector_element(bloom_filter_t bloom_filter, int index);

The you can do the following in main:
for ( i = 0; i < 10; i++ )
    printf("[%d] =: %d\n", i, get_vector_element(bloom_filter, i));


text:
Q: Missinig provisoning profile error when building an ios ionic app using xcode 10 I updated my version of xcode yesterday, and now when I build an ionic app that worked perfectly before I get the following error when validating the ipa:
Unable to process application at this time due to the following error: Missing Provisioning Profile - Apps must contain a provisioning profile in a file named embedded.mobileprovision..
How can I get the embedded.mobileprovision to be generated/ included?
Thanks,
Yuval

A: https://github.com/apache/cordova-ios/issues/407 has an answer,
\just build with the --buildFlag="-UseModernBuildSystem=0" and adjust project settings to build using legacy mode.

A: Currently the best workaround is to opt-out of the new build system:
If you're building on the command-line, you can specify --buildFlag="-UseModernBuildSystem=0":
Cordova CLI
cordova run ios --buildFlag='-UseModernBuildSystem=0'
cordova build ios --buildFlag='-UseModernBuildSystem=0'

Ionic CLI
ionic cordova run ios -- --buildFlag="-UseModernBuildSystem=0"
ionic cordova build ios -- --buildFlag="-UseModernBuildSystem=0"

If you're building with a build.json config file, you can add the following under the iOS release or debug config:
"buildFlag": [
  "-UseModernBuildSystem=0"
]

If you are opening the project in the Xcode IDE, you need to change the build system in Workspace Settings to "Legacy Build System"

Solution from here
Worked For Me. Cheers.

A: It seems like this issue has been resolved with the release of cordova ios 5.0.0 ( https://cordova.apache.org/announcements/2019/02/09/cordova-ios-release-5.0.0.html ) - they added compatibility with the modern build system


text:
Q: How can I detect multidimensional array length in javascript? In the following code the matrix.length only counts the first array and not the second one. How can I count multidimensional array so the result for the following code is 10?
var matrix = [1,2,3,4,5,6, [1,2,3,4]];

console.log(matrix.length - 1)

A: There's no shortcut, you have to sum up the lengths of the arrays. If you only have two dimensions, then:

var matrix = [1,2,3,4,5,6, [1,2,3,4]];
var sum = matrix.reduce(function(acc, entry) {
    return acc + (Array.isArray(entry) ? entry.length : 1);
}, 0);
console.log(sum);

If you may have more dimensions, you'll need recursion. As squint pointed out in a comment, making the above recursive is just a matter of giving our reduce callback a name and then doing reduce again instead of just using array.length:

var matrix = [1,2,3,4,5,6, [1,2,[3,4]]];
var sum = matrix.reduce(function callback(acc, entry) {
    return acc + (Array.isArray(entry) ? entry.reduce(callback, 0) : 1);
}, 0);
console.log(sum);

Some notes:

*

*Array.isArray and Array#reduce were added in ES5 (in 2009) and so should be available in just about any modern browser (so, not IE8); they can both be shimmed/polyfilled on older browsers.

*JavaScript doesn't actually have multi-dimensional arrays. It has arrays of arrays.

*The recursive example above uses a construct called a named function expression for callback. NFEs have a bad name because years ago browsers got them wrong several different ways, but these days they're fine. (If you used the above on IE8 — including polyfills for the things it's missing — even it would work even though IE8 gets NFEs wrong.)

A: Building on @T.J. Crowder's solution with reduce, I would suggest to turn things around a bit so there is only one mention of reduce in the code. And to spice it up, this is with arrow syntax:

function entries(a) {
    return Array.isArray(a) ? a.reduce((acc, el) => acc + entries(el), 0) : 1;
}

var matrix = [1,2,3,4,5,6, [1,2, [3,4]]];

console.log(entries(matrix));

This way it will even work for non-array arguments: return value is 1 in that case. Obviously not that important.


text:
Q: If a person is hit by an object, are their bones under predominantly compressive or shear stress? Say a person is standing still and they get hit by a tennis ball, are their bones under compressive or shear stress due to this impact? In actuality, I know they're under both, but the specifics of what each kind of stress actually is has me confused.
Shear stress is described by wikipedia as force coming from a vector parallel to the materials cross section. However, can't you draw a cross section from any angle, so you could have a bone cross section that looks like a distorted circle if it is drawn viewed from the "top", or one that looks like the silhouette of the bone if it's drawn from the "side".

A: Generally bones are under compressive stress and are optimized for this. The HUman body is an example of Tensegrity

Tensegrity, tensional integrity or floating compression, is a
structural principle based on the use of isolated components in
compression inside a net of continuous tension, in such a way that the
compressed members (usually bars or struts) do not touch each other
and the prestressed tensioned members (usually cables or tendons)
delineate the system spatially.
...
Biotensegrity, a term coined by Dr. Stephen Levin, is the application
of tensegrity principles to biologic structures.[6] Biological
structures such as muscles, bones, fascia, ligaments and tendons, or
rigid and elastic cell membranes, are made strong by the unison of
tensioned and compressed parts. The muscular-skeletal system is a
synergy of muscle and bone. The muscles and connective tissues provide
continuous pull[7] and the bones present the discontinuous
compression.


text:
Q: How to use SDF's {avoid} in rascal MPL I'm trying to design an island grammar using Rascal MPL, but I ran into a problem:
When implementing an Island Grammar in SDF a very common approach is to define a "catch-all" water production using the {avoid} attribute. This prevents the parser from using this production if others are applicable. This allows to specify a default behaviour that can be overridden by other productions whitout generating abiguities. A very simple example of this would be:
context free syntax
    Chunk*         -> Input
    Water          -> Chunk
lexical syntax
    ~[\t\n\ ]+   -> Water {avoid}  // avoid the Water production

I tried reproducing this behaviour with Rascal MPL. My goal is to create an island grammar that gathers all conditional preprocessor directives inside a piece of C/C++ code and skips the rest of the input using Water productions.
layout LAYOUT = [\t\n\ ];
lexical WATER = ![\t\n\ ]+;

start syntax Program = Line*;       // program consists of lines

syntax Line = ConditionalDirective  // preprocessor directives
            > WATER;                // catch-all option

syntax ConditionalDirective = "#ifdef"
                            | "#ifndef"
                            | "#if"
                            | "#elif";

I tried to create the {avoid} effect by giving the ConditionalDirective production a higher priority using the ">" operator, but this doesn't work apparently. The parse tree still contains ambiguities.
#ifdef asd

If I parse the above code for example, I get a parse tree that looks as follows:

As far as I can tell from the Rascal Documentation, using the "priority"-operator might not be the way to go in my case, but I don't see any other possibilities. I assume there is a way though, because the authors of rascal clearly state that every SDF grammar can be converted to a rascal grammar.
Is there a way to reproduce SDFs {avoid} functionality with rascal MPL? Or is it possible to filter the parse forest somehow, reapplying the priorities?

A: Short answer: avoid is in sdf2 a post parse filter. In rascal you can define these yourself, see https://github.com/cwi-swat/rascal/blob/master/src/org/rascalmpl/library/lang/sdf2/filters/PreferAvoid.rsc for an example which mimics sdf2 avoid behavior without ignoring injection chains and without counting. You can import it in your grammar and use @avoid and @prefer tags just like in sdf2, or write your own filters.
Caveat: avoid was generally not enough to define water behavior in sdf2 and it isn't in rascal either. The reason is that water can become longer than its alternative. Prefer and avoid can only choose between alternatives of equal length in terms of subsentence length.
One surefire but slow way to deal with water in rascal is to count it in every alternative and choose derivations with less water.
Another issue with prefer and avoid was that the uses would start interfering, especially when they were counted. This can be avoided in rascal by specializing filters for specific nonterminals or even alternative rules.
Another option is to use the \ and ! disambigation operators. See the manual. However, All and all
I believe the post parse filtering option is currently the best way to deal with island grammars because you control what is going on.


text:
Q: Unique Revit Model Identifier 2016-2018 We are looking for a way to distinguish between Revit models from multiple different computers. For BIM360 and Revit Server models, we are able to use
document.GetWorksharingCentralModelPath().GetModelGUID()

However, for local models and central models, we are not able to grab any sort of unique identifier for the model. We cannot set a parameter with a GUID due to the fact that multiple users start from a template Revit model, therefore copying the unique identifier and making them non-unique. Is there any way to uniquely distinguish a Revit model using the Revit API?

A: The Building Coder discussed the issue of creating your own unique project id and using Named Guid Storage for Project Identification.

A: in my opinion, copying the Revit Document should NOT result in a new ProjectId.
Additionally, These members don't deliver good results:
Document.ProjectInformation.Id
Document.ProjectInformation.UniqueId

The soultion above proposed by The Building Coder will work, if you want to program some kind of uploader. You will then create a GUID and save it in the "invisible storage" called ExtensibleStorage, that only your program can read again.
The easiest apporach is:
ExportUtils.GetGBXMLDocumentId(Document);


text:
Q: Catalina Update: Calendar Crashes When Trying to Print, CalDAV Problems With Confluence Calendar Integration After a macOS Catalina update the calendar app crashes when I try to print the week overview. Also the integration of confluence calendars via calDAV has problems with the UI. The text of the calDAV entries only shows up when I modify the color. After some time calendar forgets this new setting and the text is gone again. Both problems appeared directly after the Catalina update.
Crash report:
Crashing on exception: cannot set button color to nil

If I remove the Confluence CALDAV account, printing works fine.


text:
Q: Logging local variable values with AspectJ I heard a lot of great things about how AOP could help modularize things like logging, but now as I am trying to implement this, I am finding AspectJ is very limited.
Not only is it sometimes impossible to add logging to the correct lines, but accessing local variable values seems very difficult. You have to make sure that variable is either returned by a method or used as arguments to a method.
The simple fact that the logging is outside of the scope of the code being logged is a severe limitation.
Is there a better approach to accessing local variable values for the purpose of logging them?
For example, I have some code that maintains a counter, and I want to log the value of that counter. The original code looked something like this:
int totalMoves = 0;

while(canMove()) {
    // ...
    totalMoves++;
}

Logger.log(totalMoves);

I can't find a clean way to move this logging code to an aspect. There's simply no way to access totalMoves as it is. It appears that my options are:

*

*Make totalMoves a publicly accessible field (in opposition to information hiding and encapsulation)

*Create a dummy function that does nothing but allow a "hook" for AspectJ (no better than just logging directly)

*Make totalMoves a private field, but use reflection to access it (seems like a bad code smell; creates an unnecessary field and complicates access to the variable)

To be honest, I guess what I was expecting when looking into AOP was inserting code verbatim to remove cross cutting concerns. These limitations make me question if AspectJ is even worth using in the current context.
Is there anyway around this issue? Or am I approaching this the wrong way? In which case, how can I cleanly log local variables?
TL;DR: Logging local variable values with AspectJ is a mess, how can I make it better?

A: This question has been asked many times before. The answer is no. AspectJ cannot intercept read/write operations on local variables, only on members. Besides, the JVM might optimise away some of your source code dealing with local variables under certain circumstances, but that is another topic.
Abusing AOP frameworks like that would not a good idea anyway, even if it was possible. They are made for decorating classes with additional functionality or intercepting some actions accessible from outside, not for hacking local state. What does it say about your application design if an aspect needs to know local variable names?
As for the three options you are mentioning, they are not the only ones you have. You can also make totalMoves a private field and provide a getter and/or a setter if that makes sense. Furthermore, even if you decide not to use getter/setter, you can still use a privileged aspect which is able to access private or protected fields in combination with get|set() pointcuts.
Feel free to ask if you do not understand this answer after reading the provided links.

A: Another option is to refactor that chunk of your code and extract a method out of it and add an aspect that logs its return value:
@Log
private int totalMoves() {
    int totalMoves = 0;

    while(canMove()) {
        // ...
        totalMoves++;
    }

    return totalMoves;
}


text:
Q: Ansible with a rotating sudo password I have a system that has a rotating token based sudo password that changes every 30 seconds or so.  I'm using Ansible with privilege escalation.  I know I can pass in the --ask-su-pass option - but the problem I've run into is at the time of asking the password is one thing - yet it changes by the time Ansible actually attempts to sudo.
Is there a way to get prompted at the time of sudo-ing?
Ansible Script
---
- name: Install & Setup Docker
  hosts: ece
  become: true

  tasks:
    - name: Install Required Packages
      yum:
        name:
          - "yum-utils"
          - "device-mapper-persistent-data"
          - "lvm2"
        state: latest
      register: yum_result

    - debug:
        var: yum_result
        verbosity: 2

What happens when I run:

PLAY [Install & Setup Docker]

TASK [Gathering Facts]
  ********************************************************************************************************************************************************* fatal: [xxxx]: FAILED! => {"changed": false, "module_stderr":
  "Shared connection to xxxx closed.\r\n", "module_stdout":
  "sudo: a password is required\r\n", "msg": "MODULE FAILURE\nSee
  stdout/stderr for the exact error", "rc": 1}
          to retry, use: --limit

So obviously I need a password for sudo.  The problem is the sudo password is a rotating password so every 30 seconds or so it changes
I can use the --ask-su-pass flag to enter a sudo password - but by the time i get to the first time its used i get:

fatal: [xxxx]: FAILED! => {"msg": "Incorrect sudo password"}

because the password has since changed since I've entered it.  Trying to figure out if i can get a prompt at the point where its trying to enter the sudo password on the remote system


text:
Q: Outlook - Get Daily Reminder of upcoming Event In Outlook 2016 I want to have a daily reminder for an event  which tells me the days left until the date of the event is reached.
Does someone found a solution for this specific need?


text:
Q: Weird double post call in sitefinity I have a very weird problem. Let's say I have two same forms/widgets on the same page , this is the code for the form:
<form>

  <input class="form-group" type="text" title="FirstName" name="FirstName" id="FirstName" />

  <input class="form-group" type="text" title="LastName" name="LastName" id="LastName" />

  <input class="form-group" type="tel" title="PhoneNumber" name="PhoneNumber" id="PhoneNumber" />

  @Html.DropDownListFor(m => m.HearingID, Model.Hierings, new { @id = "HearingID", @class = "form-group" })

  @Html.DropDownListFor(m => m.ConnectTypeID, Model.ConnectTypes, new { @id = "ConnectTypeID", @class = "form-group" })

  <input type="button" value="Save" id="@buttonid" />

</form>

And the following js sends an ajax request.

By the laws of logic it should send the post request one time, but for some weird reason the number of calls correlates with the number of forms on the page. So if I have two forms - it sends the request two times. I tried everything, even giving the form a unique id, and yet still - two requests. The JS isn't working two times, the JS works one time but it still sends the request two times, and I can't figure out why.

A: I think you should give your form a unique ID which is generated on the server. In this way, when you drag your widget twice on the page, it will be rendered with different IDs, and moreover the jQuery selector will look for the form with the right ID. Following is a sample code of how I managed to get only one submit when I drag the widget two times on the page:
@{
    // generate ID on the server
    string formId = System.Guid.NewGuid().ToString();
}
<form id="@formId">
    ...
</form>


text:
Q: Как округлить число до двух первых значащих цифр после запятой? К своему стыду никак не могу найти способ округлять числа так (до двух первых значащих цифр после запятой):
0,0003658313517468447045911834644229 -> 0,00037
0.15 -> 0.15
0.156 -> 0.16
0.006 -> 0.006
0.0066 -> 0.0066

Есть способ делать это из коробки?

A: У меня получилась такая функция:
import math

def round_to(num, digits=2):
    if num == 0: return 0
    scale = int(-math.floor(math.log10(abs(num - int(num))))) + digits - 1
    if scale < digits: scale = digits
    return round(num, scale)

# ну или оно же в виде однострочной лямбды
_round_to = lambda num, digits: 0 if num == 0 else round(num, max(int(-math.floor(math.log10(abs(num - int(num))))) + digits - 1, digits))

nums = [0.0003658313517468447045911834644229, 0.15, 0.156, 0.006, 0.0066]
print(*[(x, round_to(x)) for x in nums], sep="\n")

Результат:
(0.0003658313517468447, 0.00037)
(0.15, 0.15)
(0.156, 0.16)
(0.006, 0.006)
(0.0066, 0.0066)


text:
Q: Valgrind reports memory leak but I don't understand where it occurs I have written a forward linked list but when I run it through valgrind it reports an memory leak in my remove (const int function) and I can't quite figure out why.
This is the remove function that valgrind complains about.
The function is inside the file "list.cc".
void Plist::remove(const int pos)
{
  current_index = root;
  if( pos == 0 )
  {
    delete root;
    root = current_index -> pointer;
  }
  else
  {
    for(int n = 0; n<pos-1; ++n)
    {
      current_index = current_index -> pointer;
    }
    index * new_link = current_index -> pointer -> pointer;
    delete current_index -> pointer;
    current_index -> pointer = new_link;
  }
}

This is the header file "list.h" belonging to "list.cc".
class Plist
{
private:

  class index
  {
  public:
    index(int value, index * ptr);
    index(int value);
    int val{0};
    index * pointer{nullptr};
  };

  index * root = nullptr;
  index * current_index = nullptr;
public:
  Plist(){}
  ~Plist();
  Plist (Plist& lst);
  Plist& operator=(Plist& lst);
  void insert(const int val);
  void remove(const int pos);
  void print();
};

Any help is appreciated!

A: This isn't your bug, but this code can't be right:
current_index = root;
if( pos == 0 )
{
  delete root;
  root = current_index -> pointer;
}

Since current_index = root, the delete root means that current_index now points to a destroyed object, which you dereference in the next line. Oops.

A: Not the problem you asked about, but this code doesn't work:
current_index = root;
if( pos == 0 )
{
    delete root;
    root = current_index -> pointer;
}

After delete root the object pointed to by root or copies of root, e.g., current_index, are dead. You need something along those lines:
current_index = root;
if (pos == 0) {
    current_index = current_index->pointer;
    delete root;
    root = current_index;
}


text:
Q: Which argument is required for np.savetxt to output float data? I have a little piece of code which is running well, however I am struggling to determine a way of outputting it into a .txt file. Here is the code:
with open("Coord") as f:
    line=f.readline()
    for line in f:
        coords=map(float,line.split(" "))
        if poly.contains(Point(coords[0],coords[1])):
            print line

The print command works and displays what I need in the terminal, however I just can't manage to find a way to save this yet. Here is what I have tried so far:
np.savetxt('inside.txt', np.vstack((line.str())).T)

AttributeError: 'str' object has no attribute 'str'

np.savetxt('inside.txt', line)

IndexError: tuple index out of range

np.savetxt('inside.txt', np.transpose([line])

TypeError: float argument required, not numpy.string_

np.savetxt('inside.txt', line, delimiter=" ", fmt="%s")

IndexError: tuple index out of range

I am still quite inexperienced at python and code in general and was hoping somebody could explain the correct formatting to be used here. Thanks in advance.

A: From documentation , you can clearly see that np.savetext requires an array_like object as the second argument.
You can try converting line into an array before saving , something like -
np.savetxt('inside.txt', np.array(line.split(" ")), delimiter=" ", fmt="%s")


text:
Q: Error in class(x) while creating panel data using plm function I'm trying to create a Panel data using the plm function for pooling a model from a balanced Panel data that I imported from Excel.
When I run the code I get the following error:

Error in class(x) <- setdiff(class(x), "pseries") :    invalid to set
  the class to matrix unless the dimension attribute is of length 2 (was
  0)

library(plm)
library(readxl)
library(tidyr)
library(rJava)
library(xlsx)
library(xlsxjars)

all_met<- read_excel("data.xlsx", sheet = "all_met")
attach(all_met)

Y_all_met <- cbind(methane)
X_all_met <- cbind(gdp, ecogr, trade)

pdata_all_met <- plm.data(all_met, index=c("id","time"))

pooling_all_met <- plm(Y_all_met ~ X_all_met, data=pdata_all_met, model= "pooling")

After running the code I was supposed to get summary statistics of a pooled ols regression of my data. Can someone tell me how I can fix this issue? Thanks in advance.

A: 1st:
Avoid plm.data and use pdata.frame instead:
pdata_all_met <- pdata.frame(all_met, index=c("id","time"))

If plm.data does not give you a deprecation warning, use a newer version of the package.
2nd (and addressing the question):
Specify the column names in the formula, not the variables from the global environment if you use the data argument of plm, i.e., try this:
plm(methane ~ gdp + ecogr + trade, data=pdata_all_met, model= "pooling")

A: check in the structure of your data if variables used in the regression are declared as factor, you can do that by typing: str(all_met).
if yes, then you should declare it as double, or as numeric, (try not to use as.numeric() function, it could change values in your data).
personally i've changed that by the next specification in the import code:
data <- read_csv("C:/Users/Uness/Desktop/Mydata.csv",
    col_types = cols(variable1 = col_double(),
        variable2 = col_double()))
View(data)

where variable1 and variable2 are the names of the variables I use, make sure you change that if you copy the code ;)


text:
Q: Oracle 9i: How can I determine, using metadata, whether or not an index is clustered? The question pretty much sums this up, but I'll provide some more details.
I can almost safely assume that any primary key index in an Oracle database is clustered. But I'm not one to assume. Besides, a user might have created a clustered index that wasn't the primary key. If that's the case, I'd really like to know.
So, in the interests of being really, really thorough, I'd like to remember (not that I forgot or anything), how to determine from the Oracle metadata, whether or not an index is clustered.
(And, per usual, Google was like rooting through a landfill, looking for the vintage Action Comics #1 that your mom through out because she thought it was useless at the time.)
Thanks!

A: Oracle does not have the concept of "clustered indexes" as SQL Server does.  In general, Oracle table are "heaps" with the data stored in no particular order.  There is a special type of table called an INDEX ORGANIZED table, which is (as its name suggests) a table that is organised like an index.  However, in Oracle most tables would not be index organized - whereas my understanding is that most tables in SQL Server do have a clustered index.
Do not be tempted to declare all your Oracle tables as index organized in an attempt to emulate SQL Server; what is right for one DBMS is not necessarily right for another.  I suggest you read the Oracle Database Concepts guide to get to know how Oracle works.
Index organized tables are identified by IOT_TYPE = 'IOT' in ALL_TABLES and USER_TABLES.

A: What is known as a clustered index in SQL Server world is in Oracle world called an Index Organized Table. Table metadata is available in the all_tables or user_tables system views described here. My guess after skimming that link is that you can determine that a table is index-organized by checking whether the IOT_TYPE column is non-null.


text:
Q: How to transform the img to smaller size in TS or CSS Is there any way to resize the image and reduce it's weight in Angular/TS or in CSS? I mean something like 'picture' tag in HTML 5.1.

A: Resizing the image on the frontend won't change it's weight, as the full image has to be retrieved from the server anyways. The 'picture' tag isn't able to do this either.
The only thing coming close to what I believe you want to achieve is this Angular directive I found online:
https://github.com/oukan/angular-image-compress
This also only compresses on the client side and won't change the weight of the image retrieved in the first place.


text:
Q: how can I get datas from google analytics? how can I get datas from google analytics?

I want to use php or javascript to get some data from ga, and display tables in my web page.
but I don't know how to query dates from ga using api. Anyone tells how to do the job? or write down simple code to guide me. thank you

A: Well, there's php gdata client libary this should do what you ask


text:
Q: RoboGuice injection I am using this code in my Android app (RoboGuice library):
@Singleton
public class UserSessionProvider {

   private User user;

   @Inject
   private Injector injector;

   public synchronized User createSession() {
      this.user = injector.getInstance(User.class);
      return this.user;
   }

   public synchronized User getUser() {
      return user;
   }

   public synchronized void destroySession() {
      this.user = null;
   }

   public synchronized Boolean isSessionAlive() {
      return getUser() != null;
   }
}

Sometimes build gets bugged up, and application fails to inject instance of injector in this provider. When I clean app and rebuild it then it again works ok (for some time). I am using Gradle build chain and Android studio. Does anyone know how can I stop this from happening?


text:
Q: Refresh Control set to TableViewController works even without adding it as Sub View Here in the following code, a TableViewController is created and it's tableView and refreshControl properties are set. However even without adding the TableViewController as sub view to the View Controller view, the refresh control starts working. Was curious about how this is happening?
@IBOutlet weak var dashBoardTableView: UITableView!

let refreshControl = UIRefreshControl()

func configureRefreshControl()
{
    refreshControl.addTarget(self, action: #selector(self.pullToRefresh)  , for: .valueChanged)
    //UIRefreshControl will not work properly without embedding it in a UITableViewController
    let tableViewContainerVC = UITableViewController()
    tableViewContainerVC.tableView = dashBoardTableView
    tableViewContainerVC.refreshControl = refreshControl
}

A: It's very likely the apple developer did such thing in UITableViewController:
var refreshControl:UIRefreshControl {
    didSet{
        //......
        self.tableView.tableHeaderView?.addSubview(refreshControl)
        //......
    }
}

So the RefreshController works immediately after : tableViewContainerVC.refreshControl = refreshControl


text:
Q: twisted: check whether a deferred has already been called This is what I'm trying to accomplish. I'm making a remote call to a server for information, and I want to block to wait for the info. I created a function that returns a Deferred such that when the RPC comes in with the reply, the deferred is called. Then I have a function called from a thread that goes threads.blockingCallFromThread(reactor, deferredfunc, args).
If something goes wrong - for example, the server goes down - then the call will never un-block. I'd prefer the deferred to go off with an exception in these cases.
I partially succeeded. I have a deferred, onConnectionLost which goes off when the connection is lost. I modified my blocking call function to:
    deferred = deferredfunc(args)
    self.onConnectionLost.addCallback(lambda _: deferred.errback(
        failure.Failure(Exception("connection lost while getting run"))))
    result = threads.blockingCallFromThread(
        reactor, lambda _: deferred, None)
    return result

This works fine. If the server goes down, the connection is lost, and the errback is triggered. However, if the server does not go down and everything shuts down cleanly, onConnectionLost still gets fired, and the anonymous callback here attempts to trigger the errback, causing an AlreadyCalled exception to be raised.
Is there any neat way to check that a deferred has already been fired? I want to avoid wrapping it in a try/except block, but I can always resort to that if that's the only way.

A: There are ways, but you really shouldn't do it.  Your code that is firing the Deferred should be keeping track of whether it's fired the Deferred or not in the associated state.  Really, when you fire the Deferred, you should lose track of it so that it can get properly garbage collected; that way you never need to worry about calling it twice, since you won't have a reference to it any more.
Also, it looks like you're calling deferredfunc from the same thread that you're calling blockingCallFromThread.  Don't do that; functions which return Deferreds are most likely calling reactor APIs, and those APIs are not thread safe.  In fact, Deferred itself is not thread safe.  This is why it's blockingCallFromThread, not blockOnThisDeferredFromThread.  You should do blockingCallFromThread(reactor, deferredfunc, args).
If you really want errback-if-it's-been-called-otherwise-do-nothing behavior, you may want to cancel the Deferred.


text:
Q: Iterating through a html array in javascript Hi I have sevral selects on my page with the name viewer[].
In javascript I wish to iterate through this array and get each ones selected index.
  var welements = document.getElementsByName('viewer[]')[0];
      for ( var i in welements )
        {
        alert(i.selectedIndex);
          }

I have above but its clearly wrong. I beleive the first line is correct - document.getElementsByName returns an array so I just want the first (and only) result which is the viewer[] html array
Advice appreciated, thanks!

A: getElementsByName requires a NodeList, not an Array. NodeLists are very much like Arrays, but there are differences.
Either way, you shouldn't iterate over them using for (foo in bar) — that gets all the properties (including foo.length), not just the values you care about.
Use:
var welements = document.getElementsByName('viewer[]'); // Removed [0], that gets the **1st** node, not the NodeList.
for (var i = 0, j = welements.length; i < j; i++) {
    var an_element = welements[i];
    alert(an_element.selectedIndex);
}

A: Using "for each"(for in) in javascript returns all attributes inside the array that includes arrays prototypes attributes. So its not advised, better if you iterate like
for(var i=0; i < welements.length; i++){
  alert(welements[i].selectedIndex);

A: To iterate over an Array you shouldn't use the "for (i in array)" form.  That is bound to return items which are not the numeric indices of the array... other names like "length" and "items".
Use this instead:
var welements = document.getElementsByName('viewer[]');
for (var i = 0; i < welements.length; i++)
    {
    alert(welements[i].selectedIndex);
    }

Note as S.Mark said you don't want the [0] on the first line, as that is grabbing only the first item.  Or maybe you do want it... you're unclear on that.  You said you have multiple things named "viewer[]", yet you also imply you want only the first one.  If that is really true, then you don't need the loop at all!  welements.selectedIndex would already give you that value for the first "viewer[]" item.

A: 3 check points

*

*should be wlements[i] instead of i

*[0] will not needed on first line

*are you sure viewer[]? i think viewer only.

If me, I will do like this
var welements = document.getElementsByName('viewer');
for ( var i in welements ){
 alert(welements[i].selectedIndex);
}

If you only want first one, for loop is not needed
var welements = document.getElementsByName('viewer')[0];
alert(welements.selectedIndex);


text:
Q: The commutator of the product of 2 groups Let $G=H\times A$ be the internal product of $A$ and $H$,
I proved that if "$A$ is abelian then $G′=H′$ "
But if we were not given that $A$ is abelian is $G′=H′\times A′$ ?

A: Let's consider a typical generator of $G'$, by picking any two elements of $G$, namely $g_1 = (h_1,a_1)$ and $g_2 = (h_2,a_2)$, and forming their commutator:
\begin{align*}
[g_1,g_2] &= g_1 \cdot g_2 \cdot g_1^{-1} \cdot g_2^{-1} \\
&= (h_1,a_1) \cdot (h_2, a_2) \cdot (h_1^{-1},a_1^{-1}) \cdot (h_2^{-1},a_2^{-1}) \\
&= (h_1 \cdot h_2 \cdot h_1^{-1} \cdot h_2^{-1}, a_1 \cdot a_2 \cdot a_1^{-1} \cdot a_2^{-1} )\\
&= ([h_1,h_2],[a_1,a_2]) \\
&\in H' \times A'
\end{align*}
Since elements of the form $[g_1,g_2]$ are generators of $G'$, this proves that $G' < H' \times A'$. The opposite inclusion should be obvious. So yes, $G' = H' \times A'$.


text:
Q: Check how long it will take for tmutil restore to complete I'm restoring my HDD from a time machine backup from the terminal (so I can use my computer while it restores).
It's working but just seeing if there's a way to check how long it will take to finish?
I'm not tech-savvy so if there's an answer out there please explain in basic layman's terms
Cheers


text:
Q: What are the advantages of having a game loop implemented as a function? I learned that functions should perform a well-defined action and should be named  according to what they do. For example, a function that adds its two arguments could be written:
def adder(arg1, arg2):
    return arg1 + arg2

Here, adder has a well-defined role and its name says exactly what it does. Now, if a game loop was implemented as a function:
def mainloop(fps):

    while True:
        # DO STUFF
        tick(fps)

would it still be right to say that the function is doing something and has a well-defined role? If so, what exactly are the advantages of implementing the loop as a function instead  of leaving it in the global scope?

A: Due to an implementation detail, the same code in a function can run faster than when it is in the global namespace.

A: It would still be good form to have your loop outside of a function, there is nothing wrong with that. For one of my own pygame projects, I had to do that because otherwise there was scoping issues. An advantage of putting it into a function is that you could potentially access it from another python file:
from game import mainloop

mainloop(65)


text:
Q: How To Read Json File in GWT? {
    "employee": {
        "name":     "sachin",
        "salary":      56000,
    }
}

This is my json file.
now i want to only read it.
When i write last line,it gives me NullPointerException.
JSONValue value = JSONParser.parseLenient(json);
JSONObject employeeObject = value.isObject();
System.out.println(employeeObject.get("name").isString().stringValue());

A: It should be:
JSONValue value = JSONParser.parseStrict(json);
JSONObject employeeObject = (JSONObject) value.isObject().get("employee");

Currently you are not evaluating an object "employee" - you are evaluating a json object which has an "employee" object as its only child.


text:
Q: Merging two dataframes by multiple columns without losing data I am new to R and have two very large datasets I want to merge. They look as follows
      ID     year   val1  val3
 1     1     2001      2   34
 2     2     2004      1   25
 3     3     2003      3   36
 4     4     2003      2   46
 5     5     1999      1   55
 6     6     2005      3   44

The second dataframe is as follows
      ID     year   val2
 1     1     2001      2
 2     2     2004      1
 3     3     2003      3
 4     4     2002      5
 5     5     1998      4
 6     6     2004      6

I want the final merged set to look like this
      ID     year   val1  val3 val2
 1     1     2001      2   34     2
 2     2     2004      1   25     1
 3     3     2003      3   36     3
 4     4     2002     NA   NA     5
 5     4     2003      2   46    NA
 6     5     1998     NA   NA     4
 7     5     1999      1   55    NA
 8     6     2004     NA   NA     6
 9     6     2005      3   44    NA

I tried merging by ID and year using the following
 total <- merge(df1,df2,by=c("id","year"))

But this results in only merging if ID and year BOTH match. I want to it to happen so that if the ID matches but year doesn't match, a new row will add in the same ID the entry for year and val2 while leaving val1 and val3 as NA.
I then tried merging only by ID and then removing rows if year.x != year.y, but since the datasets were too large it wasn't very efficient.

A: merge has an argument all that specifies if you want to keep all rows from left and right side (i.e. all rows from x and all rows from y)
 total <- merge(df1,df2,by=c("id","year"), all=TRUE)

A: You must specify all.x=TRUE and all.y=TRUE so you keep all unique rows from both datasets
 total <- merge(df1,df2,by=c("id","year"),all.x=TRUE,all.y=TRUE)


text:
Q: shared_ptr with malloc and free I have working in large application which contain c and cpp. The all files saved as cpp extension but the code is written in c- style. I mean it is define structure rather than class allocate memory through malloc and realloc and calloc.In recent They have installed boost library So I am planning to use into my existing code base So I have some following question.

*

*Can I use std::shared_ptr with malloc and free.

*If yes, can anyone point out me sample code base?

*Will it impact any functionality if I create std::shared_ptr in my application and pass this pointer to another function, which uses malloc or calloc?

Or in other words:
How do I achieve the similar functionality with std::shared_ptr, for the following code:
void allocateBlocks(int **ptr, int *cnt)
{
    *ptr = (int*)malloc(sizeof(int) * 10);
    *cnt = 10;
    /*do something*/
}

int main()
{
    int *p = NULL;
    int count = 0;
    allocateBlocks(&p, &count);
    /*do something*/

    free(p);
}

We call some functions, which accept double pointer and fill the structure inside their application and use malloc. Can we assign those pointer to std::shared_ptr? For example:
typedef struct txn_s
{
    int s;
    int d;
    int *e;
} txn_t;

typedef boost::shared_ptr<txn_t> tpointer;

tpointer((txn_t*)::malloc(sizeof(txn_t),::free));

A: To use a std::shared_pointer with malloc() and free() you should specify a custom deleter. This should do it
std::shared_ptr<T> ptr(static_cast<T*>(malloc(sizeof(T))), free);

As long as you do not pass around the result of std::shared_ptr<T>::get(), your pointer is safe.
Edit: Added casting the result of malloc() to T*.

A:
Can I use shared_ptr with malloc and free.

Yes.

Can anyone point out me sample code base.

You need to provide a custom deleter, so that memory is released using free rather than the default delete. This can be a pointer to the free function itself:
shared_ptr<void> memory(malloc(1024), free);

Remember that malloc and free only deal with raw memory, and you're responsible for correctly creating and destroying any non-trivial objects you might want to keep in that memory.

if I create shared_ptr in my application and pass this pointer to another function if they are using malloc or calloc. will it impact any functionality.

I don't quite follow the question. You can use this shared_ptr interchangably with "normal" shared pointers, if that's what you're asking. Type erasure ensures that users of the pointers aren't affected by different types of deleter. As with any shared pointer, you have to be a bit careful if you extract the raw pointer with get(); specifically, don't do anything that might free it, since you've irrevocably assigned ownership to the shared pointer.

We have call some function which accept double pointer and fill the structure inside their application and use malloc Can we assign those pointer to shared_ptr.

I guess you mean something like:
double * make_stuff() {
   double * stuff = static_cast<double*>(malloc(whatever));
   put_stuff_in(stuff);
   return stuff;
}

shared_ptr<double> shared_stuff(make_stuff(), free);

UPDATE: I didn't spot the phrase "double pointer", by which I assume you mean the C-style use of a pointer to emulate a reference to emulate a return value; you can do that too:
void make_stuff(double ** stuff);

double * stuff = 0;
make_stuff(&stuff);
shared_ptr<double> shared_stuff(stuff, free);

How will handle with realloc and calloc

It's fine to initialise the shared pointer with the result of calloc, or anything else that returns memory to be released using free. You can't use realloc, since shared_ptr has taken ownership of the original pointer and won't release it without calling free.

A:
Can I use shared_ptr with malloc and free.
  if yes Can anyone point out me sample code base.

Yes. shared_ptr does not allocate memory itself. However, it does delete your object once reference count drops to zero. Since it uses delete by default and you cannot use it with objects allocated by malloc (or any other way), you have to use a custom deleter.

if I create shared_ptr in my application and pass this pointer to another function if they are using malloc or calloc. will it impact any functionality.

It is not clear what are you asking here. If that function does not expect a shared pointer be passed, then extra care have to be taken. But it depends on what that function actually does.

We have call some function which accept double pointer and fill the structure inside their application and use malloc Can we assign those pointer to shared_ptr.

Yes, you can use any pointer with shared_ptr.


text:
Q: Workbook_Open event changes other workbooks I have the code below in Workbook module:
Private Sub Workbook_Open()
Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",False)"
    Application.DisplayFormulaBar = False
    Application.DisplayStatusBar = Not Application.DisplayStatusBar
    ActiveWindow.DisplayWorkbookTabs = False
    ActiveWindow.DisplayHeadings = False
        Application.WindowState = xlMaximized
    ActiveSheet.UsedRange.Select
    ActiveWindow.Zoom = True
    Range("A1").Select
End Sub

But when I open the workbook in question, the settings in the code are also applied to all other workbooks that are opened. How could I limit the settings in the code to apply only to the workbook in question?
Best Regards
EDIT:
This solution does not work for me either:
Private Sub Workbook_Open()
With Me
    Application.WindowState = xlMaximized
    ActiveSheet.UsedRange.Select
    ActiveWindow.Zoom = True
    Range("A1").Select
    Application.ExecuteExcel4Macro "SHOW.TOOLBAR(""Ribbon"",False)"
    Application.DisplayFormulaBar = False
    Application.DisplayStatusBar = Not Application.DisplayStatusBar
    ActiveWindow.DisplayWorkbookTabs = False
    ActiveWindow.DisplayHeadings = False
    End With

End Sub

A: try this, add a With me in the line after the Private Sub Workbook_Open() like this
Private Sub Workbook_Open()
with me
'all the rest of the code
end with
end sub

it worked here


text:
Q: C# model view controller So I am creating a C#/Winforms application in a model-view-controller pattern. My view-controller needs to instantiate multiple groups of objects. The object groups are elements of the model and elements of the view. So for example a textbox and the model to go behind that text box.
I'm wondering if the best way to do this is to put everything in some sort of collection and tie them together with a key?

A: In the WinForm MVC apps I've built, I typically don't allow the controller to instantiate anything (I try and keep the "new" keyword out of my controllers).
If I need an object I ask a service for it, and internally that service is going to fetch that object from a data source (repository or the like), or in the case of a new object it will likely utilize some kind of factory to get me a new object (with any necessary pre-filled properties already set to default values, rules run, etc.).
The way I like to think about this sort of problem is this: how would I make this work (and make it reusable) if I didn't have a GUI for a view, but instead had a command-line input for my view? The logic to create/add/delete/update the model should be somewhere in your domain, not in the controller. Then the controller just becomes the mediator between the model and the view. The view becomes an I/O mechanism that is just a prettier version of a command-line interface.
Hope that makes sense.

A: Have you considered using WPF instead of WinForms?  It has a nicer MVC-like model and built-in databinding that is much more powerful.  It would probably solve your problem and help you build with more modern technology besides.

A: Perhaps you should design your model to match what the view needs? Then there would be only one model for the controller to pass on to the view.


text:
Q: Request variable from forEach loop jQuery I am trying to make a multiple choice questionnaire in node. I have a forEach loop printing the form for the questions and answer fields. Problem is that I can not get the correct variable in my jQuery file where I am doing the comparison.
Using a forEach loop in an EJS and checking it in a jQuery file.
jQuery File:
$(document).ready(function(){
    $('.bcheck').click(function(){
        var on = 1;
        var ans = $(this).attr('realanswer');
        var theirAns = $("input[placeholder=Answer]").val();
        console.log(ans);
        if(ans == theirAns){
            //DO SOMETHING
        }
    });
});

The value for var theirAns = $("input[placeholder=Answer]").val(); stays the first element in the iteration. Could I use the this function to get value of something that is not an element of the item I am clicking?
HTML for the EJS file:
<% topic.questions.forEach(function(question){ %>
    <% if(question.difficulty == 10){ %>
        <form action="/lesson/<%= lesson._id %>/topic/<%= topic._id %>/course/<%= question._id %>/quest?_method=PUT" method="POST">

            <%= question.question %>?

                    <input type="hidden" name="res[_id]" value="<%= question._id %>">
                    <input type="hidden" name="realAnswer" value="<%= question.answer %>">
                    <input id="correct" type="hidden" name="res[correct]" value="<%= false %>">

                    <% if(question.question_type == "multiple"){ %>
                        <% var ran = ranNumber(0, 3) %>
                        <% var n = 0; %>
                        <% question.wrong_answers.forEach(function(wAns){ %>
                            <div class="bw btn btn-success" value="<%= wAns %>"> <%= wAns %>

                            <% if(ran == n){ %>

<%= question.answer %>

                            <% }; %>
                            <% n += 1; %>
                        <% }); %>
                        <input type="hidden" name="res[answer]" value="<%= question.answer %>" placeholder="Answer">
                    <% }else{%>
                        <input type="text"   name="res[answer]" placeholder="Answer" >
                        </input>

                    <% }; %>

                        <div class="bcheck btn btn-primary pull-right" realanswer="<%= question.answer %>" >Check Answer

                    <% x += 1 %>

    <% }; %>
<% }); %>

A: You're trying to use $("input[placeholder=Answer]").val() - it will return the first value indeed.
If you want to check every element matching a selector $("input[placeholder=Answer]").each() will help. Here is an example based on your code snippet.

$(document).ready(function() {
  $('.bcheck').click(function() {
    var ans = $(this).data('realanswer');

    $("input[placeholder=Answer]").each(function() {
      var theirAns = Number($(this).val());

      if (ans === theirAns) {
        console.log('Nice');
      }
    });
  });
});

<button class="bcheck" data-realanswer="42">check</button>

<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">


text:
Q: how do I nest hidden field values together? Right now, this form submits a params hash with a questions hash containing all the questions, and a separate answers hash containing all the answers. I'd like to change the form so that the params hash submitted will have a questions hash containing all the questions, and each of those questions will themselves be a hash containing their own <%= f.hidden_field "question[#{question_counter}]", value: question.content %> (4 answers per question). How should I do this?
<%= form_for(:quiz_responses, url: quiz_responses_path) do |f| %>

<%= f.hidden_field :name, value: @survey.name %>

<% @questions.each do |question| %>
<ul>
<%= f.hidden_field "question[#{question_counter}]", value: question.content %>
<%= f.label question.content %>

<% question.answers.each do |answer| %>

<%= f.hidden_field "answer[#{answer_counter}]", value: answer.content %>
<% answer_counter += 1 %>
<%= f.label answer.content %>
<%= f.radio_button("user_answer[#{user_answer_counter}]", answer.content) %>

<% end %>
<% user_answer_counter += 1 %>
</ul>
<% question_counter += 1 %>
<% end #@questions.each do %>
<%= f.submit %>
<% end #form_for%>


text:
Q: Securing my website hosting server I am hosting my website on a linux server with php5 (no mySQL). Now I am the administrator, and I'm building my first website. I want to know about security, how do I secure my site from malicious injections and hackers? With the htaccess file? And what do I need to put in there?
Any help appreciated.
Thank you

A: If you have no SQL, you don't have to worry about injection attacks.
Security for your site depends on what you have running on your site.  If it's only PHP, I suggest keeping important code which may reveal things such as passwords and authentication keys or functions in a separate php file outside of your wwwroot and include them.
Example:
Your website runs in /home/wwwroot/
Put your php files with important data or functions in /home/privatephp/
Now in all your php files where you want to use those private functions or call on data that you want hidden, you simply use
include (../privatephp/privatestuff.php); at the top of each php file.
Your privatestuff.php file can contain such things as
$adminusername="imtheadmin"; or $adminpassword="adminpassword";
Then you can simply reference those variables in any PHP file where you have used the include command.


text:
Q: Charboost unable to set campaign priorities in admin portal Recently I was trying to add and configure campaign and its priorities in Charboost admin portal. I created static and video interstitials and navigated to campaign priorities section, As expected, both static and video interstitials showed up. But if I select low to static and high to video placements, after screen reload, both placement priority automatically reset to highest.
It was working fine a month ago..
But recently I saw this bug in all browsers. ..

A: I just got reply from Chartboost support. They are saying that they fixed this issue.
mail from cb support

Good to hear from you again. Are you still seeing this today? Our
  engineers had solved a similar problem yesterday (not exactly what
  you're describing), though I'm wondering if you could've possibly been
  affected by this.
  Are you familiar with the chrome console? If so, could you please open
  up the chrome console and click the network tab? With this open, go
  ahead and try making the change (make sure to click save), and the
  network tab will record the calls that are made or attempted to be
  made. A screenshot of this would be incredibly helpful.
I look forward to hearing from you and getting this resolved. Thanks
  for the follow-up, and take care.


text:
Q: What does "a line of type" mean? This example comes from a textbook on programming (Java For Dummies by Burd, 2011):

End-of-line comments: The text //I? You? in Listing 3-6 is an end-of-line comment. An end-of-line comment starts with two slashes and goes to the end of a line of type. Once again, the compiler doesn't translate the text inside the end-of-line comment.

How do you understand that?

A: The text is describing how a compiler or interpreter for some particular language identifies the difference between the logical end of a line and the physical end of a line of a source file.
Each line in that source file is, technically, "a line of type," or "typewritten characters." In reality, however, the phrase "of type" is implied in context and, therefore, redundant. The author could write "...goes to the end of a line" and convey the same information.


text:
Q: Managing the login information in RESTful web app In a RESTful application, there's no state maintained between two requests. Each request is treated as a completely new one, even though it would have been sent by the same user. I.e. There's no session.
In that case, how does the User Login information handled by a REST application?

*

*Is that, after a successful login, the server generates a security token and sends it to client and the client sends it back for each and every request there after?

*If above is true, where the security token is stored in server? Database? (Remember: No session).

A:
Is that, after a successful login, the server generates a security token and sends it to client and the client sends it back for each and every request there after?
  If above is true, where the security token is stored in server? Database? (Remember: No session).

Ehrm. Sending a token to the client which will be sent back on each subsequent request, only to retrieve information associated with that token from the database on the server-side? That's called a session. It's exactly what PHP sessions do, apart from storing the information in a file, instead of a database. You're recreating sessions.
Anyway, I think the "no session, no state" mantra is overrated and not very practical. I think it's more than okay to store a simple cookie that contains a token so you can identify a user, and associate (some) data with that user. Anyway, I think that not storing application state (e.g. what has the user previously done, and what is he doing now) is the most important.

A: Or you can have everything encrypted in token and each request can get all user information including name, timestamp, etc. from that token.
The only thing server would need to know, is the encoding/decoding algorithm.
Even better, the server can call authentication service (that could be totally independent box) to authenticate and authorize user.
Simple is always good !


text:
Q: get the number of runnable story files java Is there any way to get the number of all step implementations of the stories?
I would like to create a progress bar, but i have to know the number of runnable test cases.

A: Okay, solved. I/You don't have to count the steps, just simply put the control of the progress bar's increase to a @AfterScenario "step", and it will count in all of the skipped test cases and working charming with any number of steps.


text:
Q: Search Generic List for Id property I have a Generic List which can contain different class objects. Al these classes have the same base class which has a Id property.
I would like to do a search for the Id in the List and extract the first occourence, something like this
T result = myGenericList.Where(i => i.Id == id).FirstOrDefault()

However I cannot get to the properties, I only get as far as: i => i.
EDIT:
I'm asked to provide the code for the myGenericList. Here it goes:
    public static IEnumerable<T> Initialize()
{
  List<T> allCalls = new List<T>();

  var phoneCalls = new PhoneCall[]
  {
    new PhoneCall{Id = 1, Date= DateTime.Now.AddDays(-1), DurationSec = 60, Phone = "", Region = new Country { From = "", To = ""}},
    ...
  };
  foreach (PhoneCall s in phoneCalls)
  {
    allCalls.Add(s as T);
  }

  var dataCalls = new DataCall[]
  {
    new DataCall{Id = 6, WebData = 5120, Phone = "", Region = new Country { From = "", To = ""}},
    ...
  };
  foreach (DataCall s in dataCalls)
  {
    allCalls.Add(s as T);
  }

  var smsCalls = new SmsCall[]
  {
    new SmsCall{Id = 6, SmsData = 512, Phone = "", Region = new Country { From = "", To = ""}},
    ...
  };
  foreach (SmsCall s in smsCalls)
  {
    allCalls.Add(s as T);
  }

  return allCalls;

Regarding the T that is a class which I have defined at the top of my Repository.cs class
public class Repository<T> : IRepository<T> where T : class

A: What you should do is define what T is and not cast the items to T. As the compiler has no way to know what T is it does not know it has the Id property. Use a generic constraint to do so:
public static IEnumerable<T> Initialize<T where T : BaseClass>()
{
    var allCalls = new List<T>();
    allCalls.Add(new PhoneCall { /* Details */};
    return allCalls;
}

After question update - move the constraint from being one of the function to being one of the class

Also you can use the FirstOrDefault overload that gets a predicate:
var result = myGenericList.FirstOrDefault(i => i.Id == id);

A: Have you tried casting to the base class?
myGenericList
     .Cast<BaseClass>()
     .FirstOrDedault(i => i.Id === id)

Or alternatively
myGenericList.FirstOrDefault(i => (i as BaseClass).Id === id)


text:
Q: I need to split two dates into separate values I need some JavaScript to separate two dates shown like this 08 Oct - 12 Oct 2019 into separate values 10/08/2019 & 10/12/2019 when I scrape a website using Apify.
I've started using Apify to scrape some event data from a local theatre website so I can supply the same information on my own. The theatre company writes the start and end date within one paragraph tag which means it returns both dates in one cell.
In order for my website to use the theatre companies date data, I need each date to be formatted like this mm/dd/yyyy and I need each date to be separated into their own values. Is there a way with javascript to separate the dates in the example provided and format them into American date form?
As an example, this is one of the pages I'm scraping data from https://theatreroyal.com/whats-on/the-rocky-horror-show/
async function pageFunction(context) {
    const { request, log, jQuery } = context;

    const $ = jQuery;
    const title = $('title').text();

    log.info(`URL: ${request.url} TITLE: ${title}`);

    return {
        url: request.url,
        name: $('.c-pg-masthead-wrapper--events-fixed .c-pg-title').text(),
        date: $('.c-pg-masthead-wrapper--events-fixed .c-pg-subtitle').text().trim()
    };
}

Currently, the above script returns the date as it is written, ie 10 October - 12 Oct 2019 which is unusable for what I need.
I would really appreciate some help. Thanks in advance!

A: Here is a function that will return from and to
I used

*

*https://regex101.com/r/5fjHtF/1 to create the RegEx

*Destructuring assignment to create the vars from the match in one go

*The date constructor using

*Template literals and

*toLocaleDateString to format the date

const format = { month: '2-digit', day: '2-digit', year: 'numeric' };

const getDates = (dateStr) => {
  [_, fd, fm, td, tm, year] = dateStr.match(/(\d{2}) ([a-zA-Z]{3}) - (\d{2}) ([a-zA-Z]{3}) (\d{4})/);
  const from = new Date(`${fd} ${fm} ${year} 15:00:00`); // using 15:00 for dst reasons
  const to   = new Date(`${td} ${tm} ${year} 15:00:00`);
  return {
    "from": from.toLocaleDateString("en-US", format),
      "to":   to.toLocaleDateString("en-US", format)
  }
};

const date = '08 Oct - 12 Oct 2019'; // change to your date string
const dates = getDates(date); // how to call it
console.log(dates.from, dates.to); // how to use the dates returned

Here is a version that can handle strings that cross years

const format = { month: '2-digit', day: '2-digit', year: 'numeric' };

const getDates = (dateStr) => {
  const sameYear = dateStr.split(" ").length === 6; // dd mmm - dd mmm yyyy
  let fy="";
  if (sameYear) {
    [_, fd, fm, td, tm, year] = dateStr.match(/(\d{2}) ([a-zA-Z]{3}) - (\d{2}) ([a-zA-Z]{3}) (\d{4})/);
  }
  else {
    [_, fd, fm, fy, td, tm, year] = dateStr.match(/(\d{2}) ([a-zA-Z]{3}) (\d{4}) - (\d{2}) ([a-zA-Z]{3}) (\d{4})/);
  }
  const from = new Date(`${fd} ${fm} ${fy?fy:year} 15:00:00`); // using 15:00 for dst reasons
  const to   = new Date(`${td} ${tm} ${year} 15:00:00`);
  return {
    "from": from.toLocaleDateString("en-US", format),
      "to":   to.toLocaleDateString("en-US", format)
  }
};

const date1 = '08 Oct - 12 Oct 2019'; // change to your date string
const dates1 = getDates(date1); // how to call it
console.log(dates1.from, dates1.to); // how to use the dates returned

const date2 = '08 Dec 2019 - 12 Jan 2020'; // change to your date string
const dates2 = getDates(date2); // how to call it
console.log(dates2.from, dates2.to); // how to use the dates returned


text:
Q: How to parameterize these pretty hyperbolic (Amsler) surfaces? I've seen the attached images describing surfaces of negative curvature. I was wondering if there exist such surfaces with constant Gaussian negative curvature.
To this end, I attempted to model the surfaces by:
$$f(r,\theta)=A(r)\sin(n\theta)$$
And attempted to find $A(r)$ such that the surface would have a constant negative curvature, $K =const < 0$.
Unfortunately, the resulting differential equation is rather complex, and I not even sure it has a solution. So:

*

*Is there a surface of constant negative Gaussian curvature, that can be described by $A(r)\sin(n\theta)$, for some finite range of $r$?

*If not, are there other surfaces of constant negative $K$ that are similar to the images, and if so, what would be there
  parameterization?

Addendum:
It looks like theses surfaces are similar to Periodic Amsler surfaces, that are claimed to have constant Gaussian curvature. The paper in the link contains the following image, and it would be nice to understand how to parameterize them.


text:
Q: Make ListView from background of the stack scrollable I have a Stack that has some containers and horizontal listView at the very bottom of it.(Intentionally, it's a part of design). Now that I'm trying to scroll through it, it doesn't work because top container make it unreachable sort of. How can I remain the same widget tree but make the bottom listView scrollable?
return Stack(
    children: <Widget>[
      AnimatedBuilder(
                animation: ctrl,
        builder: (context, child){
          var pos = ctrl.position.pixels;
          return Container(
          height: pos<h?(pos/h * 250):250,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemBuilder: (ctxt, index){
              return Container(
                height: pos<h?(pos/h * 250):250,
                width: 250,
                child: Image(), //Horizontal listview
              );
            },
          ),
          );
        },
        ),
      ListView(
        controller: ctrl,
        children: <Widget>[
          AnimatedBuilder(
            animation: ctrl,
            builder: (context, child){
              var pos = ctrl.position.pixels;
              return Container(
                height: pos<h?(pos/h * 250):250,
              );
            },
          ),
          //This is the container I'm talking about, it's just like padding(It's nothing in there)
        ],
      ),
    ],
  );

A: You could put the ListView after the Container in the order inside the Stack, so it will be over the Container and you can interact with it.
Or you could wrap the Container with IgnorePointer, so the gestures won't be intercepted by the Container and you could interact with the ListView.


text:
Q: Wrong type interface implementation I am trying to follow Prisma's guide to setting up a GraphQL Go server.
Resolver.go
package main

import (
    "context"
    "prismago/hello-world/generated/prisma-client"
)

// Resolver struct
type Resolver struct {
    Prisma *prisma.Client
}

// Mutation MutationResolver
func (r *Resolver) Mutation() MutationResolver {
    return &mutationResolver{r}
}

// Post PostResolver
func (r *Resolver) Post() PostResolver {
    return &postResolver{r}
}

// Query QueryResolver
func (r *Resolver) Query() QueryResolver {
    return &queryResolver{r}
}

// User UserResolver
func (r *Resolver) User() UserResolver {
    return &userResolver{r}
}

type mutationResolver struct{ *Resolver }

func (r *mutationResolver) CreateUser(ctx context.Context, name string) (*prisma.User, error) {
    return r.Prisma.CreateUser(prisma.UserCreateInput{
        Name: name,
    }).Exec(ctx)
}
func (r *mutationResolver) CreateDraft(ctx context.Context, title string, userID string) (*prisma.Post, error) {
    return r.Prisma.CreatePost(prisma.PostCreateInput{
        Title: title,
        Author: &prisma.UserCreateOneWithoutPostsInput{
            Connect: &prisma.UserWhereUniqueInput{ID: &userID},
        },
    }).Exec(ctx)
}
func (r *mutationResolver) Publish(ctx context.Context, postID string) (*prisma.Post, error) {
    published := true
    return r.Prisma.UpdatePost(prisma.PostUpdateParams{
        Where: prisma.PostWhereUniqueInput{ID: &postID},
        Data:  prisma.PostUpdateInput{Published: &published},
    }).Exec(ctx)
}

type postResolver struct{ *Resolver }

func (r *postResolver) Author(ctx context.Context, obj *prisma.Post) (*prisma.User, error) {
    return r.Prisma.Post(prisma.PostWhereUniqueInput{ID: &obj.ID}).Author().Exec(ctx)
}

type queryResolver struct{ *Resolver }

func (r *queryResolver) PublishedPosts(ctx context.Context) ([]prisma.Post, error) {
    published := true
    return r.Prisma.Posts(&prisma.PostsParams{
        Where: &prisma.PostWhereInput{Published: &published},
    }).Exec(ctx)
}
func (r *queryResolver) Post(ctx context.Context, postID string) (*prisma.Post, error) {
    return r.Prisma.Post(prisma.PostWhereUniqueInput{ID: &postID}).Exec(ctx)
}
func (r *queryResolver) PostsByUser(ctx context.Context, userID string) ([]prisma.Post, error) {
    return r.Prisma.Posts(&prisma.PostsParams{
        Where: &prisma.PostWhereInput{
            Author: &prisma.UserWhereInput{
                ID: &userID,
            }},
    }).Exec(ctx)
}
func (r *queryResolver) Users(ctx context.Context) ([]prisma.User, error) {
    return r.Prisma.Users(&prisma.UsersParams{
        Where: &prisma.UserWhereInput{},
    }).Exec(ctx)
}

type userResolver struct{ *Resolver }

func (r *userResolver) Posts(ctx context.Context, obj *prisma.User) ([]prisma.Post, error) {
    return r.Prisma.User(prisma.UserWhereUniqueInput{ID: &obj.ID}).Posts(nil).Exec(ctx)
}

Running go run ./server generates the following error:
cannot use &userResolver literal (type *userResolver) as type UserResolver in return argument:
        *userResolver does not implement UserResolver (wrong type for Posts method)
                have Posts(context.Context, *"prismago/hello-world/generated/prisma-client".User) ([]"prismago/hello-world/generated/prisma-client".Post, error)
                want Posts(context.Context, *"prismago/hello-world/generated/prisma-client".User) ([]*"prismago/hello-world/generated/prisma-client".Post, error)

I tried to fix the type error:
func (r *userResolver) Posts(ctx context.Context, obj *prisma.User) ([]*prisma.Post, error) {
    return r.Prisma.User(prisma.UserWhereUniqueInput{ID: &obj.ID}).Posts(nil).Exec(ctx)
}

Error:
cannot use []"prismago/hello-world/generated/prisma-client".Post as type []*"prismago/hello-world/generated/prisma-client".Post in return argument

What am I doing wrong?
Related issue: https://github.com/99designs/gqlgen/issues/714

A: Modify the generated.go file interfaces to accept a return of []prisma.Post instead of []*prisma.Post.
Change:
type UserResolver interface {
    Posts(ctx context.Context, obj *prisma.User) ([]*prisma.Post, error)
}

To:
type UserResolver interface {
    Posts(ctx context.Context, obj *prisma.User) ([]prisma.Post, error)
}


text:
Q: Identically-valued pointers comparing unequal I came across this post https://stefansf.de/post/pointers-are-more-abstract-than-you-might-expect/ which mentions

C11 § 6.5.9 paragraph 6 Two pointers compare equal if and only if both
  are null pointers, both are pointers to the same object (including a
  pointer to an object and a subobject at its beginning) or function,
  both are pointers to one past the last element of the same array
  object, or one is a pointer to one past the end of one array object
  and the other is a pointer to the start of a different array object
  that happens to immediately follow the first array object in the
  address space.

as rationalization for why in this program may address b right after a and yet have &a+1 compare unequal to &b even though the printouts of the addresses are indentical
#include <stdio.h>
int main(void) {
    int a, b; int *p = &b; int *q = &a + 1;
    printf("%p %p %d\n", (void *)p, (void *)q, p == q);
}

This made me wonder that this cannot possibly be maintained across noninlinable function boundaries (or translation unit boundaries or DSO boundaries) so I tried:
#include <stdio.h>

#pragma GCC optimize "O2"
void addrcmp(void *a1_p, void *b_p)
{
    printf("%p %c= %p\n", a1_p,"!="[a1_p==b_p],b_p);
    int *a1p = a1_p;
    int *bp = b_p;
    a1p[-1] *= 10;
    bp[0] *= 10;
}

int main()
{
#if __clang__ /*clang appears to lay the variables in reverse order*/
    int b=1, a=2;
#else
    int a=1, b=2;
#endif
    printf("%p %c= %p\n", (void*)(&a+1),"!="[&a+1==&b],(void*)&b);
    printf("%d %d\n", a, b);
    addrcmp(&a+1,&b);
    printf("%d %d\n", a, b);
}

and indeed, this is getting me
0x7ffc38b8ec5c != 0x7ffc38b8ec5c
1 2
0x7ffc38b8ec5c == 0x7ffc38b8ec5c
10 20

with gcc (6.4), and even
0x7ffe5d0cee6c == 0x7ffe5d0cee6c
2 1
0x7ffe5d0cee6c == 0x7ffe5d0cee6c
20 10

with clang (3.4).
My question is, does the 6.5.9p6 rule even make sense? It seems impossible to track something like that efficiently.


text:
Q: DB-fiddle query not giving the same result as own mysql database I'm building a node.js app that sends a reminder when I set them.
These reminders get stored in a mysql database and I'm checking every minute if there are any reminders due.
So currently I have a bit of code that runs every minute and runs a query to see if the current time lines up with the remind-time. That should return a table with reminders that are due right now so I can iterate through them and remind people.
This sounds simple enough but I'm having loads of trouble with it.
I created a mock database on DB-fiddle because that works a lot nicer with testing queries and as expected, I easily created a query that returns any reminders that are due.
When I posted this query into my code however it just started returning 0 results and I can't figure out why.
This is the SQL I used to create and fill the table on DB-fiddle. (the list of DATETIMES is the date and time it is at the time of testing to actually see results returned)
I then created the following query:
Schema (MySQL v8.0)
CREATE TABLE IF NOT EXISTS `test` (
`id` int auto_increment primary key,
  `moment` datetime
);

INSERT INTO `test` (`moment`) VALUES
('2022-05-17 15:00:00'),
('2022-05-17 15:01:00'),
('2022-05-17 15:01:00'),
('2022-05-17 14:33:00'),
('2022-05-17 14:32:00'),
('2022-05-17 14:31:00'),
('2022-05-17 14:30:00'),
('2022-05-17 14:29:00'),
('2022-05-17 14:37:00'),
('2022-05-17 14:21:00');

Query #1
SELECT *, DATE_FORMAT(SEC_TO_TIME((ROUND(TIME_TO_SEC(NOW())/60)) * 60), '%Y-%m-%d %H:%i:%s') as current FROM test WHERE DATE_FORMAT(moment, '%Y-%m-%d %H:%i:%s') = DATE_FORMAT(SEC_TO_TIME((ROUND(TIME_TO_SEC(NOW())/60)) * 60), '%Y-%m-%d %H:%i:%s');

id
moment
current

2
2022-05-17 15:01:00
2022-05-17 15:01:00

3
2022-05-17 15:01:00
2022-05-17 15:01:00

View on DB Fiddle
This worked in DB-fiddle but not in my own database so I decided to paste these exact codes into my database to exactly recreate it. It still didn't work however and I can't figure it out.
Below is the relevant javascript code.
//Block of code that runs every minute
connection.query(`SELECT *, DATE_FORMAT(SEC_TO_TIME((ROUND(TIME_TO_SEC(NOW())/60)) * 60), '%Y-%m-%d %H:%i:%s') as current FROM Reminders WHERE DATE_FORMAT(moment, '%Y-%m-%d %H:%i:%s') = DATE_FORMAT(SEC_TO_TIME((ROUND(TIME_TO_SEC(NOW())/60)) * 60), '%Y-%m-%d %H:%i:%s')`, function (error, results, fields) {
console.log(results)
if (error) throw error;
});

This logs:
[]

Running SHOW VARIABLES LIKE "%version%"; in the mysql client returns that I have version 8.0.29 which is what I have selected in db-fiddle too.
I'm really confused and hope anybody can clear this up for me.


text:
Q: Traversing through subdirectories and create simillar directory structure & then process each file in sub directories I want to create a batch script to process the directory and files in
 that directory, Basically I am using one tool to convert files in
 directory to some format and it can take each file separately also can
 handle complete directory.Now i want to convert all the files in
 directory/sub directory with same directory structure, e.g., suppose I have 3 directories:
║
║═════ Folder 1
║         ║
║         ║══════ Folder A
║                     ║
║                     ║═════ File1.adt
║
║═════ Folder 5
          ║
          ║═════ File5.adt

Now i want the conversion of above files in same directure structure but can be at different location.
║
║═════ Folder 1
║         ║
║         ║══════ Folder A
║                     ║
║                     ║═════ File1.txt
║
║═════ Folder 5
          ║
          ║═════ File5.txt

A: you should use robocopy  for this:
robocopy /e "%source folder%" "%destination%"

-------------------------------------------------------------------------------
   ROBOCOPY     ::     Robust File Copy for Windows     ::     Version XP010
-------------------------------------------------------------------------------

  Started : Sun Aug 11 12:58:38 2013

          Usage :: ROBOCOPY source destination [file [file]...] [options]

         source :: Source Directory (drive:\path or \\server\share\path).
    destination :: Destination Dir  (drive:\path or \\server\share\path).
           file :: File(s) to copy  (names/wildcards: default is "*.*").

::
:: Copy options :
::
         /S :: copy Subdirectories, but not empty ones.
         /E :: copy subdirectories, including Empty ones.
         /LEV:n :: only copy the top n LEVels of the source directory tree.

         /Z :: copy files in restartable mode.
         /B :: copy files in Backup mode.
        /ZB :: use restartable mode; if access denied use Backup mode.

  /COPY:copyflag[s] :: what to COPY (default is /COPY:DAT).
               (copyflags : D=Data, A=Attributes, T=Timestamps).
               (S=Security=NTFS ACLs, O=Owner info, U=aUditing info).

           /SEC :: copy files with SECurity (equivalent to /COPY:DATS).
       /COPYALL :: COPY ALL file info (equivalent to /COPY:DATSOU).
        /NOCOPY :: COPY NO file info (useful with /PURGE).

         /PURGE :: delete dest files/dirs that no longer exist in source.
           /MIR :: MIRror a directory tree (equivalent to /E plus /PURGE).

           /MOV :: MOVe files (delete from source after copying).
          /MOVE :: MOVE files AND dirs (delete from source after copying).

       /A+:[RASHNT] :: add the given Attributes to copied files.
       /A-:[RASHNT] :: remove the given Attributes from copied files.

        /CREATE :: CREATE directory tree and zero-length files only.
           /FAT :: create destination files using 8.3 FAT file names only.
           /FFT :: assume FAT File Times (2-second granularity).
           /256 :: turn off very long path (> 256 characters) support.

         /MON:n :: MONitor source; run again when more than n changes seen.
         /MOT:m :: MOnitor source; run again in m minutes Time, if changed.

      /RH:hhmm-hhmm :: Run Hours - times when new copies may be started.
        /PF :: check run hours on a Per File (not per pass) basis.

         /IPG:n :: Inter-Packet Gap (ms), to free bandwidth on slow lines.

::
:: File Selection Options :
::
         /A :: copy only files with the Archive attribute set.
         /M :: copy only files with the Archive attribute and reset it.
    /IA:[RASHCNETO] :: Include only files with any of the given Attributes set.
    /XA:[RASHCNETO] :: eXclude files with any of the given Attributes set.

 /XF file [file]... :: eXclude Files matching given names/paths/wildcards.
 /XD dirs [dirs]... :: eXclude Directories matching given names/paths.

        /XC :: eXclude Changed files.
        /XN :: eXclude Newer files.
        /XO :: eXclude Older files.
        /XX :: eXclude eXtra files and directories.
        /XL :: eXclude Lonely files and directories.
        /IS :: Include Same files.
        /IT :: Include Tweaked files.

         /MAX:n :: MAXimum file size - exclude files bigger than n bytes.
         /MIN:n :: MINimum file size - exclude files smaller than n bytes.

      /MAXAGE:n :: MAXimum file AGE - exclude files older than n days/date.
      /MINAGE:n :: MINimum file AGE - exclude files newer than n days/date.
      /MAXLAD:n :: MAXimum Last Access Date - exclude files unused since n.
      /MINLAD:n :: MINimum Last Access Date - exclude files used since n.
               (If n < 1900 then n = n days, else n = YYYYMMDD date).

        /XJ :: eXclude Junction points. (normally included by default).

::
:: Retry Options :
::
           /R:n :: number of Retries on failed copies: default 1 million.
           /W:n :: Wait time between retries: default is 30 seconds.

           /REG :: Save /R:n and /W:n in the Registry as default settings.

           /TBD :: wait for sharenames To Be Defined (retry error 67).

::
:: Logging Options :
::
         /L :: List only - don't copy, timestamp or delete any files.
         /X :: report all eXtra files, not just those selected.
         /V :: produce Verbose output, showing skipped files.
        /TS :: include source file Time Stamps in the output.
        /FP :: include Full Pathname of files in the output.

        /NS :: No Size - don't log file sizes.
        /NC :: No Class - don't log file classes.
           /NFL :: No File List - don't log file names.
           /NDL :: No Directory List - don't log directory names.

        /NP :: No Progress - don't display % copied.
           /ETA :: show Estimated Time of Arrival of copied files.

      /LOG:file :: output status to LOG file (overwrite existing log).
     /LOG+:file :: output status to LOG file (append to existing log).

           /TEE :: output to console window, as well as the log file.

           /NJH :: No Job Header.
           /NJS :: No Job Summary.

::
:: Job Options :
::
       /JOB:jobname :: take parameters from the named JOB file.
      /SAVE:jobname :: SAVE parameters to the named job file
          /QUIT :: QUIT after processing command line (to view parameters).
          /NOSD :: NO Source Directory is specified.
          /NODD :: NO Destination Directory is specified.
        /IF :: Include the following Files.


text:
Q: Damaged built in screen, HDMI no signal I have an MSI Prestige PS63 laptop ( spec ) who's screen got destroyed in an accident. Even though the screen was broken I could connect the HDMI cable and use and external display with no problem but the laptop suddenly went Black, the external display does not display anymore. I have a dual boot of Windows and Ubuntu but my primary software is Windows. On boot it automatically selects windows unless I switch over to Ubuntu manually via Grub.When I switch the laptop on the external display blinks a bit as it recognizes a connection but then after a few seconds it says no signal. I have tested the hdmi cable and the external display and have figured the issue is not with those. I have tried removing ram sticks and putting them back, I have tried removing the battery and putting it back, I have tried resetting the bios with the CMOS battery button but none of these worked.
The laptop switches on and the keyboard lights up but does not display externally. I have also tried using an hdmi adapter on the usb c port but that also does not work.
How can I troubleshoot this and fix it?