text:
Q: memory allocation of char arrays in different contexts Let's say I have a struct:
typedef struct {
    int number1;  /* dummy */
    int number2;  /* dummy */
    int number3;  /* dummy */
    char *name1;
    char name2[];
} Klass;

and the rest of the code is:
int main(int argc, char const *argv[])
{
    char *name1 = "this is a name";            /* 1st case */
    char name2[] = "this is also a name";      /* 2nd case */

    Klass k;
    k.number1 = 10;
    k.number2 = 20;
    k.number3 = 30;
    k.name1 = "this is my first name";         /* 3rd case */

    /* error: invalid use of flexible array member */
    k.name2 = "this is my second name";

    Klass *kp = (Klass*)malloc(sizeof(Klass));
    kp->number1 = 100;
    kp->number2 = 200;
    kp->number3 = 300;
    kp->name1 = "this is also my first name";  /* 4th case */

    /* error: invalid use of flexible array member */
    kp->name2 = "this is my second name";

    return 0;
}

*

*Can anyone clarify for me how the memory is allocated (heap vs stack) in the marked cases?

*How should I free memory at the end of main block?

*What's the reason compiler is giving the error: invalid use of flexible array member?
EDIT
If you  say k.name = "this is my name"; and kp->name = "this is also my name"; is on the stack, can you explain how I can reach "this is my name" like this:
Klass *kp;

int foo() {
    Klass k;
    k.number1 = 10;
    k.number2 = 20;
    k.number3 = 30;
    k.name = "this is my name";
    kp = &k;
} // k is destroyed now

int main(int argc, char const *argv[])
{
    kp = (Klass*)malloc(sizeof(Klass));
    foo();
    printf("%d\n", kp->number1); /* segfault */
    printf("%d\n", kp->number2); /* segfault */
    printf("%d\n", kp->number3); /* segfault */
    printf("%s\n", kp->name);    /* prints "this is my name" */
    return 0;
}

A: The arrays of flexible length are meant to be used mostly with pointers.
Klass *kp = malloc( sizeof(Klass) + 100 );

This 100 are extra bytes that can be accessed via a name2 member. Usually there is a member of the structure used for storing a flexible part size.
Freeing this memory isn't any different from the one you would use for a regular structure.
The reason why compiler complains is that it's still an array (not a pointer) and you can't simply assign arrays. When you are accessing kp->name2 no additional indirection is introduced (unlike in the case when name2 is a pointer).
As for memory allocation:
1) name1 is a pointer to some memory region (most likely read-only memory) where a string literal is stored (bytes that comprise a char array with terminating 0). Trying to modify a string that name1 points at will result in an undefined behavior (you are not allowed to modify string literals).
2) name2 is an array and it's on the stack. You can freely modify its contents. The initialization code that puts a string literal to this array might be different among different platforms and compilers. I have even seen a disassembly, where a string literal is in read-only memory region (.rodata) and it's simply memcpy'ed to `name2.
3) and 4) are the attempts to assign to arrays which is illegal.

A: *

*
*

*The memory for the string is in a static region, which is where all string constants live. name1 is just a pointer to that region.

*The memory has automatic storage ("on the stack").

*Same as in case 1.

*Yes, since you've called malloc. Every malloc must be mirrored by a call to free.

*In Klass, the member name2 is a flexible array member, whose size is unknown to the compiler (and for which, btw., you haven't allocated any memory in the malloc call). Also, you can't directly copy arrays in C; had you allocated enough memory, you could use memcpy or strcpy.

A: char *name1 = "this is a name";            /* 1st case */

This just allocates a pointer, setting it to point to the string (which is kept as static data).
char name2[] = "this is also a name";      /* 2nd case */

This is short for char name2[sizeof(init_string)] = "this is also a name"; and allocates enough space to store the characters in the string.
Your third case
char name2[];

allocates no space at all! There is nowhere to store a string (which would have had to be copied using strcpy anyway).
The 4th case
kp->name1 = "this is also my first name";  /* 4th case */

is similar to case 1 - name1 is a pointer that is set to point to a static text.

A: The only moment when you should free the memory yourself is when you come to (m)alloc something, or call a function which do so (strdup(), ...)
In case 1,3 and 4 you are allocation the string on the stack, those string won't be available when you go out of your function. The 2nd case is a bit tricky, but this string is hardcoded in the executable, and you can not modify it (You would have a segmentation fault if you try to do so).
You can not make name2 poiting to a string, as name2 is not a pointer, but an array.


text:
Q: Ошибка миграции There is already an object named 'Permission' in the database Не понимаю, постоянно ловлю ошибки например

There is already an object named 'Permission' in the database.

из за чего постоянно дропаю бд и запускаю миграцию с нуля, что сводит меня с ума. Таблица уже существует в БД Permission я добавляю новое поле, которое foreignkey
Модели:
public class Permission
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
}

public class PermissionRole
{
    public int Id { get; set; }
    [ForeignKey("RoleFK")]
    public ICollection<MyIdentityRole> Roles { get; set; }
    [ForeignKey("PermissionFK")]
    public ICollection<Permission> Permissions { get; set; }
}

public class MyIdentityRole : IdentityRole
{
    public string AltName { get; set; }

    [ForeignKey("MyIdentityRoleFK")]
    public Permission Permission { get; set; }

    public MyIdentityRole() : base() { }
    public MyIdentityRole(string name, string altName)
   : base(name)
    {
        AltName = altName;
    }
}

Все таблицы согласно моделей уже по средством предыдущих миграций были созданы в БД. Сейчас я создал модель PermissionRole и добавил два внешних ключа. По логике он должен создать таблицу(PermissionRole) и добавить по столбцу в существующие таблицы, но он почему то пытаться создать их снова вместо alter table делает create подскажите, что я делаю не так?(Я так уже нажарился, что ручками 100 раз бы уже всю структуру БД сделал бы)

redpajama_set_name: RedPajamaStackExchange


text:
Q: unrestorable checkpoint error when selection.AbstractCashSelection.unconsumedCashStatesForSpending - Coin selection failed whenever coin selection fails, "unrestorable checkpoint" exception is thrown.
I am testing out scheduled event functionality, when an IOU is created, an event is scheduled to do payment at a specific time. from the error logs (see below), whenever coin selection fails, unrestorable checkpoint" exception is thrown, but the process continues to run, retries until coin selection is successful.
The exception stack doesn't provide info on where the error could be, how can I debug this?
@Suspendable
    public List<StateAndRef<Cash.State>> getFunds(Set<AbstractParty> issuers, Amount<Currency> amt) {

        try {
            AbstractCashSelection db = AbstractCashSelection.Companion.getInstance( () -> {
                    try {
                        return this.serviceHub.jdbcSession().getMetaData();
                    }catch(Exception e) {
                        throw new RuntimeException("getFunds error", e);
                    }
                });

            List<StateAndRef<Cash.State>> funds = db.unconsumedCashStatesForSpending(this.serviceHub, amt, issuers, null, this.flowRunId, new HashSet<OpaqueBytes>());
            funds.forEach(s -> {
                states.put(StateAndRefSerializer.getRef(s), s);
            });
            return funds;
        }catch(Exception e) {
            throw new FlowException("getFunds error", e);
        }
    }

Error from log file:

INFO ] 2019-07-21T20:52:07,683Z [Node thread-1]
  IOU_nextScheduledActivity.info - com.example.iou.autopaymentImplis
  scheduled at 2019-07-21T20:52:07.678Z,
  flowRef=com.example.iou.autopaymentImpl {actor_id=internalShell,
  actor_owning_identity=O=charlie, L=New York, C=US,
  actor_store_id=NODE_CONFIG, fiber-id=10000002,
  flow-id=0eebd34b-92be-4af5-a650-2d49675702c3,
  invocation_id=35bd0d5c-ea00-4a7d-972d-ff353bb9d2ec,
  invocation_timestamp=2019-07-21T20:51:57.700Z, origin=internalShell,
  session_id=13825f94-0f7c-4df7-80e2-c73511031bc7,
  session_timestamp=2019-07-21T20:51:57.304Z, thread-id=229,
  tx_id=D0EDC810EF00AFC9E99494F2DEF50AD040F439DAE3FC554BBC7698B9DCBA6073}
  [INFO ] 2019-07-21T20:52:07,699Z [Node thread-1]
  corda.flow.notariseAndRecord - Recorded transaction locally
  successfully. {actor_id=internalShell,
  actor_owning_identity=O=charlie, L=New York, C=US,
  actor_store_id=NODE_CONFIG, fiber-id=10000002,
  flow-id=0eebd34b-92be-4af5-a650-2d49675702c3,
  invocation_id=35bd0d5c-ea00-4a7d-972d-ff353bb9d2ec,
  invocation_timestamp=2019-07-21T20:51:57.700Z, origin=internalShell,
  session_id=13825f94-0f7c-4df7-80e2-c73511031bc7,
  session_timestamp=2019-07-21T20:51:57.304Z, thread-id=229,
  tx_id=D0EDC810EF00AFC9E99494F2DEF50AD040F439DAE3FC554BBC7698B9DCBA6073}
  [INFO ] 2019-07-21T20:52:07,840Z [pool-6-thread-1]
  IOU_nextScheduledActivity.info - com.example.iou.autopaymentImplis
  scheduled at 2019-07-21T20:52:07.839Z,
  flowRef=com.example.iou.autopaymentImpl [INFO ]
  2019-07-21T20:52:07,891Z [Node thread-1] corda.flow.call - autopayment
  is triggered by a schedulable event {fiber-id=10000003,
  flow-id=c8d1be17-aa32-4a73-b031-fff2707ed877,
  invocation_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  invocation_timestamp=2019-07-21T20:52:07.842Z, origin=Scheduler,
  session_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  session_timestamp=2019-07-21T20:52:07.842Z, thread-id=229} [INFO ]
  2019-07-21T20:52:07,897Z [Node thread-1] corda.flow.info - flow
  autopayment is started {fiber-id=10000003,
  flow-id=c8d1be17-aa32-4a73-b031-fff2707ed877,
  invocation_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  invocation_timestamp=2019-07-21T20:52:07.842Z, origin=Scheduler,
  session_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  session_timestamp=2019-07-21T20:52:07.842Z, thread-id=229} [INFO ]
  2019-07-21T20:52:07,912Z [Node thread-1] corda.flow.info - autopayment
  is completed {fiber-id=10000003,
  flow-id=c8d1be17-aa32-4a73-b031-fff2707ed877,
  invocation_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  invocation_timestamp=2019-07-21T20:52:07.842Z, origin=Scheduler,
  session_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  session_timestamp=2019-07-21T20:52:07.842Z, thread-id=229} [INFO ]
  2019-07-21T20:52:07,915Z [Node thread-1]
  corda.flow.createSubflowObject - autopayment to invoke flow
  com.charlie.iou.flows.SettleIOUInitiatorImpl {fiber-id=10000003,
  flow-id=c8d1be17-aa32-4a73-b031-fff2707ed877,
  invocation_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  invocation_timestamp=2019-07-21T20:52:07.842Z, origin=Scheduler,
  session_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  session_timestamp=2019-07-21T20:52:07.842Z, thread-id=229} [INFO ]
  2019-07-21T20:52:07,922Z [Node thread-1] corda.flow.info - flow
  SettleIOU startred {fiber-id=10000003,
  flow-id=c8d1be17-aa32-4a73-b031-fff2707ed877,
  invocation_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  invocation_timestamp=2019-07-21T20:52:07.842Z, origin=Scheduler,
  session_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  session_timestamp=2019-07-21T20:52:07.842Z, thread-id=229} [INFO ]
  2019-07-21T20:52:08,062Z [Node thread-1] corda.flow.lambda$eval$3 -
  txbuilder::build commands, cmd=Move,
  keys=["GfHq2tTVk9z4eXgyGKLLbMNy9c7hZ3XmrUEpRayxezT7VanQYX7c61RPCedL","GfHq2tTVk9z4eXgyQbQ5fnon7qDegNzvJ4s71djeDtZVSfoA466yXun6CLcK","GfHq2tTVk9z4eXgyV2oK18JdGAUozHXddWjBCFoMMKhMz5taj1qUyVYWBBfi"]
  {fiber-id=10000003, flow-id=c8d1be17-aa32-4a73-b031-fff2707ed877,
  invocation_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  invocation_timestamp=2019-07-21T20:52:07.842Z, origin=Scheduler,
  session_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  session_timestamp=2019-07-21T20:52:07.842Z, thread-id=229} [INFO ]
  2019-07-21T20:52:08,063Z [Node thread-1] corda.flow.eval -
  txbuilder::build commands, cmd=com.example.iou.SettleIOU,
  keys=["GfHq2tTVk9z4eXgyQbQ5fnon7qDegNzvJ4s71djeDtZVSfoA466yXun6CLcK","GfHq2tTVk9z4eXgySdF6Vz2jjYaaUP61nQVBgMJUAvmnhhWGA34bUwC9CaVn","GfHq2tTVk9z4eXgyV2oK18JdGAUozHXddWjBCFoMMKhMz5taj1qUyVYWBBfi"]
  {fiber-id=10000003, flow-id=c8d1be17-aa32-4a73-b031-fff2707ed877,
  invocation_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  invocation_timestamp=2019-07-21T20:52:07.842Z, origin=Scheduler,
  session_id=09dbdf92-55cb-4bcc-8ce9-5eae3103a740,
  session_timestamp=2019-07-21T20:52:07.842Z, thread-id=229} [INFO ]
  2019-07-21T20:52:08,337Z [Node thread-1] corda.flow.call - Party
  O=bob, L=New York, C=US received the transaction.
  {actor_id=internalShell, actor_owning_identity=O=charlie, L=New York,
  C=US, actor_store_id=NODE_CONFIG, fiber-id=10000002,
  flow-id=0eebd34b-92be-4af5-a650-2d49675702c3,
  invocation_id=35bd0d5c-ea00-4a7d-972d-ff353bb9d2ec,
  invocation_timestamp=2019-07-21T20:51:57.700Z, origin=internalShell,
  session_id=13825f94-0f7c-4df7-80e2-c73511031bc7,
  session_timestamp=2019-07-21T20:51:57.304Z, thread-id=229,
  tx_id=D0EDC810EF00AFC9E99494F2DEF50AD040F439DAE3FC554BBC7698B9DCBA6073}
  [INFO ] 2019-07-21T20:52:08,338Z [Node thread-1] corda.flow.call - All
  parties received the transaction successfully.

A: In our recent release of the TokenSDK 1.1, we have officially introduced the token-selection pack.
Here is the link for the binary file: https://ci-artifactory.corda.r3cev.com/artifactory/webapp/#/artifacts/browse/tree/General/corda-lib/com/r3/corda/lib/tokens/tokens-selection
And here is an example of how to import the dependencies to your project: https://github.com/corda/samples-java/blob/master/Accounts/worldcupticketbooking/build.gradle#L120
And here is how you use it:
Pair<List<StateAndRef<FungibleToken>>, List<FungibleToken>> inputsAndOutputs =
                tokenSelection.generateMove(Arrays.asList(partyAndAmount), buyerAccount, new TokenQueryBy(), getRunId().getUuid());


text:
Q: What is article_set ? How does it works? from django.db import models

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

    class Meta:
        ordering = ('headline',)

Now in python shell:
from datetime import date

r = Reporter(first_name='John', last_name='Smith', email='john@example.com'
r.save()

new_article = r.article_set.create(headline="John's second story",
pub_date=date(2005, 7, 29))

Above code is referenced from Django docs. If there is any misunderstanding please go to this link.

A: article_set is a backward relation to the articles from your reporter object.
Django creates this "hidden" fields because of the ForeignKey reporter in your Article model.
See this part of the doc.

If a model has a ForeignKey, instances of the foreign-key model will
  have access to a Manager that returns all instances of the first
  model. By default, this Manager is named FOO_set, where FOO is the
  source model name, lowercased. This Manager returns QuerySets, which
  can be filtered and manipulated as described in the "Retrieving
  objects" section above.

You can access the reporter from an article instance like this:
article_instance.reporter

And you can access the articles from a reporter like this:
reporter_instance.article_set.all()


text:
Q: Нелёгкая задача с формой(сложно)
ВНИМАНИЕ, МОЖЕТ ЗАНЯТЬ МНОГО ВРЕМЕНИ И НЕРВОВ!
При практике попалась интересная форма.
Не при фокусе там стоит подсказка, когда есть фокус подсказка изчезает и вводиться текст, когда текст введен подсказка снова появляется но то что мы вводили переходит на право, как с FORD
Если есть какие вопросу, отвечу, помогите пожалуйста решит задачу

A:

function blurBrand() {
  var input = document.getElementById("brandInput");
  var span = document.getElementById("brandDisplay");
  span.textContent = input.value;
  input.value = "";
  input.placeholder = "Brand";
}

function focusBrand() {
  var input = document.getElementById("brandInput");
  input.placeholder = "";
}
input {
  border:none;
}
<input id="brandInput" type="text" placeholder="Brand"
  onfocus="focusBrand()" onblur="blurBrand()"/>


text:
Q: ggplot + spss multiple response variables I have a dataset that looks somewhat like this:
data <- data.frame (id = c(1,2,3), V1 = c(2,3,4), V2 = c(1,2,3), Group = c(1,2,1))

V1 and V2 are actually 2 characteristics of the same variable, let's say variable V.
I am trying to make a ggplot where I can actually visualize how many V variables I have present on my population, filtered by variable group. But this gets tricky since I don't want to double account responses (2 times some V characteristic but still only 1 person has it not 2)
After actually having this solved how can ggplot show the actual label stored on the spss instead of values 1,2,3,etc.


text:
Q: How to create a Server using ServerSocket to connect two or more client device via wifi Am trying to connect (using ServerSocket for server) to android device via wifi. But the problems seems to be the ip of the server. what ip can i use, or is there some other way round.
-Code Sample
//ServerSide
WifiManager wmanager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
String addr = String.valueOf(wmanager.getConnectionInfo().getIpAddress());
ServerSocket server = ServerSocket(3000, 3, InetAddress.getByName(addr));
Socket s = server.accept();

//ClientSide
//Howerver testing with terminal<telnet: open wifiIp 3000> returns connection error.


text:
Q: Drag and Drop: Trying to understand DropDemo tutorial I'm working on Drag and Drop right now, and I've found an interesting tutorial on Oracle's website on custom TransferHandlers, etc. etc. etc. Anyway, I've been staring at the source code for the custom handler in the DropDemo program they provide, and it's driving me crazy.
What's confusing me is that there appear to be a whole bunch of methods that aren't invoked: importData(), importString(), and exportDone(). They all appear to serve vital functions, and all must be triggered at some point, but I can't seem to see where in the program these methods are being called.
I'm ultimately trying to understand how DropDemo offers the ability to re-order a JList through drag and drop, since I have so far been unable to replicate this. However, this has morphed into my larger question.

A: Transferable#importData(TransferHandler.TransferSupport)

Causes a transfer to occur from a clipboard or a drag and drop
  operation. The Transferable to be imported and the component to
  transfer to are contained within the TransferSupport. While the drag
  and drop implementation calls canImport to determine the suitability
  of a transfer before calling this method, the implementation of paste
  does not. As such, it cannot be assumed that the transfer is
  acceptable upon a call to this method for paste. It is recommended
  that canImport be explicitly called to cover this case.
Note: The TransferSupport object passed to this method is only valid
  for the duration of the method call. It is undefined what values it
  may contain after this method returns.

Basically, this is called when the component which the Transferable is associated it detects an "import" event.  This is the opportunity for the Transferable to physically import the data from the TransferHandler.TransferSupport based on it's requirements
Transferable#exportDone

Invoked after data has been exported. This method should remove the
  data that was transferred if the action was MOVE. This method is
  implemented to do nothing since MOVE is not a supported action of this
  implementation (getSourceActions does not include MOVE).

This is called on the instance of Transferable which initiated the export process, telling it what action was taken by the receiver of the transfer so it can take appropriate action
It should be noted that not all the methods have to be called, for example, if you're exporting the data, then you would not be notified of the importData method.  Equally, if the transfer it is never completed successfully, then exportDone may not be called.
These methods are triggered by core D'n'D subsystem, ontop of which the Transferable API sits and are done in response to lower level events.  You don't really need to "know" how they are called, but need to know what to do "when" they are called.  This is a bit more of the "black magic" of event driven program.

I'm ultimately trying to understand how DropDemo offers the ability to re-order a JList through drag and drop, since I have so far been unable to replicate this. However, this has morphed into my larger question. So thanks in advance.

For example


text:
Q: Set option of select form with JavaFX webengine.executeScript() I'm building a webcrawler with UI using JavaFX. I'm trying to preselect birthday day, month and year. So there is three select blocks. Unfortunately, there is no id, just a name 'birthday.day', 'birthday.month' and 'birthday.year' respectively.
I can fill other elements of the form like username and password, but no luck on a select so far. Here is what i tried:
engine.executeScript("document.getElementsByTagName('select')[0].options[0].selected='selected'");
engine.executeScript("document.getElementsByName('birthday.month')[0].selectedIndex=2");
engine.executeScript("document.getElementsByName('birthday.year')[0].selectedIndex=2");`


text:
Q: Sporadically SqlDataReader doesn't fill DataTable We've got some code to manage SQL-Connections. The class keeps the connection open for faster access to the database. Last week i recognized, that sporadically a DataTable is created but not filled with any Data. It happens when the software stays unused for some time. I could catched it in a Debug-Session but after i run the part of code for a second time, it returned a filled table like expected.
Our customer uses the same software on other machines since some months and didn't got this problem yet. Only on a new selled system this happens. But its the same SQL-Server and Databank. Has anyone an Idea why? Is there any timeout or something like this?
Thank you in advance
public class DBEncaps
{
    public SqlConnection oSqlDbConnection = null;

    public void OpenDb (string _sOpenString )
    {
        this.oSqlDbConnection = new SqlConnection(this.sConnectionString);
        this.oSqlDbConnection.Open();
    }

    public DataTable GetTable (string _sSql, string _sTableName)
    {
        DataTable oTable = null;
        SqlCommand oSqlDbCmd = new SqlCommand(_sSql, this.oSqlDbConnection);
        SqlDataAdapter oSqlAdapter = new SqlDataAdapter(oSqlDbCmd);
        oSqlAdapter.Fill(oTable);
    }
}

void CallingFunction()
{
    DBEncaps encap = new DBEncaps();
    encap.OpenDb ("Server=127.0.0.1; Database=foo; Trusted_Connection=yes");
    Datatable someTable = encap.GetTable("SELECT * FROM dbo.bar");
}


text:
Q: C# SQL database access I need your help.  I'm trying to get into servers on my own. I was searching yesterday about it a bit, I saw one code here and also tried one from a YT video. Not exactly sure what I'm doing. I've created an online SQL database on this page https://remotemysql.com/. I've created a database and table and manually assigned some values for further testing.  Then I started to look for some code to open the database

using MySql.Data.MySqlClient;
using System;

namespace SQLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world"); //for testing
            string server = "Momoos-PC";
            string database = "Score";
            string uid = "iqWUaqal5x";
            string password = "Q4tcOaJXdW";
            string connectionString;
            connectionString = "SERVER=" + server + "; PORT = 3306 ;" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
            MySqlConnection mycon = new MySqlConnection(connectionString);
            mycon.Open(); //error
            Console.WriteLine("Connection Open  !");
            mycon.Close();
        }
    }
}

So I understand that there is a need for some connection string but I'm not sure how it should look like or what library to use (mysqlconnection/sqlconnection).
string server - I'm not sure what to write here but when I'm in the PHPmyAdmin it says Server: localhost, But it shouldn't be because it's online no? So I wrote the localhost as my PC's name. Idk.
Then there is a string database. Don't know if they mean the name of the database - like the thing that contains all small tables or they mean the exact table to which to connect. Score is the name of table containing some values.
UID is I think username for logging into the database - I used the one I use to access PHPMyAdmin. (You can use it too, It's just free database, nothing important in it)
Password - password used to log into PHPMyAdmin.
Yes, and the error, AggregateException: 192.168.100.3:3306 No connection could be made because the target machine actively refused it. 192.168.100.3:3306
Please help me or point me to a good tutorial. I would like to have an online SQL server. Most of tutorials are for local server - Idk, should I watch them? Is it the same as an online server? How to make the transition to online then?

A: From the info given in your code then you should be able to connect remotely to that database with these changes
string server = "removemysql.com";
string database = "iqWUaqal5x";
string uid = "iqWUaqal5x";
string password = "Q4tcOaJXdW";
string connectionString;
connectionString = $"SERVER={server};PORT=3306;DATABASE={database};UID={uid};PASSWORD={password};";

Notice that I assume that the database name is the same as your user name. I have tried to use this service (and at first sight it seems pretty done) and the first database has the same name as the user.
IMPORTANT
Be sure to read their FAQ. The limitations on their service could be a problem for real applications.

A: Try if that works. I believe the issue was the incorrect server name. Also, when you use Uid as user id, try to use Pwd for password.
Check out the official docs on the same : https://remotemysql.com/tutor4.html
Please edit the answer and remove if those are actual credentials.
using MySql.Data.MySqlClient;
using System;

namespace SQLTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world"); //for testing
            string server = "remotemysql.com";
            string database = "Score";
            string uid = "xxxx";
            string password = "xxxx";
            string connectionString;
            connectionString = "SERVER=" + server + "; PORT = 3306 ;" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PWD=" + password + ";";
            MySqlConnection mycon = new MySqlConnection(connectionString);
            mycon.Open(); //error
            Console.WriteLine("Connection Open  !");
            mycon.Close();
        }
    }
}


text:
Q: Windows 10 - Inaccessible boot device Sorry if this is long. I've backed up the data at two places.
Windows 10 error INACCESSIBLE BOOT DEVICE
I was trying to dual boot Windows 10 with Xubuntu. Deleted the recovery partition(googled and saw it was ok) and left
untouched Win 7 Loader(200Mb), Win 10 Loader (1MB) and Win 10 partitions(NTFS 140 GB). Free Space is 150GB(partitioned into / and /home ext4, primary, format).
Tried installing Xubuntu but Grub install failed and now Windows 10 won't boot.
Created a separate recovery USB from another Windows 10 laptop but that has option of deleting all my files to recover the OS.
When Automatic Repair launches, the options are:

*

*Troubleshoot

*

*Recover from a drive

*

*Just remove my files. Tried and it tries to start recovery process but will delete all my user accounts and personal files) so didn't proceed

*Full clean the drive. Didn't try this yet

*Advanced Options

*

*System Restore(doesn't work)

*System Image Recovery(Windows cannot find a system image on this computer)

*Startup Repair(SR couldn't repair your PC. Log file: None

*Command Prompt(X drive:)

*Go back to previous version(can't go back)

*Turn off your PC.
I tried dual boot Xubuntu since I've wasted hours due to the broken Windows Update process. But Windows 7 was paid for and free upgraded to Windows 10 and so I need to get back to it. I've good experience with dual booting and with Linux and I dual booted twice successfully within the past 24 hours. Windows 10 has caused me more problems than 3.1, 95, 98, 2000, XP, Vista, and 7 combined. I haven't used 8.
Can I recover my data and OS?

A: The steps listed in the comments are useful and may work for some, but in the end I got the data out with the Xubuntu Live CD(try without install option) and recovered Windows 10 using a recovery USB. I recommend:

*

*Creating a recovery usb for Windows 10 and keeping it in a safe place. Recovery USB created from one laptop will work on another. Takes up about 4-8 GB.

*Backup your data. I had but was not sure if i had missed anything so was quite concerned.

*Follow the steps in the comments above.


text:
Q: Autocomplete location and Google Maps Nearby Places in Android studio, Do I need a billing account? I understand that for using the API that allows to provide autocomplete addresses and to show the nearby places in a maps, I need to have a billing account. It is just a universitary project, so I would not like to have a subscription. However, I read that when I enable billing on my account, I will not pay nothing. I'm not sure about these information. Anyone could give me more information?

A: Yes u should have a billing account. You just need to do just link your credit or debit card to your account unless your API will not work. Just add a your card u can get free 3 months trial


text:
Q: Changing element in another ViewController I am new to iOS and have a very basic question. I've googled and can't find the answer.
I have a UILabel on one ViewController and view and would like to change the font color with:
myLabel.textColor = [UIColor blueColor];

but in another ViewController. Is that possible?
So myLabel is in the first ViewController and the button to change the color of myLabel is in the other ViewController.
So more information like yall asked:
My app is compiled of tons of buttons with simple commands. All the buttons are in the same area so I thought of putting some of them on a different view instead of just piling buttons on top of each other and calling .hidden = true; on them.

A: It is possible but it does not immediately sound like a good design. Without knowing more about your app...
If the color change is to reflect some change in your model you should effect the change through your model:
--(UIEvent)--> ViewController1 --(update)--> model --(observe)--> ViewController2 --(change color)-> textField.
If your app is not that complicated, you should at the very least implement a method on ViewController2 that is descriptive of the reason why the text field should change and send that message (call the method) from ViewController1.
You will also need to pass a reference to VC2 into VC1 - you either already have this because there is a VC1->VC2 parent child relationship or you will have to do it through a joint parent.


text:
Q: pandas dataframe.at for a whole series How can I convert the following code without using the loop, using pythonic pandas :
import pandas as pd

xls = pd.ExcelFile('...')
df_1 = pd.read_excel(xls, '...')
df_2 = pd.read_excel(xls, '...')

df_1_len = len(df_1)
results = np.empty(df_1_len)
for idx in range(df_1_len):
    results[idx] = df_2.at[df_1['x'][idx], df_1['y'][idx]]

df_1 looks like :

x
y

1
a

2
a

2
b

...
...

df_2 looks like :

1
2
..

a
val(1,a)
val(2,a)
..

b
val(1,n)
val(2,a)
..

...
...
...

A: did you try df_2.loc[df_1['x'], df_1['y']]? Maybe this answer can help you understanding the difference between at and loc.


text:
Q: Prevent repeatitive request when injecting SVG from image source I have tried multiple SVG injectors including:

*

*SVGInjector by iconic

*And the example provided in this
answer.

The issue I have with both is that it's bad enough that placing the SVG in the src of an img tag takes one request, the scripts seem to be sending a second request.
Using JS, I would like this:
<img id="thumb-up" class="inject-me" src="https://cdn.rawgit.com/iconic/SVGInjector/master/examples/all-the-things/assets/svg/thumb-up.svg" alt="Thumbs Up!">

to inline such as this:
<svg class="injected-svg inject-me" id="thumb-up" viewBox="0 0 8 8" height="8" width="8" xmlns="http://www.w3.org/2000/svg">
  <path d="M4.47 0c-.19.02-.37.15-.47.34-.13.26-1.09 2.19-1.28 2.38-.19.19-.44.28-.72.28v4h3.5c.21 0 .39-.13.47-.31 0 0 1.03-2.91 1.03-3.19 0-.28-.22-.5-.5-.5h-1.5c-.28 0-.5-.25-.5-.5s.39-1.58.47-1.84c.08-.26-.05-.54-.31-.63-.07-.02-.12-.04-.19-.03zm-4.47 3v4h1v-4h-1z"></path>
</svg>

Example JSFiddle.
Is there a way to inline the SVG that is already in the DOM without sending a second request?


text:
Q: Installation of tflite c++ on ubuntu 20.04 I want to install tflite c++ on my ubuntu 20.04 but I am having some issues regarding installation. I got to know that I can only build this by using cmake or bazel but unfortunately both of them were not working for me. As cmake taking alot of RAM so it gets crash every time when it reaches to 96% during build and bazel is also giving some error during build. After using this command.

bazel build -c opt //tensorflow/lite:libtensorflowlite.so

It gave me this
error. I have also checked that numpy is available.
I was following this video.
Can anyone please send me the link of github where tflite c++ is available for ubuntu or any other link from where i can install this easily. As I am new in this. Your comments and suggestions will be greatly appreciated.
Thanks in advance.
Here is the error which I am getting.
bazel build -c opt //tensorflow/lite:libtensorflowlite.so
Extracting Bazel installation...
Starting local Bazel server and connecting to it...
INFO: Options provided by the client:
  Inherited 'common' options: --isatty=1 --terminal_columns=91
INFO: Reading rc options for 'build' from /home/umer/Downloads/tensorflow-2.4.2/.bazelrc:
  Inherited 'common' options: --experimental_repo_remote_exec
INFO: Reading rc options for 'build' from /home/umer/Downloads/tensorflow-2.4.2/.bazelrc:
  'build' options: --apple_platform_type=macos --define framework_shared_object=true --define open_source_build=true --java_toolchain=//third_party/toolchains/java:tf_java_toolchain --host_java_toolchain=//third_party/toolchains/java:tf_java_toolchain --define=tensorflow_enable_mlir_generated_gpu_kernels=0 --define=use_fast_cpp_protos=true --define=allow_oversize_protos=true --spawn_strategy=standalone -c opt --announce_rc --define=grpc_no_ares=true --noincompatible_remove_legacy_whole_archive --noincompatible_prohibit_aapt1 --enable_platform_specific_config --config=short_logs --config=v2
INFO: Reading rc options for 'build' from /home/umer/Downloads/tensorflow-2.4.2/.tf_configure.bazelrc:
  'build' options: --host_force_python=PY2 --action_env PYTHON_BIN_PATH=/usr/bin/python --action_env PYTHON_LIB_PATH=/usr/local/lib/python2.7/dist-packages --python_path=/usr/bin/python --config=xla --action_env TF_CONFIGURE_IOS=0
INFO: Found applicable config definition build:short_logs in file /home/umer/Downloads/tensorflow-2.4.2/.bazelrc: --output_filter=DONT_MATCH_ANYTHING
INFO: Found applicable config definition build:v2 in file /home/umer/Downloads/tensorflow-2.4.2/.bazelrc: --define=tf_api_version=2 --action_env=TF2_BEHAVIOR=1
INFO: Found applicable config definition build:xla in file /home/umer/Downloads/tensorflow-2.4.2/.bazelrc: --define=with_xla_support=true
INFO: Found applicable config definition build:linux in file /home/umer/Downloads/tensorflow-2.4.2/.bazelrc: --copt=-w --host_copt=-w --define=PREFIX=/usr --define=LIBDIR=$(PREFIX)/lib --define=INCLUDEDIR=$(PREFIX)/include --define=PROTOBUF_INCLUDE_PATH=$(PREFIX)/include --cxxopt=-std=c++14 --host_cxxopt=-std=c++14 --config=dynamic_kernels
INFO: Found applicable config definition build:dynamic_kernels in file /home/umer/Downloads/tensorflow-2.4.2/.bazelrc: --define=dynamic_loaded_kernels=true --copt=-DAUTOLOAD_DYNAMIC_KERNELS
DEBUG: Rule 'io_bazel_rules_go' indicated that a canonical reproducible form can be obtained by modifying arguments shallow_since = "1557349968 -0400"
DEBUG: Repository io_bazel_rules_go instantiated at:
  no stack (--record_rule_instantiation_callstack not enabled)
Repository rule git_repository defined at:
  /home/umer/.cache/bazel/_bazel_umer/ed358c98f40a3a8df15c688cf3579422/external/bazel_tools/tools/build_defs/repo/git.bzl:195:18: in <toplevel>
INFO: Repository local_config_python instantiated at:
  no stack (--record_rule_instantiation_callstack not enabled)
Repository rule python_configure defined at:
  /home/umer/Downloads/tensorflow-2.4.2/third_party/py/python_configure.bzl:294:20: in <toplevel>
ERROR: An error occurred during the fetch of repository 'local_config_python':
   Traceback (most recent call last):
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/py/python_configure.bzl", line 267
        _create_local_python_repository(<1 more arguments>)
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/py/python_configure.bzl", line 213, in _create_local_python_repository
        _get_numpy_include(<2 more arguments>)
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/py/python_configure.bzl", line 187, in _get_numpy_include
        execute(repository_ctx, <3 more arguments>)
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/remote_config/common.bzl", line 217, in execute
        fail(<1 more arguments>)
Problem getting numpy include path.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named numpy
Is numpy installed?
ERROR: Analysis of target '//tensorflow/lite:libtensorflowlite.so' failed; build aborted: Traceback (most recent call last):
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/py/python_configure.bzl", line 267
        _create_local_python_repository(<1 more arguments>)
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/py/python_configure.bzl", line 213, in _create_local_python_repository
        _get_numpy_include(<2 more arguments>)
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/py/python_configure.bzl", line 187, in _get_numpy_include
        execute(repository_ctx, <3 more arguments>)
    File "/home/umer/Downloads/tensorflow-2.4.2/third_party/remote_config/common.bzl", line 217, in execute
        fail(<1 more arguments>)
Problem getting numpy include path.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named numpy
Is numpy installed?
INFO: Elapsed time: 87.176s
INFO: 0 processes.
FAILED: Build did NOT complete successfully (11 packages loaded, 19 targets configured)
    currently loading: @bazel_tools//tools/jdk
    Fetching @local_execution_config_python; Restarting.
    Fetching @rules_java; fetching
    Fetching @io_bazel_rules_docker; fetching
    Fetching @go_sdk; fetching

A: I could successfully install tflite c++ on ubuntu 20.04. I have used  the following commands in a conda virtual environment. As per the tested build configurations TF v2.4 is compatible with Bazel 3.1.0. Hence I have used Bazel 3.1.0 to install tflite c++.
sudo apt update
sudo apt upgrade

#install python
sudo apt-get install python

#set environment variable "/usr/bin/python" in my case
export PATH=$PATH:/path/to/python

#Install the TensorFlow pip package dependencies
pip install -U --user pip numpy wheel packaging requests opt_einsum
pip install -U --user keras_preprocessing --no-deps

#Install Bazel and move file to bin folder so that it will be available system wide
chmod +x bazel-3.1.0-linux-x86_64
sudo mv bazel-3.1.0-linux-x86_64 ./.local/bin/bazel

cd ./.local/bin
#Extract bazel installation
bazel

#Check bazel version
bazel --version

#clone tensorflow repo in the same location where Anaconda is installed
cd ~

#clone tensorflow repo
git clone https://github.com/tensorflow/tensorflow.git

#Download the source code of tensorflow 2.4.2 and unzip it
cd tensorflow-2.4.2
python ./configure.py

It prompts the following:

Please specify the location of python. [Default is /usr/bin/python3]:

You can press Enter if the default location is ok.

Do you wish to build TensorFlow with ROCm support? [y/N]: N No ROCm
support will be enabled for TensorFlow.
Do you wish to build TensorFlow with CUDA support? [y/N]: N No CUDA
support will be enabled for TensorFlow.
Do you wish to download a fresh release of clang? (Experimental)
[y/N]: N Clang will not be downloaded.
Please specify optimization flags to use during compilation when bazel
option "--config=opt" is specified [Default is -Wno-sign-compare]:
Would you like to interactively configure ./WORKSPACE for Android
builds? [y/N]: N Not configuring the WORKSPACE for Android builds.

I have opted "N" for all the prompts
#bazel command to build build tflite library
bazel build -c opt //tensorflow/lite:libtensorflowlite.so

You can see the Build successful screenshot below. Thank you!


text:
Q: Is there a way to rewrite this matrix equation to eliminate inverse matrix? Let $\mathbf{u},\mathbf{v}\in\mathbb{R}^{n}$ and $\mathbf{K}\in\operatorname{GL}(n)$. Consider the following constraint:
$$\mathbf{u}^{\top} \left( \mathbf{K^{\top} K} \right)^{-1} \mathbf{v} = 0 \tag{1}$$
This constraint appears in some computer vision applications when dealing with camera calibration. The form of $(1)$ involves heavy computations which leads me to ask:
Is there a way to rewrite $(1)$ so that when checking for this constraint we don't have to compute matrix inverse as it is in many cases numerically unfeasible?

A: Note that ${\bf K}^{T}{\bf K}$ is symmetric and positive definite. Therefore you can take advantage of its Cholesky decomposition to efficiently compute its inverse.


text:
Q: What's the best way to check return value of read and write system calls? I am interested in finding out the best way possible for checking the return value from read and write system calls on Linux. According to the man page, e.g for write:

Upon successful completion, write() and pwrite() shall return the
  number of bytes actually written to the file associated with fildes.
  This number shall never be greater than nbyte. Otherwise, -1 shall be
  returned and errno set to indicate the error.

For read:

On success, the number of bytes read is returned (zero indicates end
  of file), and the file position is advanced by this number. It is not
  an error if this number is smaller than the number of bytes requested;
  this may happen for example because fewer bytes are actually available
  right now (maybe because we were close to end-of-file, or because we
  are reading from a pipe, or from a terminal), or because read() was
  interrupted by a signal. On error, -1 is returned, and errno is set
  appropriately. In this case it is left unspecified whether the file
  position (if any) changes.

So that makes me wondering:
if (ret < 0) {
    // see strerror
}

or
if (ret == -1) {
    // see strerror
}

Which one is the way to go, and why? Per man page, it seems to me like these are exactly same from functionality perspective. Is it right? Only difference I'm guessing would be that first statement should use a comparator, which would require more resources. Am I right with this assumption? Please share with me your thoughts. Thanks

A: First I'll look at it with performance in mind, using gcc 9.2 (x86-64):
#include <stdio.h>

int main(int argc, char **args, char **env) {
   if (argc < 0) {
       printf("ERROR!");
   }

   return 0;
}

will generate something like
.LC0:
        .string "ERROR!"
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 32
        mov     DWORD PTR [rbp-4], edi
        mov     QWORD PTR [rbp-16], rsi
        mov     QWORD PTR [rbp-24], rdx
        cmp     DWORD PTR [rbp-4], 0
        jns     .L2
        mov     edi, OFFSET FLAT:.LC0
        mov     eax, 0
        call    printf
.L2:
        mov     eax, 0
        leave
        ret

and
#include <stdio.h>

int main(int argc, char **args, char **env) {
   if (argc == -1) {
       printf("ERROR!");
   }

   return 0;
}

generates
.LC0:
        .string "ERROR!"
main:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 32
        mov     DWORD PTR [rbp-4], edi
        mov     QWORD PTR [rbp-16], rsi
        mov     QWORD PTR [rbp-24], rdx
        cmp     DWORD PTR [rbp-4], -1
        jne     .L2
        mov     edi, OFFSET FLAT:.LC0
        mov     eax, 0
        call    printf
.L2:
        mov     eax, 0
        leave
        ret

so there isn't any difference performance-wise. With THIS compiler and architecture.
Anything else is personal opinion. I personally would go for "< 0" ... just because it catches everything.

A: The style question  has been IMO answered by Maxine in his comment.
The efficiency is also better especially if compiler optimizes the code more aggressively
https://godbolt.org/z/MrTdqX


text:
Q: segmentation fault when push_back or erase on std::list Some pieces of my code crash randomly when call push_back or erase on std::list, the code is in a long time runing service . I removed the unimportant part and just keep the most relevant.

std::list<RxCCPReport> pendingSync;

size_t AnchorConnection::HandleCCPTxReport(const char *rxBytes, size_t length) {
    if (!pendingSync.empty())
    {
        std::list<RxCCPReport>::iterator iter = pendingSync.begin();
        while (iter != pendingSync.end())
        {
            if (condition1)
            {
                iter = pendingSync.erase(iter);
            }
            else
            {
                if (condition2)
                {
                    ++iter;
                }
                else if (condition3)
                {
                    ++iter;
                }
                else
                {
                    iter = pendingSync.erase(iter);
                }
            }
        }
    }

    return length; }

size_t AnchorConnection::HandleCCPRxReport(const char *rxBytes, size_t length) {
    RxCCPReport rxCCP;
    rxCCP.anc = anc;
    rxCCP.rxTime = ccpRxTime;
    rxCCP.seqNum = pCsMsg->seqNum;
    pendingSync.push_back(rxCCP);
    return length;
}

The two function runs on the same thread; code will crash at pendingSync.erase(iter) or pendingSync.push_back(rxCCP) sometimes, about 1 time a week.
the backtrace:

*

*crashed at erase

#0  std::__detail::_List_node_base::_M_unhook (this=0x7fffcc024040) at ../../../../../libstdc++-v3/src/c++98/list.cc:142
        __next_node = 0x0
        __prev_node = 0x7fffcc024040
#1  0x00000000004db14a in std::list<RxCCPReport, std::allocator<RxCCPReport> >::_M_erase (this=0x7fffdc011970, __position=...) at /usr/include/c++/4.8.2/bits/stl_list.h:1570
        __n = 0x7fffe5ffad80
#2  0x00000000004daddb in std::list<RxCCPReport, std::allocator<RxCCPReport> >::erase (this=0x7fffdc011970, __position=...) at /usr/include/c++/4.8.2/bits/list.tcc:112
        __ret = <error reading variable __ret (Cannot access memory at address 0x10)>
#3  0x00000000004e3d8b in AnchorConnection::HandleCCPTxReport (this=0x7fffdc009240, rxBytes=0x7fffc4022abb "0rl\206%M/\004\205O\263\002\216\356\003\002f", length=12)
    at LE/Network/rtls_anchor_conn.cpp:731
        rxCCP = {rxTime = 3.1943677384753104, seqNum = 114 'r', anc = }
        cSeqRxCCP = 114 'r'
        cs = 0x7fffdc016430
        ccpTx = 203157767788
        ccpTxTime = 3.1794272052158457
        pCsMsg = 0x7fffc4022abb
        cSeqTxCCP = 114 'r'

*crashed at push_back another time

> #0  0x00007ffff6dff387 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:55
        resultvar = 0
        pid = 5068
        selftid = 5418
#1  0x00007ffff6e00a78 in __GI_abort () at abort.c:90
        save_stage = 2
        act = {__sigaction_handler = {sa_handler = 0x7ffff6ddb76d, sa_sigaction = 0x7ffff6ddb76d}, sa_mask = {__val = {5, 140737336646961, 3, 140737043728478, 2,
              140737336643303, 1, 140737336652017, 3, 140737043728452, 12, 140737336652021, 2, 140737043729264, 140737043729264, 140737043731024}}, sa_flags = 16,
          sa_restorer = 0x7fffe57f8d70}
        sigs = {__val = {32, 0 <repeats 15 times>}}
#2  0x00007ffff6e41ed7 in __libc_message (do_abort=do_abort@entry=2, fmt=fmt@entry=0x7ffff6f54350 "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/unix/sysv/linux/libc_fatal.c:196
        ap = {{gp_offset = 40, fp_offset = 48, overflow_arg_area = 0x7fffe57f9260, reg_save_area = 0x7fffe57f9170}}
        ap_copy = {{gp_offset = 16, fp_offset = 48, overflow_arg_area = 0x7fffe57f9260, reg_save_area = 0x7fffe57f9170}}
        fd = 26
        on_2 = <optimized out>
        list = <optimized out>
        nlist = <optimized out>
        cp = <optimized out>
        written = <optimized out>
#3  0x00007ffff6e483e4 in malloc_printerr (action=<optimized out>, str=0x7ffff6f54548 "malloc(): memory corruption (fast)", ptr=<optimized out>, ar_ptr=<optimized out>)
    at malloc.c:4967
        buf = "00007fffd8001570"
        cp = <optimized out>
        ar_ptr = <optimized out>
        ptr = <optimized out>
        str = 0x7ffff6f54548 "malloc(): memory corruption (fast)"
        action = <optimized out>
#4  0x00007ffff6e4bb20 in _int_malloc (av=av@entry=0x7fffd0000020, bytes=bytes@entry=40) at malloc.c:3383
        p = 0x7fffd8001560
        fb = <optimized out>
        pp = <optimized out>
        nb = 48
        idx = <optimized out>
        bin = <optimized out>
        victim = 0x7fffd8001560
        size = <optimized out>
        victim_index = <optimized out>
        remainder = <optimized out>
        remainder_size = <optimized out>
        block = <optimized out>
        bit = <optimized out>
        map = <optimized out>
        fwd = <optimized out>
        bck = <optimized out>
        errstr = <optimized out>
#5  0x00007ffff6e4e6fc in __GI___libc_malloc (bytes=40) at malloc.c:2905
        ar_ptr = 0x7fffd0000020
        victim = <optimized out>
        hook = <optimized out>
#6  0x00007ffff7929ecd in operator new (sz=40) at ../../../../libstdc++-v3/libsupc++/new_op.cc:51
        p = <optimized out>
#7  0x00000000004dc6f8 in __gnu_cxx::new_allocator<std::_List_node<RxCCPReport> >::allocate (this=0x7fffdc011930, __n=1) at /usr/include/c++/4.8.2/ext/new_allocator.h:104
No locals.
#8  0x00000000004dc006 in std::_List_base<RxCCPReport, std::allocator<RxCCPReport> >::_M_get_node (this=0x7fffdc011930) at /usr/include/c++/4.8.2/bits/stl_list.h:334
No locals.
#9  0x00000000004db699 in std::list<RxCCPReport, std::allocator<RxCCPReport> >::_M_create_node<RxCCPReport const&> (this=0x7fffdc011930)
    at /usr/include/c++/4.8.2/bits/stl_list.h:502
        __p = 0x0
#10 0x00000000004db1c2 in std::list<RxCCPReport, std::allocator<RxCCPReport> >::_M_insert<RxCCPReport const&> (this=0x7fffdc011930, __position=...)
    at /usr/include/c++/4.8.2/bits/stl_list.h:1561
        __tmp = 0x0
#11 0x00000000004dae68 in std::list<RxCCPReport, std::allocator<RxCCPReport> >::push_back (this=0x7fffdc011930, __x=...) at /usr/include/c++/4.8.2/bits/stl_list.h:1016
No locals.
#12 0x00000000004e475b in AnchorConnection::HandleCCPRxReport (this=0x7fffdc01be90, rxBytes=0x7fffd004d7fb "1{\212\211D\021\006\061+\b\250\256i\227@ԺF(ú\002\005\003o\200@",
    length=88) at LE/Network/rtls_anchor_conn.cpp:936
        rxCCP = {rxTime = 4.3416058279497198, seqNum = 123 '{', anc = 0x7fffdc016320}
        prevSeqNum = 122 'z'
        master = 0x7fffdc0101a0
        cs = 0x7fffdc016450
        masterID = 588618078431250826
        logNum = 45794088
        pCsMsg = 0x7fffe57f9500
        ccpRx = 277418192552
        ccpRxTime = 4.3416058279497198
        txTime = "0000000000\000\334\377\177\000\000\177\236", <incomplete sequence \345>
        temp = "\000\000\000\000"
        diagMsg2 = "0F000005036F8040001000000412C8A607120000086000BC07390AD806130000040000FC0114000005F9FF0700731500000EA8AE699740D4BA740800EC69974025000010A604C3FB4C07A3F7520743FE260538072E100002EF022700280491FE1F6D2E100"...
        csmsg = {type = 49 '1', seqNum = 123 '{', masterID = "\212\211D\021\006\061+\b", csRxTime = "\250\256i\227@", {firstPath16 = 47828, firstPath = "Ժ"},
          extLen = 70 'F', {
            ext = "(ú\002\005\003o\200@\000\022Ȧ\a`\000\274\a9\n\330\006\000\000\374\001\371\377\a\000s\250\256i\227@Ժt\b\000\354i\227@\000\246\004\303\373L\a\243\367R\aC\376&\005\070\a\357\002\221\376\037m?\021", {{logNum32 = 45794088, logNum = "(ú\002"},
              diagnostics = "\005\003o\200@\000\022Ȧ\a`\000\274\a9\n\330\006\000\000\374\001\371\377\a\000s\250\256i\227@Ժt\b\000\354i\227@\000\246\004\303\373L\a\243\367R\aC\376&\005\070\a\357\002\221\376\037m?\021"}}}
        FP = 747
        rxTime = "409769AEA8\000\345\377\177\000\000Н", <incomplete sequence \345>

I was nearly mad, any suggestion appreciated
Code that receive data over socket is as follows:
#define FRAME_HEADER_LEN (6)
#define FRAME_DATA_IDX   (3)

virtual void Run()
{
    unsigned int length = 0;
    std::string rxBytes;
    bool msgProcess;
    uint8_t fcode;
    unsigned int flen = 0;

    while (shutdown_select_anc(socket) != -1)
    {
        int count = socket->ReceiveData();

        if (count <= 0) // Something failed. Socket is probably closed.
        {
            break;
        }

        length += count;
        rxBytes.append(socket->buf_, count);

        /*
        * the data coming from the anchor is framed:
        *<STX><LENlsb><LENmsb><DATA:<FC><XX>.....><CRClsb><CRCmsb><ETX>
        * STX = 0x2
        * LEN is the length of data message(16 bits)
        * CRC is the 16 - bit CRC of the data bytes
        * ETX = 0x3
        * FC = is the function code (API code)
        */
        if (length <= FRAME_HEADER_LEN) //minimum length is 7 bytes (header + 1 byte function code)
        {
            continue;
        }

        do {
            msgProcess = false;
            crc_err_t pckt_crc = CRC_ERROR;
            //search through the received data to find the start of frame
            while (length > FRAME_HEADER_LEN)
            {
                if ((rxBytes.c_str())[0] == 0x2) //this is the start - check if length and end match
                {
                    uint8_t hi = (rxBytes.c_str())[2];
                    uint8_t lo = (rxBytes.c_str())[1];

                    flen = lo + ((uint16_t)hi << 8);

                    if ((flen + FRAME_HEADER_LEN) > length) //we don't have all the frame yet
                    {
                        break;
                    }

                    if ((rxBytes.c_str())[flen + 5] == 0x3) //end of frame present
                    {
                        //received whole frame: check frame checksum here
                        pckt_crc = check_crc16((uint8_t *)&(rxBytes.c_str())[3], (flen + 2));
                        break;
                    }
                    else //no end of frame in the expected place - start byte was not real start
                    {
                        rxBytes.erase(0, 1);
                        length -= 1;
                    }
                }
                else //remove the byte and check if next is a start of frame
                {
                    rxBytes.erase(0, 1);
                    length -= 1;
                }
            }

            //check if we have a frame
            if (((flen + FRAME_HEADER_LEN) > length) || (length <= FRAME_HEADER_LEN))
            {
                break;
            }

            if (pckt_crc != CRC_OKAY)
            {
                //frame packet fully received but it's CRC bad
                DBG_PRINTF(DBG_DEFAULT, "ACHTUNG ACHTUNG : incompatible software without CRC or network CRC error\n");
                //let incompatible software proceed at the moment
            }

            fcode = (rxBytes.c_str())[FRAME_DATA_IDX]; //get function code

            typename std::map<uint8_t, std::pair<size_t, handler> >::iterator it = handlers.find(fcode);
            if (it != handlers.end()) //we have found a handler for this function code
            {
                if (flen >= it->second.first)
                {
                    handler f = it->second.second;
                    size_t n = (static_cast<Child*>(this)->*f)(&((rxBytes.c_str())[FRAME_DATA_IDX]), flen );
                    if (n > 0)
                    {
                        msgProcess = true;
                        rxBytes.erase(0, n + FRAME_HEADER_LEN);
                        length -= (unsigned int)(n + FRAME_HEADER_LEN);
                    }
                    else
                    {
                        //Unexpected Message
                        rxBytes.clear();
                        length = 0;
                    }
                }
            }
            else
            {
                rxBytes.clear();
                length = 0;
            }
        } while((length > 0) && msgProcess);
    }

    socket->Close();
}

A: In the push_back case you have

str = 0x7ffff6f54548 "malloc(): memory corruption (fast)"

Suggests that you have an memory corruption elsewhere, most likely shortly before calling HandleCCPRxReport.


text:
Q: OnClickListener disabled when using Android proximity sensor I am trying to create a proximity sensor in an application that is already working fine. I am able to run ok the sensor, but when I do it, it disables the OnClickListener of the buttons of the application and I really don't understand why.
This is my MainActivity.class
public class MainActivity extends Activity implements OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button option1 = (Button) findViewById(R.id.option1);
        Button option2 = (Button) findViewById(R.id.option2);

        option1.setOnClickListener(this);
        option2.setOnClickListener(this);
   }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = new Intent();
        intent.setClass(getBaseContext(),ProximitySensor.class);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.option1:
                // Option1
               break;
            case R.id.option2:
                // Option1
                break;
            default:
                break;
        }

    }
}

And here the ProximitySensor.class that is working OK
public class ProximitySensor extends Activity implements SensorEventListener{

    private SensorManager sm;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sm= (SensorManager)getSystemService(Context.SENSOR_SERVICE);
    }

    @Override
    protected void onStart(){
        super.onStart();
        Sensor proximitySensor= sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        if (proximitySensor == null){
            Toast.makeText(ProximitySensor.this,"No Proximity Sensor Found! ",Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_PROXIMITY),SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onStop() {
        super.onStop();
        sm.unregisterListener(this);
   }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(event.sensor.getType()==Sensor.TYPE_PROXIMITY){
            if(event.values[0] == 0){
               Toast.makeText(ProximitySensor.this,"You are close",Toast.LENGTH_LONG).show();
            }
        }
    }

}

I think that I might be calling wrong the sensor, could anyone give me a hand?
Many thanks!

A: You need to register onClick listeners in ProximitySensor activity just like you did on your main activity.
You are currently starting a new activity, setting its layout the same as your main activity. But when you do that, the onClickListeners you set up on your main activity no longer works, because it is a new activity and a new layout.


text:
Q: update fields mysql table with value from other row for the same product id I need to update a database table with value that is used in another row.
I have a database with 4000 products, for every product there are 3 rows, 1 for every language (i work with 3 languages).
Now i need to copy the product title from the dutch language into the title field from the English product row and the French product row for the same product id. Some title field in English and Frensh are empty, but not al off them are empty.
So I have this fields
product_id ;
language_id ;
product_title
Anyone can help me with the sql i need to have to do this for all my 4000 products?
Thank you, kind regards
Pete
ps_product_lang is the name of the product table
the database is MySQL
id_product  int(10) unsigned    NO  PRI NULL
id_shop int(11) unsigned    NO  PRI 1
id_lang int(10) unsigned    NO  PRI NULL
description text    YES     NULL
description_short   text    YES     NULL
link_rewrite    varchar(128)    NO      NULL
meta_description    varchar(255)    YES     NULL
meta_keywords   varchar(255)    YES     NULL
meta_title  varchar(128)    YES     NULL
name    varchar(128)    NO  MUL NULL
available_now   varchar(255)    YES     NULL
available_later varchar(255)    YES     NULL

A: Something along these lines should work.
UPDATE ps_product_lang p1
   SET name =
       (SELECT name
          FROM (SELECT * FROM ps_product_lang) p2
         WHERE p2.`id_product` = p1.`id_product`
           AND p2.`id_lang` = 6)
 WHERE `id_lang` != 6

You need the extra nested select in there to prevent MySQL from reporting the following error:
Error Code: 1093
You can't specify target table 'p1' for update in FROM clause


text:
Q: Check if a nested property has an object that partially matches a target in expect I have an object like this:
> const expect = require('chai').expect
> r = {  loadedElementData: { userIdRecord: { name: 'Chiara', surname: 'Fabbietti', id: 1 } }, resolvedIdParamsValues: { users: 1 }, resolvedListFilter: {}, totalLoads: 1 }

I can check if an object with specific contents is somewhere deep in r -- this doesn't throw:
> expect(r).to.have.nested.deep.property('loadedElementData.userIdRecord', { name: "Chiara", surname: "Fabbietti", id: 1 })

However, I want to check for partial objects. So, I would like something like this to pass even though the comparison object is a partial match:
> expect(r).to.have.nested.deep.property('loadedElementData.userIdRecord', { id: 1, name: 'Chiara' })

This obviously won't work, since it will check for the object's deep equality.
This in theory should work:
expect(r).to.nested.include({'loadedElementData.userIdRecord': { id: 1, name: 'Chiara' } })

But doesn't.
This should REALLY work:
 expect(r).to.deep.nested.include({ 'loadedElementData.userIdRecord': { id: 1, name: 'Chiara' } })

But doesn't.
I can make it work checking ONE property (only 'id'):
expect(r).to.nested.include({ 'loadedElementData.userIdRecord.id': 1})

But I am limited to check for id, and can't check for name too at the same time.
I can do this in 2 steps:
> expect(r).to.include.nested.property('loadedElementData.userIdRecord')
> expect(r.loadedElementData.userIdRecord).to.include({ id: 1 })

But this is a two step process -- can I do it in one step?

A: If you check their Github issues, maintainers acknowledge that the nested inclusion of an object subset is not working since 2020. Reference: chai Github
This is the line where Chai decides if doing a deep equality or a strict equality when comparing two objects: https://github.com/chaijs/chai/blob/a8359d3d15779a23a7957a4c52539d48de2763e0/lib/chai/core/assertions.js#L1892.
_.eql is a reference to Chai's deep equal own library implementation.
In the deep-eql library the flow will reach to this function that does loose equality comparisons but not partial ones.


text:
Q: How can I display the hierarchy of my custom objects in a Visualforce page using a datatable? In advance of posting this question, I have attempted to use maps and wrapper classes. I've already made several attempts for the past two months using the suggestions on this forum and the SF developer forum to create custom hierarchy extension controllers, but nothing has worked perfectly.
What I'm trying to do is display long form responses on a VF page using a data table using an integration from FormAssembly, which is a survey website.
My objects and relationships are:

*

*Form__c (Master)

*Section__c (Child)

*Question__c (Grandchild)

*Response__c (Great-grandchild)

Additionally not every Question__c has a Question_Batch__c, but every Question_Batch__c looks up to a Question__c and Section__c/.
An example of a Question_Batch__c is a "Mailing Address," which looks up to the Section__c, "Contact Information," which looks up to the Question__cs, "Street Address," "City," "State," and "Country."
The apex code extension I have written currently is:

    public ListFormObjects(ApexPages.StandardController controller) {

    }

    public List<Section__c> getSections(){
        return [SELECT Name,
                Question__r.Question_Text__c
                FROM Section__c
               WHERE Form__c = :Apexpages.currentPage().getParameters().get('id')];
    }

 public List<Response__c> getResults() {
        return [SELECT Name,
                       Response__c,
                       Question__r.Id,
                       Question__c,
                       Question__r.Section__c,
                       Question__r.Question_Text__c,
                       Question__r.Question_Batch__c,
                       Question__r.Question_Batch__r.Name,
                       Question__r.Section__r.Name,
                       Question__r.Section__r.Form__c,
                       Question__r.Section__r.Form__r.Name
                FROM Response__c
               WHERE Question__r.Section__r.Form__c =
                      :Apexpages.currentPage().getParameters().get('id')];

 }
    }

The Visualforce I have written currently is:
<apex:page standardController="Form__c" lightningStyleSheets="true" extensions="ListFormObjects">

Form Viewer

    <apex:pageBlock >
        <apex:pageBlockSection title="Submission Details">
        <apex:pageBlockTable value="{!Form__c}" var="ft">
            <apex:column headerValue="Form" width="200px" >
            Reporting Month: {!ft.Reporting_Month__c}

            Name: {!ft.Name}

            </apex:column>
            <apex:column headerValue="Dates" width="200px">
            <apex:outputText value="Submitted Date: {0, date, MMMM d','  yyyy}"
            style="{!IF(ft.Submitted_Date__c > ft.Due_Date__c, 'color: #EE4034; font-weight:600;', '')}">
                <apex:param value="{!ft.Submitted_Date__c}" />
                </apex:outputText>

            <apex:outputText value="Due Date: {0, date, MMMM d','  yyyy}">
                <apex:param value="{!ft.Due_Date__c}" />
                </apex:outputText>

            </apex:column>
       </apex:pageBlockTable>
       </apex:pageblocksection>
    <apex:pageBlockSection title="Submitter Details">

    <apex:detail subject="{!Form__c.Contact__c}" relatedList="false" title="true">

    </apex:detail>
    </apex:pageblocksection>

<apex:pageBlock >
<apex:pageblocksection title="Form Details" showheader="true" collapsible="true" columns="1">
    <apex:pageBlockTable value="{!Sections}" var="s">
        <apex:column value="{!s.Name}"/>
        <apex:column breakBefore="true" colspan="2">
            <apex:pageBlockTable value="{!Results}" var="r" rendered="true">
                <apex:column value="{!r.Question__r.Question_Text__c}"/>
                <apex:column value="{!r.Response__c}"/>
                <apex:column value="{!r.Question__r.Section__r.Name}"/>
                <apex:column value="{!r.Question__r.Question_Batch__r.Name}"/>

            </apex:pageBlockTable>
       </apex:column>
       </apex:pageBlocktable>
</apex:pageblockSection>
</apex:pageBlock>

    </apex:pageBlock>
</apex:page>

This is an example of how the data table renders:

This is an example of the full Visualforce page:

My goal is to get the Sections to be ordered 1-3 and then to show the Question Batches below the Sections. Then below that I'd like to see the corresponding Questions and Responses.
Hope someone can help :)


text:
Q: width: auto property not being respected with position: relative I'm currently trying to style a dropdown menu, but I'm running into some issues. The biggest one is that the dropdown elements don't seem to be exceed the size of their parent object when the css for the dropdown is set to relative.

(Had to block out the search results, sorry).
It seems to work on fixed, but only in Firefox, Chrome's dropdowns are all off.

So I think I need one of two solutions:

*

*Fixing the width issue and keeping the position: relative

*Fixing the offset issue that occurs ONLY in chrome, and setting the position: fixed attribute.

HTML:

            <input type="text" id="nodetext" placeholder="Enter a node" name="nodetext" value="">

Truncated search results..

CSS
#searchresults, #noderesults, #roadmapresults, #intersectnoderesults {
    max-width: 1000px;
    background: #2E3C3F;
    width:auto;
    height: 0px;
    padding: 0;
    border: none;
    position: relative;
    z-index: 3; /*So that the dropdown stays infront of the forms*/
}

Would anyone know how I could go about fixing this?

A: I ended up just fixing this by breaking down the CSS into one category for each one of the fields, set the position property to fixed, and scaled the css "top" property so that the results would fit for each of the search fields.


text:
Q: "Network Servers" folder mysteriously appeared on desktop, and cannot re-hide it? The "Network Servers" folder somehow ended up on my desktop, and I can't re-hide it, or otherwise remove it from the desktop area. There is likely a simple solution, but I don't know what it is. I also don't know where it came form or why it's there to beging with, although it may have popped up last night when I added a repository to download Arc themes as I don't recall it being there prior to yesterday.

A: unity tweak tool has this option under system>desktop icons>
sudo apt install unity-tweak-tool


text:
Q: Laravel, MYSQL full join workaround on two aggregated tables I've got a table called transactions with below schema:
TRANSACTIONS
+----+-----------------+-------------------+--------+
| id | to (account_id) | from (account_id) | amount |
+----+-----------------+-------------------+--------+
| 1  | 1               | 3                 | 500    |
+----+-----------------+-------------------+--------+
| 2  | 2               | 1                 | 250    |
+----+-----------------+-------------------+--------+
| 3  | 1               | 2                 | 100    |
+----+-----------------+-------------------+--------+
| 4  | 4               | 2                 | 50     |
+----+-----------------+-------------------+--------+

to and from are foreign keys to id on table accounts.
I wanna get the subtraction of sum of all received transactions from all paid transactions of selected accounts as in the example accounts 1 and 2 and all the accounts which whom those had transaction with.
This is the desired result:
DESIRED QUERY RESULT
+---+------------+---------------+-----------+---------+
| # | account_id | totalReceived | totalPaid | balance |
+---+------------+---------------+-----------+---------+
| 1 | 1          | 600           | 250       | 350     |
+---+------------+---------------+-----------+---------+
| 2 | 2          | 250           | 150       | 100     |
+---+------------+---------------+-----------+---------+
| 3 | 3          | 0             | 500       | -500    |
+---+------------+---------------+-----------+---------+
| 4 | 4          | 50            | 0         | 50      |
+---+------------+---------------+-----------+---------+

What I've got so far:
as I'm using Laravel with query builder I run it like follows:
$k = [1, 2];

$receivedTransactions = DB::table('transactions as t1')->selectRaw('t1.to as account_id, sum(t1.amount) as totalReceived')
    ->whereIn('t1.from', $k)->orWhereIn('t1.to', $k)->groupBy('t1.to');

$paidTransactions = DB::table('transactions as t2')->selectRaw('t2.from as account_id, sum(t2.amount) as totalPaid')
    ->whereIn('t2.from', $k)->orWhereIn('t2.to', $k)->groupBy('t2.from');

$result = $receivedTransactions->leftJoinSub($paidTransactions, 't2', function ($join) {
    $join->on('t1.to', 't2.account_id');
})->selectRaw('totalPaid, (COALESCE(sum(t1.amount),0) - COALESCE(totalPaid,0)) as balance');

The big problem is it doesn't give me the 3rd row in the desired result table, because I don't have full join and I don't get the result from the right table which doesn't have corresponding row in the join so null.
this is what I get:
CURRENT QUERY RESULT
+---+------------+---------------+-----------+---------+
| # | account_id | totalReceived | totalPaid | balance |
+---+------------+---------------+-----------+---------+
| 1 | 1          | 600           | 250       | 350     |
+---+------------+---------------+-----------+---------+
| 2 | 2          | 250           | 150       | 100     |
+---+------------+---------------+-----------+---------+
| 4 | 4          | 50            | 0         | 50      |
+---+------------+---------------+-----------+---------+

I don't get the account_id 3 which was involved in giving account 1 the transaction no.1
Any help would be really appreciated. It doesn't matter if it is in Raw MYSQL format or laravel query builder. Thank you very much.

A: I did this directly on mysql and after I tried to translate to Laravel syntax
SELECT
  DISTINCT base_accounts.account_id,
  COALESCE(t1.totalReceived, 0) as totalReceived,
  COALESCE(t2.totalPaid, 0) AS totalPaid,
  COALESCE(t1.totalReceived, 0) - COALESCE(t2.totalPaid, 0) as totalBalance
FROM (
     SELECT `to` as account_id FROM transactions UNION SELECT `from` FROM transactions
) as base_accounts
LEFT JOIN (
     SELECT `to` as account_id, sum(amount) as totalReceived FROM transactions GROUP BY `to`
) as t1 on base_accounts.account_id = t1.account_id
LEFT JOIN (
     SELECT `from` as account_id, sum(amount) as totalPaid FROM transactions GROUP BY `from`
) as t2 on base_accounts.account_id = t2.account_id
ORDER BY base_accounts.account_id

 \DB::table(\DB::raw('(SELECT `to` as account_id FROM transactions UNION SELECT `from` FROM transactions) as base_accounts'))
        ->select(DB::raw('
        DISTINCT base_accounts.account_id,
        COALESCE(t1.totalReceived, 0) as totalReceived,
        COALESCE(t2.totalPaid, 0) AS totalPaid,
        COALESCE(t1.totalReceived, 0) - COALESCE(t2.totalPaid, 0) as totalBalance
        '))
        ->leftJoin(
            \DB::raw('(SELECT `to` as account_id, sum(amount) as totalReceived FROM transactions GROUP BY `to`) as t1'),
            'base_accounts.account_id',
            '=',
            't1.account_id'
        )
        ->leftJoin(
            \DB::raw('(SELECT `from` as account_id, sum(amount) as totalPaid FROM transactions GROUP BY `from`) as t2'),
            'base_accounts.account_id',
            '=',
            't2.account_id'
        )->orderBy('base_accounts.account_id')->get();

I tested the query and worked fine.


text:
Q: The side borders of the calendar do not appear I have an angular project version 7 (+), I'm using adminLTE 3, fullCalendar and I'm having trouble rendering the left and right edges of the calendar.
I am not able to manually adjust the calendar css to show the side borders.
What do I need to do to make the calendar borders render correctly?
Here is the image of the project that I am using css adminLTE3 together with fullCalendar
Here, the link to the code that shares the problem:
https://stackblitz.com/edit/fullcalendar-with-adminlte3
Thank you in advance.

A: I played with the css file. After adding border-style: solid there was a border appearing on all the side of the calendar. If you only want the border to appears on left and right you can do:
border-left: <sizeOfBorder> <typeOfBorder> <colorOfBorder> and in the same way border-right: <s> <t> <c>
Also, try to change the padding value from 0 to -1 and it will extend the table fully to the side frames.

A: You can add some css rule in your custom stylesheet. Possibly in the style.css stylesheet. Here is the code.
.fc-view-container {
  border-left: 1px solid #ddd !important;
  border-right: 1px solid #ddd !important;
}


text:
Q: DrRacket autocomplete does not see functions defined in my source code I am using Racket and DrRacket for a small project (I am trying to learn both and using them to teach a friend of mine some functional programming).
I have just discovered the autocomplete function (C-/) and it works fine with library functions, but it won't see my own functions.
I have also added
(provide (all-defined-out))

at the beginning of my source file (I thought that the autocomplete function might not see the symbols because they are not exported) but this does not solve the problem.
All the symbols are accessible in the DrRacket REPL (I can evaluate my functions and they work fine).
Can you give me any indication on how to solve this problem? Do I need to configure something?

A: I can confirm that DrRacket currently works this way. The best advice I can give, is to submit a feature request (use "Submit Bugreport" in the Help menu) and then cross your fingers.


text:
Q: How to receive the app delegate calls in a Swift Flutter plugin? I am writing a Flutter plugin in Swift. I have successfully created the plugin and can call my Swift functions from Flutter using the default code that is generated when you create a new Flutter plugin. My Swift code currently looks like this.
public class MyFlutterPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "my_plugin", binaryMessenger: registrar.messenger())
    let instance = MyFlutterPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    if call.method == "hello" {
      result("hello from swift")
    } else {
      result(FlutterMethodNotImplemented)
    }
  }
}

I would like app delegate calls (for example when a notification is received) to be sent to my plugin. I would like to know how to make this work with Swift.
I have seen in the source code from some Objective C plugins the line [registrar addApplicationDelegate:instance];. But I don't know how to achieve anything like this in Swift and the official documentation doesn't seem to exist for this.

A: It turns out it is fairly simple. Use registrar.addApplicationDelegate(instance) to register to receive the calls. Then include app delegate methods like this:
public func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    channel.invokeMethod("onToken", arguments: token)
}


text:
Q: LDO without ground I am trying to simplify the schematics and work around chip shortage at the same time. In current implementation the MCU is talking to BMS via ISOW7821 isolator. The primary reason for this was to isolate the ground, not the Tx/Rx lines. The PCB with MCU receives power over heavy gauge wires. However if the ground wire gets disconnected for any reason, up to 80A may try to go over 28AWG ground in BMS connection.
Now, since the board does have +24V from the battery, I've decided to replace that isolator with simple LDO (MCP1799T) and cheap digital isolator (SI8422AB) combination. What I am worried about, is the plugging/unplugging of the BMS. If the UART pins got connected before the ground pin, then it seems to me there could be full battery voltage coming through LDO on those wires (INA, OUTB), relative to the BMS ground or internal BMS 3.3V power rail.

simulate this circuit – Schematic created using CircuitLab
UPDATE:
Just to clarify, the question is - How does LDO behave with floating ground pin? Is it a) open circuit, b) closed circuit, or c) something in between, depending on internal schematics and/or load impedance?
From the discussion with @DKNguyen it seems to be c), and the suggested protection is resistors/zeners on Tx/Rx pins. Zeners will not work, however, without the ground. But I certainly can put in some series resistors.
Regarding schematics, the connectors can be plugged/unplugged in any order. Furthermore, they do not guarantee any specific order of their pins making contact. So, there can be any combination of those five wires, if only for a short time.


text:
Q: is it possible to pass array as obj via nsnotification I could do this by using protocol and delegate but I would like to try with NSNotification
My task is sending an NSMutableArray via notification from one to another view.  Is it possible to do
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:myArray];

Then, in the receiver, how can I get the passed myArray. I was reading and confused about the userInfo and object of notification object.
Please advice me on this issue.

A: An NSNotification has a property called userInfo that is an NSDictionary.  The object is the NSObject that is posting the NSNotification.  So usually I use self for the object when I'm setting up the NSNotification because self is the NSObject sending the NSNotification.  If you wish to pass an NSArray using an NSNotification I would do the following:
NSArray *myArray = ....;
NSDictionary *theInfo =
  [NSDictionary dictionaryWithObjectsAndKeys:myArray,@"myArray", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData"
                                                    object:self
                                                  userInfo:theInfo];

And then catch it using the following:
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(doTheReload:)
                                             name:@"reloadData"
                                           object:sendingObject];

where sendingObject is the object that is sending the NSNotification.
Finally, decode the array in doTheReload: using:
NSArray  *theArray = [[notification userInfo] objectForKey:@"myArray"];

That always works for me.  Good luck!

A: You should use userInfo.  It is for misc data you want to send with the notification.  The object argument is for the object that the event is fired for.  For example, if you want to monitor a certain MPMoviePlayerController (but not others), then you would sign up for only its notifications (via the object argument).

A: it is very consistent because the object is the object and the userInfo is the userInfo when you post any notification using the -postNotificationName:object:userInfo: method.
yes, you can post any subclass of NSObject via the NSNotificationCenter.

A: Swift 4, Swift 5
NotificationCenter.default.post(name: Notification.Name("favoriteIsDeleted"), object: [message, self.viewModel.deleteSuccessIcon])

@objc func favoriteIsDeleted(notification: Notification) {
    guard let object = notification.object as? [String?], let message = object[0], let deleteSuccessIcon = object[1] else { return }
    // Code here ...
}


text:
Q: Strange Permalink Issue I've been dealing with a really strange Permalink Issue on my WordPress site which runs Sage 8.5.1, previously setup by another developer.
Yesterday, I made a new homepage live on my site within Settings > Reading, and after doing this the permalinks within my site seemed to stop working completely. I was using the setup: /%postname%/, when switching to the generic: ?p=123, all my links worked again.
I did quite a lot of testing, checking .htaccess file, deactiving plugins, going back a code version and other things.
This morning, the last thing I tested was activating the generic WordPress theme and then testing my permalinks (/%postname%/), and they worked. I then reactivated by original theme built on Sage 8.5.1, and all my links worked again with the original permalinks setup.
Has anyone come across this before? Its very strange, and I can't see why deactivating the theme, and then activating it would fix the problem.

A: Turns out it was something to do with a custom post type I setup. I removed the custom post type, and created a new one based on the WordPress codex and that solved the problem.


text:
Q: Setting a property in grunt is creating an unwanted json object I am trying to set a property in grunt with the command grunt.config(<property>, <value>) and grunt will not escape a period . that is in my property name, and turns it into a new json object.  I am looping through a list of projects and creating a list of less files.  Here is the code.
grunt.config('projects').forEach(function(project) {
  grunt.config('less.development.files.' + project + '.less', 'project/' + project + '.css');
});

I want the result to be a json object with a less key and a css value like this project.less : project.css.
This gives me a json object that looks like this
{
  "file1": {
    "less": "project\/file1.css"
  },
  "file2": {
    "less": "project\/file2.css"
  },
  "file3": {
    "less": "project\/file3.css"
  }
}

If I change the filenames from .less to _less, then the object looks like I want.
{
  "file1_less": "project\/file1.css",
  "file2_less": "project\/file2.css",
  "file3_less": "project\/file3.css",
}

but I want it to be .less.  What do I do to make Grunt not create this as a new object?  I have tried double quotes, single quotes, single quotes with escaping, and pushing the key/value into a variable name and using the variables.  None of these worked.  Does anyone have any other ideas?  Thanks for the help.

A: This should work:
grunt.config('projects').forEach(function(project) {
  grunt.config.data.less.development.files[project + '.less'] = 'project/' + project + '.css';
});

Basically, you want to use that concatenated string with the .less as the key so you can access it directly through the grunt.config.data.less.development.files object using square bracket notation.
That assumes you already have a placeholder for it like:
grunt.config.init({
  less:{
    development:{
      files:[]
    }
  }
})


text:
Q: Need Help Understanding Eagle Ground Plane I am creating a pcb board on eagle for a Texas Instruments boost converter and I am experimenting with the polygon feature. Through research on the web I have leaned how to create a ground plane throughout the board. However, I have some questions that I just cant seem to find the answers to online. My first question would be, do I have to connect the ground of my battery to the ground plane of my board? If so, how would I go about doing that? Secondly, if I connected my grounds to vias would that automatically pass through to the ground plane or no? I experimented with vias and the ground plane on my previous model and was not able to get it right. If you could please help me that would be great. I am sorry if these questions are stupid but I have no prior experience in electronics and am teaching myself as I go.
Thanks,
John

A: The first thing you should do is the following: Finish the entire route of the tracks of your circuit. Draw the copper polygon around the entire contour of your PCB. Then assign a net this must be gnd. Clicking on Ratsnets will generate your GND plane. Simply the connector (-) of your battery will be part of the GND plane. By placing the tracks they immediately go from Top to Bottom. You must see who will make your PCB and according to it take into account the minimum diameter of the vias, do this before advancing in the design.
If you are working with a Buck converter you must be very careful in the layout, you must comply with the manufacturer's recommendation. You must isolate the nodes most prone to noise within the circuit.


text:
Q: Удалить несколько узлов за раз site.remove();
bla.remove();
this.v.remove();

Предусмотрена ли возможность удаления за раз несколько узлов?
Если необходимо писать функцию под эту задачу, подскажите оптимальный ее вариант?
Я как всегда кучу кода напишу, тогда как возможно было в 1 строчку...


text:
Q: Sort vector by sum of a pair array elements I'm just playing with C++ sort & lambda and wondering if it would possible to sort elements by sum?
For example:
std::sort(my_vector.begin(), my_vector.end(), [&, sum](int a, int b){
return a + b == sum; });

I tried the method above, it gives a runtime error: "Expression: Invalid operator <".
Update1
The example:
Sum = 4
1 ,2 ,5, 3, 2
I need to group elements the sum of both would equal Sum e.g 4
So it must be grouped like so:
1,3,2,2,5
Can anybody suggest an alternative solution? I'm just lazy to achieve it using a dumb iteration.
Thanks.

A: std::sort requires a predicate that compares elements. That predicate must establish strict weak ordering, one important property of which is if pred(a, b) returns true, pred(b, a) must return false. Your lambda does not satisfy this property.


text:
Q: SaaS with bring-your-own-key - at what point do you need something for key management? We're starting to use some SaaS providers, including Office365 Exchange Online, that allow bring-your-own-key or hold-your-own-key for encrypting data at rest. These are, to my understanding, simply one key per provider, not something per-user or per-item.
What are the things I need to consider for deciding how to manage the keys? If it's under 6 services, can I just print 2 copies of the keys and store them in different locations, plus a copy in our password management system? At what point does an organization start to consider a key management solution?


text:
Q: Using Planet Labs API tile service with leaflet map I'm using Planet Labs API tile service with leaflet map. Need to add it as a tile layer/WMS layer.
But the map stays the same when zoomed in or out.
My Map: https://drive.google.com/open?id=1jodnQB9exuxxt6trxirGmbdF3FkPX-nx
Here's my code.
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
var wmsLink='https://tiles0.planet.com/basemaps/v1/planettiles/global_monthly_2016_05_mosaic/gmap/0/0/0.png?api_key={your_key}'
var wmsLayer4 =  L.tileLayer.wms(wmsLink , {layers: 'layer_name',format: 'image/png',transparent: true  }).addTo(mymap);

Referred from https://developers.planet.com/docs/api/tile-services/
Providing a working example would be great.

A: Looks like a couple of problems: planettiles rather than planet-tiles and using the fixed 0 rather than {x}, {y} and {z} so that Leaflet knows to replace those with the correct tile in the pyramid. Without the second change, at every zoom level, you will get the same zoomed out map since Leaflet only knows to request that single tile.
Here is the URL in the docs and it should work fine:
https://tiles.planet.com/basemaps/v1/planet-tiles/global_monthly_2016_05_mosaic/gmap/0/0/0.png?api_key=XYZ

Note that Planet's services use tiles not WMS, so you need to follow the Leaflet documentation for tilelayers: https://leafletjs.com/reference-1.3.4.html#tilelayer


text:
Q: Load Multiple Library in C program I dont know if this is a bad question, but I am having some problem of an undefined symbol when my program is run.
I have more than 20 dynamic libraries,
When I run my program that loads my library
 void *encode_func  = dlopen("lib_9_3.so", RTLD_LAZY  );

It returns error as undefined symbol,
All its symbol depends upon those 20 dynamic libraries
Can I load all those dynamic libraries in my C program ???
EDIT::
if ( encode_func == NULL)
    {
            fprintf(stderr, "dlopen failed: %s\n", dlerror());
            return 1;
    }

Code is fine,
dlerror is returning
 dlopen failed: ./lib_9_3.so: undefined symbol: sip_getExtensionParamCountFromFromHdr

These symbols are present in my 20 dynamic libraries,
I found this out by doing  "nm"
One more thing, these undefined symbols are not system specific.
Can I load all those dynamic libraries in my C program ???


text:
Q: Handling exceptions in exception block Could someone please provide some good practice to handle exceptions in exception for   example I have
 try {
 ...
 DeserializationResult deserialization = xmlSerializationService.deserializeFromXml(node);
 some code here
} catch (Exception e) {

try {

//I need to create process result xml with error code and some details
// creation of result xml document

} catch (Exception e) {

// maybe some error message here

  }

}

can I somehow make this code looks clearer, noiseless and easier to understand?
Thanks for answers. P.S. I know that using general exception is not good practice, its just for example purpose here.

A: The first approximation for solving that problem is usually to put the logic of the catch in a separate method, and only have one line in the catch block (the method call).

A: Always catch specific exceptions, not the general Exception superclass.
If I look at that code, I'm not sure what can go wrong. If you specifically catch exceptions, it's much easier to see what failures you are expecting and catering for.
Also handle each failure in a specific way that makes sense for that failure. The simplest form of that is to return a result that describes the failure.
Maybe something like:
try{
    //DeserializationResult deserialization = xmlSerializationService.deserializeFromXml(node);
    //some code here
}catch(NullPointerException npe){
    //Maybe return something like: new DeserializationResult("xmlSerializationService not initialized")
}catch(DeserializationException dse){
    //Maybe return something like: new DeserializationResult("Could not deserialize because ...")
}


text:
Q: Facebook client side App authorization in codeigniter I'm having trouble with facebook javascript client side App authorization. The code below works as expect when the App is not authorized, App authorization popup appears. When the same code runs in codeignigter the authorization dialog fails to appear.
      // Load the SDK Asynchronously
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
   }(document));

  // Init the SDK upon load
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '169550646480230', // App ID
      channelUrl : '//'+window.location.hostname+'/channel', // Path to your Channel File
      status     : true, // check login status
      cookie     : true, // enable cookies to allow the server to access the session
      xfbml      : true  // parse XFBML
    });

A: This might be due to two things (I am making assumptions here):

*

*CSRF is enabled and blocking the external response from Facebook

*response from FB is filtered out due to invalid URI characters.

Disable CSRF first, and check if it works, that would be my starting point.

A: Figured this one out.
Any PHP facebook calls that are run before the Javascript authentication will generate an exception on the server and stop all HTML activity. I guess its called Async for a reason.


text:
Q: PHP Ratchet - send message from client to server on disconnect I have a chat application, client code written in javascript and some jquery and server code is written with php
i'm using ratchet websockets : http://socketo.me/
according to the official tutorial : http://socketo.me/docs/hello-world , with javascript there are only two events : onopen and onmessage
i was wondering if i can detect the disconnection on the client side and send a message(example : JSON message) from the client (with javascript) to the server just before the client disconnects
i can detect that the client disconnected in the server but i can't get that message that i need
any ideas ?


text:
Q: How to use CoreMotion in WatchKit? I was quite dubious on this question's title phrasing, but I think that's the whole point as it is.
I've been trying to just read the CoreMotion data on the WatchKit, but as it turns out, I can't get startDeviceMotionUpdatesToQueue to work, my handler is never called.
I tried running in a custom background thread (NSOperationQueue()), still no luck.
I'm debugging on a real Apple Watch, not the simulator.
In my WKInterfaceController:
let manager = CMMotionManager()

override func awakeWithContext(context: AnyObject?) {
    super.awakeWithContext(context)
    let communicator = SessionDelegate()
    manager.deviceMotionUpdateInterval = 1 / 60
    manager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) {
        (motionerOp: CMDeviceMotion?, errorOp: NSError?) -> Void in
        print("got into handler")
        guard let motion = motionerOp else {
            if let error = errorOp {
                print(error.localizedDescription)
            }
            assertionFailure()
            return
        }
        print("passed guard")
        let roll = motion.attitude.roll
        let pitch = motion.attitude.pitch
        let yaw = motion.attitude.yaw
        let attitudeToSend = ["roll": roll, "pitch": pitch, "yaw": yaw]
        communicator.send(attitudeToSend)
    }

    print("normal stack")
}

the output is
normal stack
normal stack

(Yes, twice! I don't know why that either, but that is not the point, must be another thing I'm doing wrongly)
I'm posting this here 'cause I have no clue to where look into, this is freaking crazy.

A: Device Motion (startDeviceMotionUpdatesToQueue) is not available in WatchOS2 yet (deviceMotionAvailable returns false), probably accelerometer can help you startAccelerometerUpdatesToQueue