text:
Q: How to push items from orderBy method to the Firestore database in the same order? I have a collection of user posts with documents that contain unique id's. In each document is a timestamp created by the server. To visualize the structure looks like this:

userPosts (collection) -> uniqueID (document) -> timeStamp (field)

There are around 100 or so uniqueID's with different timeStamp values. I have queried and ordered my data by the timeStamp field, using .orderBy() and have the ordered results and wish to write to a document in another collection called "mostRecent" with roughly this structure:

mostRecent (collection) -> recentTwenty(document) -> posts (array of maps)

await db.collection(userPosts)
.orderBy("timeStamp").limit(20).get()
    .then((querySnapshot) => {
            querySnapshot.docs.map((item,key) => {
               console.log(item.data())
               db.collection("mostRecent").doc("recentTwenty")
                 .update(
                    {
                      posts: FieldValue.arrayUnion(item.data())
                    },
                    { merge: true }
                  )
            }
     });

When console.log(item.data) the data is correctly ordered by the timestamp field. However, when I call .update() with the correctly ordered items in item.data() to the recentTwenty doc the order is completely out of whack. I would love to understand what is going on. Thanks in advance for whoever helps me out!

A: You are NOT waiting for each .update() to complete - it IS an asynchronous operation.  Whether it works at ALL also depends on what code you're running outside of what you show - I see no proof that the operations are guaranteed to be competed.  The OUTER await doesn't guarantee the synchronicity of the INNER loop.
Firestore arrays ARE ordered by the order they were inserted (if that's how you create them) -but the order the DATABASE will see the operations, as you have shown it here, will depend on Network conditions, etc - you've set up a race condition.  At a MINIMUM, you need to await the result of EACH .update() operation to get them in sequence.
A bigger question, though, is WHY use individual .update() at all?  Just collect your information using the .map, and write the array in a single operation:
await db.collection(userPosts)
.orderBy("timeStamp").limit(20).get()
    .then((querySnapshot) => {
            //the following .map() is SYNCHRONOUS
            let result_array = querySnapshot.docs.map((item,key) => {
               console.log(item.data())
               return item.data();
            });
            //return the PROMISE from the .set(), for the OUTER await
            return db.collection("mostRecent").doc("recentTwenty")
                 .set(
                    {
                      posts: result_array;
                    },
                    { merge: true }
                  )
     });

a single write to the database (which is less expensive)

A: Your problem is that the map runs over a callback function and in your case it is a function with an asynchronous .update() function call. Therefore, you will be never be able to be 100% sure that this will be in order. For that you need the execute them in a synchronous call in for loop.
  return new Promise((resolve, reject) => {
    db.collection("mostRecent").doc("recentTwenty")
      .update(
        {
          posts: FieldValue.arrayUnion(item.data())
        },
        { merge: true }
      )
      .then((result) => resolve(result))
      .catch((err) => reject(err))
    ;
  });
};

await db.collection(userPosts)
  .orderBy("timeStamp").limit(20).get()
  .then(async (querySnapshot) => {
    for(let i = 0; i < querySnapshot.docs.length; i++) {
      await updateItem(querySnapshot.docs[i]);
    }
  })
;

You could also find a way to bulk update all the querySnapshot.docs in a single operation, which would have a better performance. However, I don't know firebase very well so I can't help you on this.


text:
Q: Save data through the controller after an event has been fired in laravel I'm allowing a user to upload a post which includes an image and some related information as well as select the promotion fee[bronze,silver or gold].In my /post controller i'm validating the request and then sending a request to another API[third party api for performing  payments].The API takes the user phone number and the promotion fee selected and does the payment transaction.So i made the Transaction model[used to save details concerning the completed transaction]to dispatch a created event since i  want to save the other post related information only if the payment is successful.
I've tried to create the listener for the TransactionCreatedEvent but i can't find a way to pass the post related data into the listener in order to save them. I also tried to use the closure by calling the listen method on the Event Facade inside the post controller to no avail.

A: Mh, i'm not quite sure if i undestood you question correctly, but in you case, you could either relate the Transaction with the post, or  pass the Transaction and the Post Model to any event or to a job, and then do whatever you want with the data in the event handler or job

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to translate an email snippet in Laravel? My language is Brazilian Portuguese, and I'm having trouble translating a snippet of an email template that Laravel sends to the user. in /vendor/laravel/framework/src/Illuminate/Auth/Notifications/ResetPassword I managed to translate most of the template, but a snippet I couldn't, as I don't know where it is located.

I would like to know where is the location of the passages marked in red to translate in my language (i'm using Laravel Breeze application).

A: They can be translated in the JSON file in the lang directory (see the docs).
You can download a prefilled translation file here (just rename it "pt_BR.json" and place it in /lang/): https://github.com/Laravel-Lang/lang/blob/main/locales/pt_BR/json.json
You're free to modify these translations as you wish.


text:
Q: Failed to decode image. The provided image must be a Bitmap BitmapDescriptor bmpD = BitmapDescriptorFactory.fromResource(R.raw.podval);

    Log.d("myLog", ":" + bmpD);

    GroundOverlayOptions newarkMap = new GroundOverlayOptions()
            .image(bmpD)
            .position(sydney, 8600f, 6500f);
    Log.d("myLog", ":" + newarkMap);
    GroundOverlay imageOverlay = mMap.addGroundOverlay(newarkMap);

Failed to decode image. The provided image must be a Bitmap.
But in log I got :com.google.android.gms.maps.model.BitmapDescriptor@58e0ee6
:com.google.android.gms.maps.model.GroundOverlayOptions@1ea9c27
Also I converted jpg image to bmp, after failing to convert it here
Help please.

A: See https://stackoverflow.com/a/45564994/2914140 for vector drawables (SVG).
private BitmapDescriptor bitmapDescriptorFromVector(Context context, @DrawableRes int vectorResId) {
        Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
        vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
        Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.draw(canvas);
        return BitmapDescriptorFactory.fromBitmap(bitmap);
}

A: Place your image in the drawable folder, not in the raw folder. Also make sure the resource is a valid image file.


text:
Q: Parametrizing Rust trait on list of types? I'm toying with an idea for a computation-graph based game engine. The gist is that each abstract concept (Player, Map, Enemy, Spaceship, etc) is a node in a DAG. The nodes themselves are simply Rust types which implement a "Component" interface which specifies how
a. How members of the Component are created/deleted/retrieved
b. What other Components the Component relies on (ie, what are the dependencies?)
c. How to update a member of the Component
Expressing (a) is easy enough: here's a trait which (I think :) specifies this behavior
pub trait Component {
    type KeyType: Copy; // Each member of a Component is associated with a key

    fn Add(_: Self::KeyType) -> bool;
    fn Delete(_: Self::KeyType) -> bool;
    fn Get<'a>(_: Self::KeyType) -> Option<&'a Self>;
    fn GetAll<'a>() -> dyn Iterator<Item = (Self::KeyType, &'a Self)>;

    // TODO This block will be described next
}

An implementation is easy to imagine: an impl corresponding to the Player Component could just use player IDs (u32, for instance) for keys, and then basically implement all the other functions using some static(global) hash map. So far so good.

(b) and (c) are harder. I'd like to express through the trait

*

*A Component can "rely" on (members of) other Components

*A member of a Component can specify which members of its dependencies that it requires to update itself.

*Each member of a Component implements a function using the results of (2) to update itself.

In other words, I want the TODO block from above to express to something like this
// (a) Each Component specifies its dependencies as a list (set) of Components. This list is fixed at compile time.
type Dependencies: [Component;]

// For each Dependency, a member of the Component can specify a list of members that it needs. The keys of the returned map are fixed at compile time, but the requested members can always change
fn GetDependencyMembers(&mut self) -> Map<DepType d, List<d::KeyType>>

// Each Component must implement an "update" function which looks like the following.
// "N" varies from component to component.
fn Update<'a>(
    List&'a Dep1Type>,
    ...
    List<&'a DepNType>,
)

Unfortunately, my meager rust isn't adequate to translate this into working code. Could someone with more knowledge show me how I should write this?


text:
Q: Resource handler returned message: "Invalid request (Service: Connect, Status Code: 400) I am trying to create Amazon Connect Contact flows using the cloudformation template and Amazon Contact flow language which is new for me. But I am
facing this issue and the stack fails to create. I am not sure If I am having syntax errors in my yml file.
Complete error message
Resource handler returned message: "Invalid request (Service: Connect, Status Code: 400, Request ID: aa1e1049-47bb-43ea-8065-0f8b1cf503d2)" (RequestToken: ff62940b-0e60-2308-d33d-917eeb399402, HandlerErrorCode: InvalidRequest)

Here is the cloud formation template
---
AWSTemplateFormatVersion: "2010-09-09"
Description: "Amazon Connect - Contact Flow"

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: "General Information"
        Parameters:
          - SystemName
          - EnvironmentName
      - Label:
          default: "Amazon Connect Information"
        Parameters:
          - InstanceID
          - ContactFlowName

Parameters:
  SystemName:
    Type: String
  EnvironmentName:
    Type: String
    AllowedValues: [prd, stg, dev]
  InstanceID:
    Type: String
    Description: "Enter the Amazon Connect Instance ID (e.g. 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx')"
  ContactFlowName:
    Type: String
    Description: "Enter the Name of the Contact flow"

Resources:
  ContactFlow:
    Type: 'AWS::Connect::ContactFlow'
    Properties:
      Name: !Sub "${ContactFlowName}"
      Description: Example contact flow
      InstanceArn: !Sub "arn:aws:connect:${AWS::Region}:${AWS::AccountId}:instance/${InstanceID}"
      Type: CONTACT_FLOW
      Content: |
        {
          "Version": "2019-10-30",
            "StartAction": "c8275c19-08aa-4ee5-9b42-bcc47d32e914",
            "Metadata": {
            "entryPointPosition": {
                "x": 20,
                "y": 20
            },
            "snapToGrid": false,
            "ActionMetadata": {
                "5c47b68e-d790-45eb-a0bd-654027af4868": {
                "position": {
                    "x": 463,
                    "y": 491
                },
                "useDynamic": false
                },
                "c8275c19-08aa-4ee5-9b42-bcc47d32e914": {
                "position": {
                    "x": 180,
                    "y": 20
                },
                "conditionMetadata": [
                    {
                    "id": "6a7b09ef-d441-4183-8ef3-2f0f360ba747",
                    "value": "1"
                    },
                    {
                    "id": "f3516737-c758-4d6f-8d31-ea43d1e27990",
                    "value": "2"
                    },
                    {
                    "id": "21ad3977-2559-4449-ba54-b84d4a0521b6",
                    "value": "3"
                    }
                ],
                "useDynamic": false,
                "useLexBotDropdown": true,
                "useDynamicLexBotArn": false
                },
                "c36d9f86-780d-4c44-8c79-80c8353a699a": {
                "position": {
                    "x": 1068,
                    "y": 317
                }
                },
                "14837518-cc08-4d54-ac93-ea7e063481a8": {
                "position": {
                    "x": 492,
                    "y": 340
                },
                "overrideConsoleVoice": false,
                "defaultVoice": "Standard"
                },
                "1e435e5f-7b62-4938-8c9f-fa05106c72b3": {
                "position": {
                    "x": 501,
                    "y": 174
                },
                "overrideConsoleVoice": false,
                "defaultVoice": "Standard"
                },
                "98768cdb-f5e6-4642-90e3-6e06fd6813e8": {
                "position": {
                    "x": 478,
                    "y": 21
                },
                "overrideConsoleVoice": false,
                "defaultVoice": "Conversational",
                "fragments": {
                    "SetContactData": "bc981918-e0b3-4840-afa5-12b6d7078248"
                }
                },
                "bc981918-e0b3-4840-afa5-12b6d7078248": {
                "position": {
                    "x": 0,
                    "y": 0
                }
                },
                "3a521089-edfe-4821-8156-19014b7b8926": {
                "position": {
                    "x": 716,
                    "y": 45
                },
                "useDynamic": false,
                "ContactFlow": {
                    "id": "arn:aws:connect:eu-central-1:132387760551:instance/a65f970f-0f59-444e-b421-5ec6ec74c116/contact-flow/d727e34f-6707-437f-8013-20e4f2a867d6",
                    "text": "Transaction Banking Authentication"
                }
                }
            }
            },
            "Actions": [
            {
                "Identifier": "5c47b68e-d790-45eb-a0bd-654027af4868",
                "Parameters": {
                "Text": "An Error Occured!"
                },
                "Transitions": {
                "NextAction": "c36d9f86-780d-4c44-8c79-80c8353a699a",
                "Errors": [
                    {
                    "NextAction": "c36d9f86-780d-4c44-8c79-80c8353a699a",
                    "ErrorType": "NoMatchingError"
                    }
                ],
                "Conditions": []
                },
                "Type": "MessageParticipant"
            },
            {
                "Identifier": "c8275c19-08aa-4ee5-9b42-bcc47d32e914",
                "Parameters": {
                "Text": "To continue in English press 1, Ukuqhubeka ngesiZulu cindezela u- 2, Vir Afrikaans Druk 3.",
                "StoreInput": "False",
                "InputTimeLimitSeconds": "5"
                },
                "Transitions": {
                "NextAction": "5c47b68e-d790-45eb-a0bd-654027af4868",
                "Errors": [
                    {
                    "NextAction": "5c47b68e-d790-45eb-a0bd-654027af4868",
                    "ErrorType": "NoMatchingError"
                    },
                    {
                    "NextAction": "5c47b68e-d790-45eb-a0bd-654027af4868",
                    "ErrorType": "NoMatchingCondition"
                    },
                    {
                    "NextAction": "5c47b68e-d790-45eb-a0bd-654027af4868",
                    "ErrorType": "InputTimeLimitExceeded"
                    }
                ],
                "Conditions": [
                    {
                    "NextAction": "98768cdb-f5e6-4642-90e3-6e06fd6813e8",
                    "Condition": {
                        "Operator": "Equals",
                        "Operands": [
                        "1"
                        ]
                    }
                    },
                    {
                    "NextAction": "1e435e5f-7b62-4938-8c9f-fa05106c72b3",
                    "Condition": {
                        "Operator": "Equals",
                        "Operands": [
                        "2"
                        ]
                    }
                    },
                    {
                    "NextAction": "14837518-cc08-4d54-ac93-ea7e063481a8",
                    "Condition": {
                        "Operator": "Equals",
                        "Operands": [
                        "3"
                        ]
                    }
                    }
                ]
                },
                "Type": "GetParticipantInput"
            },
            {
                "Identifier": "c36d9f86-780d-4c44-8c79-80c8353a699a",
                "Type": "DisconnectParticipant",
                "Parameters": {},
                "Transitions": {}
            },
            {
                "Identifier": "14837518-cc08-4d54-ac93-ea7e063481a8",
                "Parameters": {
                "TextToSpeechVoice": "Lotte"
                },
                "Transitions": {
                "NextAction": "3a521089-edfe-4821-8156-19014b7b8926",
                "Errors": [],
                "Conditions": []
                },
                "Type": "UpdateContactTextToSpeechVoice"
            },
            {
                "Identifier": "1e435e5f-7b62-4938-8c9f-fa05106c72b3",
                "Parameters": {
                "TextToSpeechVoice": "Marlene"
                },
                "Transitions": {
                "NextAction": "3a521089-edfe-4821-8156-19014b7b8926",
                "Errors": [],
                "Conditions": []
                },
                "Type": "UpdateContactTextToSpeechVoice"
            },
            {
                "Identifier": "98768cdb-f5e6-4642-90e3-6e06fd6813e8",
                "Parameters": {
                "TextToSpeechVoice": "Joanna"
                },
                "Transitions": {
                "NextAction": "bc981918-e0b3-4840-afa5-12b6d7078248",
                "Errors": [],
                "Conditions": []
                },
                "Type": "UpdateContactTextToSpeechVoice"
            },
            {
                "Identifier": "bc981918-e0b3-4840-afa5-12b6d7078248",
                "Parameters": {
                "LanguageCode": "en-US"
                },
                "Transitions": {
                "NextAction": "3a521089-edfe-4821-8156-19014b7b8926",
                "Errors": [
                    {
                    "NextAction": "3a521089-edfe-4821-8156-19014b7b8926",
                    "ErrorType": "NoMatchingError"
                    }
                ],
                "Conditions": []
                },
                "Type": "UpdateContactData"
            },
            {
                "Identifier": "3a521089-edfe-4821-8156-19014b7b8926",
                "Parameters": {
                "ContactFlowId": "arn:aws:connect:eu-central-1:132387760551:instance/a65f970f-0f59-444e-b421-5ec6ec74c116/contact-flow/d727e34f-6707-437f-8013-20e4f2a867d6"
                },
                "Transitions": {
                "NextAction": "c36d9f86-780d-4c44-8c79-80c8353a699a",
                "Errors": [
                    {
                    "NextAction": "c36d9f86-780d-4c44-8c79-80c8353a699a",
                    "ErrorType": "NoMatchingError"
                    }
                ],
                "Conditions": []
                },
                "Type": "TransferToFlow"
            }
            ]
      Tags:
        - Key: System
          Value: !Ref SystemName
        - Key: Environment
          Value: !Ref EnvironmentName

Any kinda  help will Appreciated

A: Okay, looks like the Content object is not valid. For starters it ends with a ] character instead of a } But even fixing that it has issues.
I'd suggest creating a flow in the gui and export it, then use the json from that as a template.
Also, check the Flow language documentation to get the syntax and structure correct.


text:
Q: Is it necessary to use mysqli_real_escape_string with data from  inputs? Just as the title states.  Is it a standard procedure/practice to escape number inputs?
I know text fields should be escaped, but i'm wondering if I need to escape numbers.

A: You should use Prepared Statement. But if you don't wish to do that, at least cast some data type, for example:
<?php
$myVar = (int)$_POST['user_age'];
$myVar = (float)$_POST['user_salary'];


text:
Q: How can I use SqlBulkCopy from Entity Framework database connection in unknown state I have a static helper method for bulk inserting Entity Framework objects. It works and my unit tests pass but it looks wrong and I can't help but think there must be a better way to do it.
public static void BulkInsert<T>(Entities db, IList<T> list)
{
    SqlTransaction transaction =  db.Database.CurrentTransaction != null ? db.Database.CurrentTransaction.UnderlyingTransaction as SqlTransaction : null;

    if (db.Database.Connection.State != ConnectionState.Open)
    {
        db.Database.Connection.Open();
    }

    using (var bulkCopy = new SqlBulkCopy((db.Database.Connection) as SqlConnection, SqlBulkCopyOptions.Default, transaction))
    {
        //fill a datatable and write to server, this bit works
    }
}

It could be called inside a DbContextTransaction and/or the DbContext.Database might have done something already so the connection might be open. If you don't explicitly open the connection before creating the bulk copy you get an error:

System.InvalidOperationException: WriteToServer requires an open and available Connection

which is odd, I'd have thought that sqlBulkCopy would have opened the connection if it had to.
So my question is am I going about this the right way?

A: I have used your approach successfully myself.
My feeling is that you should close it again if you opened it.
I would additionally let SqlBulkCopy handle the transaction itself. I don't think enlisting SqlBulkCopy into any ambient transaction is a great idea unless your particular scenario absolutely demands it.
public static void BulkInsert<T>(PandaDataContext db, IList<T> list)
{
    var mustOpen = db.Database.Connection.State != ConnectionState.Open;
    try
    {
        if (mustOpen)
            db.Database.Connection.Open();
        using (var bulkCopy = new SqlBulkCopy((db.Database.Connection) as SqlConnection, SqlBulkCopyOptions.Default))
        {
        }
    }
    finally
    {
        if (mustOpen)
            db.Database.Connection.Close();
    }
}


text:
Q: Why does the cycle of Link and Gannondorf keep repeating itself? In my last question it was mentioned that it is the same Gannondorf returning, and a different hero of ages is chosen.
Why does this 'triforce' cycle keep repeating itself? Is there an in-universe explanation?

A: The short answer is: Because of Demise's Curse of Incarnation
As, I somewhat mentioned in my answer to that same question, the cycle of "Ganon" is referenced to the spirit of Demise resurfacing every so often.
You can watch the sequence that alludes to this here: Youtube Link
The short of it is that Demise is defeated for the first time by the Hero of Time with the Master Sword at the charge of the goddess. The spirit of despair manifested in Gannon will resurface, this is indicated somewhere in there.
It's a little vague, but the reasoning is that evil cannot be defeated and destroyed forever, but sealed, or put to sleep. It will resurface as many times as the franchise requires.
The Hero of Time is always chosen by the goddess, because if not, the world will be held by Ganon. Zelda's purpose is less clear, but perhaps she is simply the final piece of the puzzle, always.
SPOILER
The clip below shows exactly what happens and what is said to set the gears in motion. Go right to the end of it. Basically Demise, in his defeat is held by the curse of incarnation, explaining that the incarnation of his will, as well as the Hero of Time, and Zelda, will always be bound to conflict whenever he rises again (as Ganon).
End of Demise and His Curse
The Trio
Just so it's clear, the people in this loop are:
Ganon (or the will of Demise)
Zelda (having the blood of the goddess)
The Hero of Time (chosen by the goddess each time)


text:
Q: Optimizing GLViewWidget MeshItem plot I'm plotting 100K+ cylinders which are added to a GLViewWidget like this:
openGlWidget = GLViewWidget()

points = np.array([
    [0, 1, 2],
    [0, 1, 5],
    [4, 1, 6],
    [4, 1, 10]
])

cyl = MeshData.cylinder(6, 6, radius=[.1, .1])

for i in range(0, len(points), 2):
    mesh = GLMeshItem(meshdata=cyl)

    p1, p2 = points[i], points[i+1]

    v = p2 - p1
    theta = np.arctan2(v[1], v[0])
    phi = np.arctan2(np.linalg.norm(v[:2]), v[2])

    tr = Transform3D()
    tr.translate(*p1)
    tr.rotate(theta * 180 / np.pi, 0, 0, 1)
    tr.rotate(phi * 180 / np.pi, 0, 1, 0)
    tr.translate(0, 0, 1)
    tr.scale(1, 1, np.linalg.norm(v1))

    mesh.setTransform(tr)

    self.openGlWidget.addItem(mesh)

This of course gives low fps when rotating/paning and I assume a good part of it has to do with adding that many singular items. So, I started thinking about the possibility of combining the cylinders into one item, is this possible? And/or should I be using something else than the GLViewWidget?


text:
Q: How to clean up Stack overflow account, means delete all deleted answers or Posts on my account permanently from SO? I know if we delete any post or answer it is not deleted permanently, Suppose for example this post which is deleted including my answer but still the post is visible to users having 10K+ reputations.
Questions :
1) Is it possible to delete that answer permanently from SO?
2) Is there a way to raise request to SO people to clean my account (which means delete all deleted answers or Posts on my account permanently from SO)?

A: *

*No. In theory, you could get a post dissociated (which isn't really deletion), but "I regret posting that" isn't a good reason. More or less, its worth actually thinking before you post. Nothing you post on SE is completely gone, I suspect. The only things that seem gone gone are redacted posts, and those are probably saved somewhere. Practically, the best thing is to actually consider what you post and where you post it before you do.

*No, and honestly, it's probably a bit of a waste of resources and wouldn't scale at all if people started doing it.


text:
Q: Python: Make duplicate keys unique json response I am extracting data through POST method and let's say we have different post data in a list and for each request there will be a different post data like this:
cookies = {
    "_sp_id.cf1a": "205e16a5-8970-4c92-97b8-969eebfcbb63.1647289721.7.1648545896.1648465133.73852927-e047-4c36-bae7-90c001509900",
    "_sp_ses.cf1a": "*",
}

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:98.0) Gecko/20100101 Firefox/98.0",
    "Accept": "text/plain, */*; q=0.01",
    "Accept-Language": "en-US,en;q=0.5",
    "Accept-Encoding": "gzip, deflate, br",
    "Referer": "https://www.tradingview.com/",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
    "Origin": "https://www.tradingview.com",
    "Connection": "keep-alive",
    # Requests sorts cookies= alphabetically
    # 'Cookie': '_sp_id.cf1a=205e16a5-8970-4c92-97b8-969eebfcbb63.1647289721.7.1648545896.1648465133.73852927-e047-4c36-bae7-90c001509900; _sp_ses.cf1a=*',
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-site",
    "Sec-GPC": "1",
    # Requests doesn't support trailers
    # 'TE': 'trailers',
}

    data = [
        '{"filter":[{"left":"name","operation":"nempty"},{"left":"exchange","operation":"in_range","right":["AMEX","NASDAQ","NYSE"]},{"left":"High.All","operation":"eless","right":"high"},{"left":"is_primary","operation":"equal","right":true},{"left":"subtype","operation":"nequal","right":"preferred"}],"options":{"lang":"en","active_symbols_only":true},"markets":["america"],"symbols":{"query":{"types":[]},"tickers":[]},"columns":["logoid","name","close","change","change_abs","Recommend.All","volume","Value.Traded","market_cap_basic","price_earnings_ttm","earnings_per_share_basic_ttm","number_of_employees","sector","description","type","subtype","update_mode","pricescale","minmov","fractional","minmove2","currency","fundamental_currency_code"],"sort":{"sortBy":"name","sortOrder":"asc"},"range":[0,150]}',
        '{"filter":[{"left":"name","operation":"nempty"},{"left":"exchange","operation":"in_range","right":["AMEX","NASDAQ","NYSE"]},{"left":"High.All","operation":"eless","right":"high"},{"left":"is_primary","operation":"equal","right":true},{"left":"subtype","operation":"nequal","right":"preferred"}],"options":{"lang":"en","active_symbols_only":true},"markets":["america"],"symbols":{"query":{"types":[]},"tickers":[]},"columns":["logoid","name","change|1","change|5","change|15","change|60","change|240","change","change|1W","change|1M","Perf.3M","Perf.6M","Perf.YTD","Perf.Y","beta_1_year","Volatility.D","description","type","subtype","update_mode","currency","fundamental_currency_code"],"sort":{"sortBy":"name","sortOrder":"asc"},"range":[0,150]}',
    ]

        with httpx.Client() as client:
            for d in data:
                r = client.post(
                    "https://scanner.tradingview.com/america/scan",
                    headers=headers,
                    cookies=cookies,
                    data=d,
                )

I store post data in a list and iterating over it and passing it in request object, so far so good. Post requests returns json object and problem begins here, every request returns different json object except keys, they are the same for e.g
'{"filter":[{"left":"name","operation":"nempty"},{"left":"exchange","operation":"in_range","right":["AMEX","NASDAQ","NYSE"]},{"left":"High.All","operation":"eless","right":"high"},{"left":"is_primary","operation":"equal","right":true},{"left":"subtype","operation":"nequal","right":"preferred"}],"options":{"lang":"en","active_symbols_only":true},"markets":["america"],"symbols":{"query":{"types":[]},"tickers":[]},"columns":["logoid","name","change|1","change|5","change|15","change|60","change|240","change","change|1W","change|1M","Perf.3M","Perf.6M","Perf.YTD","Perf.Y","beta_1_year","Volatility.D","description","type","subtype","update_mode","currency","fundamental_currency_code"],"sort":{"sortBy":"name","sortOrder":"asc"},"range":[0,150]}'

this post data returns this json:
{
  "totalCount": 141,
  "data": [
    {
      "s": "NYSE:ABBV",
      "d": [
        "abbvie",
        "ABBV",
        0,
        0.13602918,
        0.2662209,
        0.37497288,
        0.6400696,
        0.39670241,
        0.39670241,
        9.60952832,
        20.52236029,
        48.81477398,
        19.62333826,
        51.75676942,
        0.5128781,
        1.56710337,
        "AbbVie Inc.",
        "stock",
        "common",
        "delayed_streaming_900",
        "USD",
        "USD"
      ]
    }
  ]
}

and post data
{"filter":[{"left":"name","operation":"nempty"},{"left":"exchange","operation":"in_range","right":["AMEX","NASDAQ","NYSE"]},{"left":"High.All","operation":"eless","right":"high"},{"left":"is_primary","operation":"equal","right":true},{"left":"subtype","operation":"nequal","right":"preferred"}],"options":{"lang":"en","active_symbols_only":true},"markets":["america"],"symbols":{"query":{"types":[]},"tickers":[]},"columns":["logoid","name","close","change","change_abs","Recommend.All","volume","Value.Traded","market_cap_basic","price_earnings_ttm","earnings_per_share_basic_ttm","number_of_employees","sector","description","type","subtype","update_mode","pricescale","minmov","fractional","minmove2","currency","fundamental_currency_code"],"sort":{"sortBy":"name","sortOrder":"asc"},"range":[0,150]}'

returns this which is similar to the last one i.e. keys but values are different
{
  "totalCount": 141,
  "data": [
    {
      "s": "NYSE:ABBV",
      "d": [
        "abbvie",
        "ABBV",
        161.97,
        0.39670241,
        0.64,
        0.42121212,
        4516453,
        731529892.41,
        286085169370,
        25.01356652,
        6.4775,
        50000,
        "Health Technology",
        "AbbVie Inc.",
        "stock",
        "common",
        "delayed_streaming_900",
        100,
        1,
        "false",
        0,
        "USD",
        "USD"
      ]
    }
  ]
}

Hence I am getting just one json object which is the last one in the loop instead of both.
Desired Output:
    {
  "overview": {
    "totalCount": 141,
    "data": [
      {
        "s": "NYSE:ABBV",
        "d": [
          "abbvie",
          "ABBV",
          161.97,
          0.39670241,
          0.64,
          0.42121212,
          4516453,
          731529892.41,
          286085169370,
          25.01356652,
          6.4775,
          50000,
          "Health Technology",
          "AbbVie Inc.",
          "stock",
          "common",
          "delayed_streaming_900",
          100,
          1,
          "false",
          0,
          "USD",
          "USD"
        ]
      }
    ]
  },
  "performance": {
    "totalCount": 141,
    "data": [
      {
        "s": "NYSE:ABBV",
        "d": [
          "abbvie",
          "ABBV",
          0,
          0.13602918,
          0.2662209,
          0.37497288,
          0.6400696,
          0.39670241,
          0.39670241,
          9.60952832,
          20.52236029,
          48.81477398,
          19.62333826,
          51.75676942,
          0.5128781,
          1.56710337,
          "AbbVie Inc.",
          "stock",
          "common",
          "delayed_streaming_900",
          "USD",
          "USD"
        ]
      }
    ]
  }
}

I am looking for some solution to handle this kind of duplication in json response and get data from different post data on each request by making the duplicate keys to unique.


text:
Q: How to Resize Ubuntu 17.04 Zesty Swap file size? Last night, I was converting movies with handbrake. There was steam and ubuntu software centre running in background. When I woke up, I saw a message 'Ubuntu faced an internal error......' and handbrake is crashed. So, I think it was because of lack of swap memory (2GB swap file). Anyone knows how to increase swap file size? (My PC Have 4GB RAM)

A: I wouldn't try to resize it literally. Probably it is possible - maybe gparted could to it - but I can't think of a reason to bother and it would be quicker and simpler to just make a new one. First turn off the current one:
    swapoff -a
Delete the old one, then make a new one however big you want, and turn it on. If you give it the same /path/name, you won't even need to change fstab, and you will have EFFECTIVELY, if not literally, enlarged the swap file. Somebody at Redhat here:
https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/5/html/Deployment_Guide/s2-swap-creating-file.html
wrote this (I quote 'cause some fora frown on incorporation by ref, but the block quote button messes with the format, so I'm editing this to just paste it in plain):
# # # QUOTATION FOLLOWS # # #
To add a swap file:
Determine the size of the new swap file in megabytes and multiply by 1024 to determine the number of blocks. For example, the block size of a 64 MB swap file is 65536.
At a shell prompt as root, type the following command with count being equal to the desired block size:
dd if=/dev/zero of=/swapfile bs=1024 count=65536

Change the persmissions of the newly created file:

chmod 0600 /swapfile

Setup the swap file with the command:

mkswap /swapfile

To enable the swap file immediately but not automatically at boot time:

swapon /swapfile

To enable it at boot time, edit /etc/fstab to include the following entry:
/swapfile          swap            swap    defaults        0 0

The next time the system boots, it enables the new swap file.
After adding the new swap file and enabling it, verify it is enabled by viewing the output of the command cat /proc/swaps or free.
# # # END QUOTATION # # #
If you already have a swap file, you probably already know most of that. Anyway, I think that is close to a literal answer to the question as posed.
But if it is only in this one context that you need a bigger swap, and it doesn't happen often, if you are short of drive space, you might consider, instead of REPLACING your swap file, just make and mount an ADDITIONAL one prior to when you need it. They are cumulative. You can have as many as you want. Then you can unmount and delete it when you are through.
Regarding the issue of swap file vs. swap partition that Ravery touched on, much of what you will read on that subject is out of date. Unless your swap partition is on another drive (and maybe I should even say another drive controller) it isn't likely to be any faster than a swap file. And it is definitely less flexible. Unless it is on a separate drive, I can't see a lot of reason to use a swap partition any more.


text:
Q: What is the term for decade, century, millenium, etc? What is the terminology for a decade, century, millennium, etc?

A: They're called units of time or midst units.

Midst unit: A unit of time or midst unit is any particular time interval, used as a standard way of measuring or expressing duration.
Examples: Month, year, decade, century, millennium etc.

— Wikipedia


text:
Q: Select Calendar Date and Update Link Label I have a Link Label on my page. When I click on the label a calendar pops up. When I click on a date on the calendar I want my link label to update to that particular date in this format '30 JAN 2017'
The issue is because of the local variable var dateText =..., My label never updates but gets the correct format.
If I comment or remove the date formatting section than my label updates to the correct date but does not contain the format I'm looking for.
How do I update my link label with the desired formatting when clicking on a specific date on the calendar?

$(document).ready(function() {

  $("#dp").datepicker({
    onSelect: function(dateText, inst) {

      var dateText = new Date().toLocaleString('en-GB', {
        day: 'numeric',
        month: 'short',
        year: 'numeric'
      }).split(' ').join(' ');

      $("#datep").html(dateText);
    },
    beforeShow: function(event, ui) {
      var $link = $("#datep");
      ui.dpDiv.offset({
        top: $link.offset().top + 10,
        left: $link.offset().left + 10
      });
    }
  });

  $("#datep").click(function() {
    $("#dp").datepicker("show");
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

Date Picker Link Label
<input type="hidden" id="dp" />

A: You're calling new Date().toLocaleString(..., which uses the current date. All you're missing is passing the dateText parameter to the Date constructor:

$(document).ready(function() {

  $("#dp").datepicker({
    onSelect: function(dateText, inst) {

      var dateText = new Date(dateText).toLocaleString('en-GB', {
        day: 'numeric',
        month: 'short',
        year: 'numeric'
      }).split(' ').join(' ');

      $("#datep").html(dateText);
    },
    beforeShow: function(event, ui) {
      var $link = $("#datep");
      ui.dpDiv.offset({
        top: $link.offset().top + 10,
        left: $link.offset().left + 10
      });
    }
  });

  $("#datep").click(function() {
    $("#dp").datepicker("show");
  });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

Date Picker Link Label
<input type="hidden" id="dp" />


text:
Q: Best way to manage Magic Strings in JavaScript external JS file Has T4MVC is not extensible to external JavaScript file, I would like to find the best way for manage "Magic Strings" like a Controller/Action value in a JQuery .load() method.
I want to minimize the risk of the change of an Action to provoque an error in the application. I know that I can compile the Views with Visual Studio to find client side errors, but not in JS external files.
I found some solutions like include a View as a javascript file type so I can use T4MVC and detect Views compilaion errors, but this approach makes a server unnecessary request and if it was JS it would be cached at the client side.
I'm thinking about a constant JS file, or in the limit, a constant View file with T4MVC params method.
Any better ideia?
I leave here a sample:
<script type="text/javascript">
$(function () {
    $('#Category_Id')
        .cascade(
        {
            url: '@Url.Action(MVC.Ad.ListCategoryTypeByCategory())',
            paramName: '@MVC.Ad.ListCategoryTypeByCategoryParams.categoryId',
            firstOption: '@HeelpResources.DropdownlistCategoryTypeFirstRecord',
            childSelect: $('#CategoryType_Id')
        })
        .cascade(
        {
            url: '@Url.Action(MVC.Ad.ListMakeByCategory())',
            paramName: '@MVC.Ad.ListMakeByCategoryParams.categoryId',
            firstOption: '@HeelpResources.DropdownlistMakeFirstRecord',
            childSelect: $('#Make_Id')
        });

    $('#Make_Id').cascade({
        url: '@Url.Action(MVC.Ad.ListModelByMake())',
        paramName: '@MVC.Ad.ListModelByMakeParams.makeId',
        firstOption: '@HeelpResources.DropdownlistModelFirstRecord',
        childSelect: $('#Model_Id')
    });
});
</script>

How can I avoid "Magic Strings" if I want to put this code in a JS external file?
Thanks.

A: I know you already tried that, but if you want to use T4MVC I would think that returning JS from a server side .cshtml file is probably your best bet. Note that doing that does not implied that it won't be cached on the client side (if you get the headers right). In fact, from the point of view of the client, returning a pure JS file and returning one that comes from a .cshtml is not really distinguishable. Either way, it gets JS back.

A: I think the method you use is fine, it's what I use. They aren't really magic strings because you are using route based Url generation, and you never have to worry about the Url's in the javascript becoming outdated.
Another approach could be to use a controller action that returns a JsonResult:
    public JsonResult GetConcentrationsMap() {
        var magicStrings = _magicStringsService.GetAll().Select(c => new { Name= c.Name, Url = c.Url });

        return Json(new { urls = magicStrings }, JsonRequestBehavior.AllowGet);
    }

This would get cached on the client, but as David Ebbo said, you can achieve that with .cshtml too. I think it's more trouble because you still have to manage telling your javascript code the path to the .js or json resource that has the magic strings.

A: You could use JavaScriptModel ( http://jsm.codeplex.com ).
If you need these "magic strings" globally, you should consider writing a filter and add them there.
Heres an example how to write a filter with JavaScriptModel:
http://jsm.codeplex.com/wikipage?title=Use%20JavaScriptModel%20in%20a%20global%20filter&referringTitle=Documentation


text:
Q: Can someone please explain the antenna and gang capacitor of this AM superheterodyne receiver? This is about an Elenco AM/FM superheterodyne radio receiver. I have noticed a similar post (Can somebody please explain the antenna and mixer stage of this AM superheterodyne receiver?), but still have some questions and hope if someone can help me understand some part of it.
(image from the same link.)
The right side of L4 is connected to the left square of the gang capacitor. This is the antenna.
The left side of L4 is the secondary coil of the antenna.
The right square of the gang capacitor tunes local oscillation. And the signal is sent to the emitter of Q7, which is an mixer.
My questions are:

*

*From most superhet circuits (eg. link below), the antenna coil is in a seperate circuit. Why is this antenna conected to the Vcc and to the secondary coil?
(superhet circuits:
https://circuitdigest.com/article/superheterodyne-am-receiver
https://www.nutsvolts.com/magazine/article/a_simple_superhet)

*The antenna coil seems to not be in parallel with tuning capacitors. How it is tuned here?

*Which part of the circuit generates local oscillation?
What does C28, C29 and C31 do?
thanks

A: This "little" circuit is deceptively complicated in its interactions. Inevitably there are repetitions in the explanations I offer here.

The right side of L4 is connected to the left square of the gang
capacitor. This is the antenna.

Strictly speaking, the ferrite rod inside L4 is the antenna.
If you think of L4 as a transformer then the primary "coil" is entirely notional, "inside" the ferrite rod (I'm stretching the analogy to breaking point here).
The flux changes in the ferrite are induced by the external RF.
Both the L4 coils on the schematic are secondaries.

The left side of L4 is the secondary coil of the antenna.

Both coils of L4 are secondaries, as above.

*

*Why is this antenna conected to the Vcc and to the secondary coil?

*The antenna coil seems to not be in parallel with tuning capacitors.

Vcc is the power supply which is low impedance (including RF) to ground. @autistic put this more succinctly. C28 is also low impedance to RF.
Thus L4 (right) and "square of the gang capacitor" (left) form a parallel tuned circuit.
Station tuning is done here and the tuned RF is fed to Q7 base from the low impedance L4 left coil. (Low impedance compared to the L4 right coil).

*Which part of the circuit generates local oscillation?

Q7 has dual function: LO and Mixer
(in the era of this fragment of schematic, transistors were expensive.
Often times they were given dual functions in order to get more "bang for buck", as the saying goes).
The LO parallel tuned circuit (a "tank") is made from "square of the gang capacitor" (right) via C30 to L5 primary (left) in a similar way to the main tuning.
The tank oscillation is maintained by Q7 collector AC.
Q7 collector and emitter voltages are antiphase, but their currents are in phase. A low impedance tap on L5 primary provides positive current feedback to Q7 emitter.
Summary for capacitors.
C28 will have a value that is too large to affect the MW tuning. However, it must be good quality (low parasitics) to remain low impedance at RF.
C29 blocks the DC base bias of Q7 from being shorted to ground through L4 left, but passes RF (value and quality as C28).
C31 blocks the DC emitter bias of Q7 from being shorted to ground through L5 primary (left), but passes RF (value and quality as C28).
Notes
T6 primary (left coil) is tuned to IF (Intermediate Frequency) typically 470kHz.
The tuning capacitor is not shown explicity but is integral to the transformer construction.
The missing capacitor and the flat right-hand side of Q7 are drawing artefacts, to save space on the schematic.


text:
Q: Definable non measurable set after adding one Cohen real to L Suppose $x$ is a Cohen real over the constructible universe $L$. Is there a (parameter free) definable non measurable set of reals in $L[x]$?
This appeared in Will Brian's answer here where he noted that the analogous question after adding a random real has a postive answer.

A: The paper "$\Delta^1_2$-sets of reals" by Ihoda (=Judah) and Shelah  [Annals of Pure and Applied Logic 42 (1989) 207-223] should have the result you want.
Theorem 3.1(i) tells you that every $\Delta^1_2(r_0)$ ($\Delta^1_2$ using only $r_0$ as a parameter) set is Lebesgue measurable if and only if there is a real $r$ that is random over $L[r_0]$.
In particular, all $\Delta^1_2$ (parameter free) sets of reals are measurable if and only if there is a random real over $L$.  This latter fails if we add a single Cohen real to $L$, so there is a non-measurable $\Delta^1_2$ (without parameters) set in $L[c]$ if $c$ is Cohen over $L$.
The paper addresses regularity properties of $\Delta^1_2$ sets in many different settings, and not just Lebesgue measurability.


text:
Q: What component actually dumps core? I am unsure whether this is the C library or some other stuff which dumps contents to core file and make a program Exit. What i mean here is that is the glibc or libc handles the SIGSEGV and creates the core dump in the handler function ? Please explain.

A: In linux, the kernel process execution and signal handling mechanisms are responsible.
http://lxr.linux.no/#linux+v2.6.32/fs/exec.c#L1752
void do_coredump(long signr, int exit_code, struct pt_regs *regs)
    {
    ...

http://lxr.linux.no/#linux+v2.6.32/kernel/signal.c#L1926
            if (sig_kernel_coredump(signr)) {
                    if (print_fatal_signals)
                            print_fatal_signal(regs, info->si_signo);
                    /*
                     * If it was able to dump core, this kills all
                     * other threads in the group and synchronizes with
                     * their demise.  If we lost the race with another
                     * thread getting here, it set group_exit_code
                     * first and our do_group_exit call below will use
                     * that value and ignore the one we pass it.
                     */
                    do_coredump(info->si_signo, info->si_signo, regs);

A: When there's no other handler, the kernel will generate the core file if ulimit -c is greater than 0 for the process.

A: The kernel is what creates the core dump, at least in Linux.
As Gonzalo points out, ulimit -c determines the maximum size of the core dump (with 0 disabling it completely and unlimited specifying no limit).  Depending on available disk space, you may want to set this to some value other than unlimited to prevent filling a disk, though you'll likely find it hard to use the truncated core file.
The name of the core file can be configured using /proc/sys/kernel/core_uses_pid and /proc/sys/kernel/core_pattern.
You can use kill -SEGV <pid> to make a process dump core.

A: I believe that it is handled by the kernel.  On Linux, I have not found a library or system call to create one manually, though.


text:
Q: The use of "High-order" vs "Higher-order" to describe the order of accuracy of numerical schemes I would like to know if there is a qualitative difference between the phrases "high-order" and "higher-order". I have recently received a response to an article I submitted in the field of numerical methods for curvature computation of liquid-gas interfaces. In the article, I develop an arbitrary-order polynomial fitting procedure to reconstruct the liquid-gas interface, after which the interface curvature is computed (for surface tension computation purposes). I titled the article "A Higher-order Accurate ..." because I manage to demonstrate that the "order of accuracy" of the procedure matches the order of the fitted polynomial.
One of the reviewers of the article strongly suggests replacing "higher-order" with "high-order". I partially understand this request as I have noticed a trend where a number of researchers in my field use the phrase "high-order" in similar contexts to mine (although most still use "higher-order"). However, I gravitate towards "higher-order" as it is widely used all over mathematics. Can anyone advise me on the differences (if any) between these two phrases, and which one I should adopt?

A: I have found it difficult to settle language issues without face to face communication, something which is not possible here. It may be possible to avoid the issue entirely and still attract the right audience. Consider the title "Methods of arbitrary order for approximating <something relevant>." In the abstract, write something along the lines of : "Given an positive integer $p$ we show how to generate approximations of order $p$ for <something relevant>".


text:
Q: Surfacing information from an AngularJS component The documentation says

Outputs are realized with & bindings, which function as callbacks to component events

The handler is defined in the controller of the feature that contains my component.
$scope.handleStatusChange = function (sc) {
  console.log(sc);
}

It is bound in markup to the component.
<search-context
  centre-code="4321"
  on-status-change="handleStatusChange">
</search-context>

When I invoke the handler in the code of my component the handler is called but the parameter is undefined. I have unsuccessfully tried expressing the parameter in various ways.
ctrl.onStatusChange(ctrl.status);
ctrl.onStatusChange({ value: ctrl.status });

How do I pass the parameter?
Is there a required signature for the handler?

A: This sample from the docs implies there's a matching convention between attribute names and parameter names.
function HeroDetailController() {
  var ctrl = this;

  ctrl.delete = function() {
    ctrl.onDelete({hero: ctrl.hero});
  };

  ctrl.update = function(prop, value) {
    ctrl.onUpdate({hero: ctrl.hero, prop: prop, value: value});
  };
}

<hero-detail ng-repeat="hero in $ctrl.list" hero="hero"
  on-delete="$ctrl.deleteHero(hero)"
  on-update="$ctrl.updateHero(hero, prop, value)"></hero-detail>

Rewrite so that the name in the markup binding matches the attribute name in the object passed when invoking the callback.
The handler implementation need not match, just the component code and markup.


text:
Q: Unexpected file transfer behaviour when building API using Express Here is how my API works:

You can find SeaweedFS here on GitHub.
And the code here:
// /drivers/seaweedfs.js Defines how API interacts with SeaweedFS
const { error } = require("console");
const http = require("http");
module.exports = class Weed {
  constructor(mserver) {
    this.mserver = new URL(mserver);
  }

  get(fileId) {
    return new Promise((resolve, reject) => {
      let options = {
        hostname: this.mserver.hostname,
        port: this.mserver.port,
        method: "GET",
        path: `/${fileId}`,
        timeout: 6000,
      };
      let data;
      const fileReq = http.request(options, (res) => {
        console.log(`Statuscode ${res.statusCode}`);
        res.on("data", (response) => {
          data += response;
        });
        res.on("end", () => {
          resolve(data);
        });
      });
      fileReq.on("error", () => {
        console.error(error);
        reject();
      });
      fileReq.end();
    });
  }
};

// /routes/file.js An Express router
const express = require("express");
const router = express.Router();
const Weed = require("../drivers/seaweedfs");
let weedClient = new Weed("http://localhost:60002");

router.get("/:fileId", (req, res) => {
    weedClient.get(req.params.fileId)
    .then(data=>{
        res.write(data)
        res.end()
    })
}
)

module.exports = router;

MongoDB driver not yet implemented.
When I try to GET a file(using Firefox, Hoppscotch says Could not send request: Unable to reach the API endpoint. Check your network connection and try again.), I get something whose MIME type is application/octet-stream for some reason. It's bigger than the original file. I know there must be some problems with my code, but I don't know where and how to fix it.


text:
Q: Destroy clones of Gameobject after collision in Unity I have made a 2D game unity, and I have "RockSpawner" gameobject which spawns rocks when game starts. If my player collides with any this rocks, I want to destroy rock clones (Spawned by RockSpawner) or set all rock clones made in game play mode to false.

A: Basically , if you look on the internet there are a lot of examples.
However , the best way is to use :
OnCollision2DEnter
From the example in the link given there is :
public class ExampleClass : MonoBehaviour {
    void OnCollisionEnter2D(Collision2D coll) {
        if (coll.gameObject.tag == "Enemy")
            coll.gameObject.SendMessage("ApplyDamage", 10);

    }
}

From here you can then use "Destroy" .


text:
Q: How to install Sxslt package on Windows? R In relation to this question, I need to install Sxslt package in R on a windows platform. I used RStudio to compile the package from the source, but it encountered an error. It returned a message about defining LIB_XSLT. Please see the log below:
> install.packages("Sxslt", repos = "http://www.omegahat.org/R", type="source")
Installing package(s) into 'local/R/win-library/2.15'
(as 'lib' is unspecified)
trying URL 'www.omegahat.org/R/src/contrib/Sxslt_0.91-1.tar.gz'
Content type 'application/x-gzip' length 112790 bytes (110 Kb)
opened URL
downloaded 110 Kb

* installing *source* package 'Sxslt' ...
Please define LIB_XSLT
ERROR: configuration failed for package 'Sxslt'
* removing 'local/R/win-library/2.15/Sxslt'
Warning in install.packages :
  running command 'local/bin/i386/R CMD INSTALL -l "local/R/win-library/2.15" local/downloaded_packages/Sxslt_0.91-1.tar.gz'
had status 1
Warning in install.packages :
  installation of package 'Sxslt' had non-zero exit status

The downloaded source packages are in
    'local\downloaded_packages'

Thanks.

A: Sxslt package which were provided by Omega Project is outdated now. It is better to use xslt package available at CRAN.
install.packages("xslt")


text:
Q: 1 output bindings in Spring Cloud Stream Kafka Binder in this page tells that you can't make just one Outputs
but I need to make just one Outputs by using Spring Cloud Stream Kafka Binder
what should I do?
some articles says that using org.springframework.cloud.stream.function.StreamBridge but it's not works for me
I made StreamBridge to send topics to Kafka but Kafka doesn't produce topics to my Spring boot application
and this is my application.yml and produce topic code
// producer Springboot application

  spring.cloud.stream:
    kafka:
        binder:
            brokers: {AWS.IP}:9092
            zkNodes: {AWS.IP}:2181
    bindings:
        deliveryIncoming:
            destination : deliveryIncomingtopic

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
  // wanna produce deliveryIncomingtopic and send to Spring's Consumer
}

// Consumer Springboot application

spring :
     cloud:
        stream:
            kafka:
                binder:
                    brokers: {AWS.IP}:9092
                    zkNodes: {AWS.IP}:2181
            function:
                definition : deliveryIncoming;

            bindings:
                deliveryIncoming-in-0:
                    destination : deliveryIncomingtopic

    @Bean
    public Consumer<KStream<String, String>> deliveryIncoming() {
        return input ->
                input.foreach((key, value) -> {
                    System.out.println("deliveryIncoming is playing");
                    System.out.println("Key: " + key + " Value: " + value);
                });
    }

EDIT
sorry I think I made kind of unclear
I just want to do like below
produce(deliveryIncomingtopic) -> Kafka -> consumer(deliveryIncomingtopic)

A: If that's the case, then you need to change your bean function definition to return java.util.Function instead of java.util.Consumer.
@Bean
public Function<KStream<String, String>, KStream<String, String>> deliveryIncoming() {
return input ->
                input.foreach((key, value) -> {
                    System.out.println("deliveryIncoming is playing");
                    System.out.println("Key: " + key + " Value: " + value);
                });
}

However, AFAIK.. you still need to define the output channel in your application.yml. You can use the same name with different suffix. Something like below :
deliveryIncoming-in-0:
   destination: <your_topic_name>
deliveryIncoming-out-0:
   destination: <your_topic_name>

A: Just want to make things clear here. Are you looking to consume a message from your inbound topic deliveryIncomingtopic and then generate/produce another message to another output topic ?
If that's your question about, then I believe you were missing something there within your application.yml.
You need to have another configuration for your output topic. e.g. :
Since you're using Spring Cloud Function (based on what i see in your application.yml), then you should add more configuration for your output topic as follow:
spring :
     cloud:
        stream:
            kafka:
                binder:
                    brokers: {AWS.IP}:9092
                    zkNodes: {AWS.IP}:2181
            function:
                definition: deliveryIncoming;deliveryOutput

            bindings:
                deliveryIncoming-in-0:
                    destination: deliveryIncomingtopic
                deliveryOutput-out-0:
                    destination: deliveryOutput

And also define another bean for your producer function :
@Bean
public Producer<KStream<String, String>> deliveryOutput() {
   // do your necessary logic here to outbound your message
}

Hope this will match your expectation.


text:
Q: Начиная с какой минимальной версии Android можно загружать приложения в google play market? Недавно слышал, что для того, чтобы загрузить приложение в google play market, минимальная версия для него должна быть не ниже android 8.0. Это так или нет?
И если нет, то начиная с какой версии можно его загружать приложения?

A: Минимальную поддерживаемую версию (minSdkVersion) можно ставить любую, но ниже 16 sdk просто нет смысла. Ограничения вводятся на targetSdkVersion. Сейчас нельзя опубликовать или обновить приложение с target sdk ниже 26 (android 8.0), с первого ноября 2019г. под запрет попадут версии ниже 28 (android 9.0).
Это связано с безопасностью. Например после добавления runtime permissions в 23 sdk, долгое время можно было публиковать приложения таргетированные под старые версии, не заморачиваясь с новым api, они получали все разрешения при установке на девайс, по старинке.

A: Минимальная версия (minSdkVersion) может быть любой, а вот целевая (targetSdkVersion):
Android 8.0 (API уровня 26)

*

*С 1 августа 2018 года требуется для новых приложений.

*С 1 ноября 2018 года требуется для обновлений приложений.

Android 9 (API уровня 28)

*

*С 1 августа 2019 года будет требоваться для новых приложений.

*С 1 ноября 2019 года будет требоваться для обновлений приложений.

Android 10 (API уровня 29)*

*

*С 3 августа 2020 года потребуется для новых приложений.

*Со 2 ноября 2020 года потребуется для обновлений приложений.

*Требование об API уровня 29 не относится к приложениям для Wear OS.
Как только эти требования вступят в силу, в Play Console нельзя будет загрузить новые APK-файлы с более ранними целевыми уровнями API.
https://support.google.com/googleplay/android-developer/answer/113469#targetsdk

A: В принципе, можно использовать любую версию targetSdkVersion, в том числе несуществующую: внутри манифеста (уже скомпилированного приложения) можно просто запатчить это значение. И вы знаете, это вполне работает!
Если попробовать декомпилировать такое приложение, то видно внутри следующее:
<manifest versionCode="1" versionName="1.0" compileSdkVersion="28" compileSdkVersionCodename="9" package="******" platformBuildVersionCode="28" platformBuildVersionName="9">

    <uses-sdk minSdkVersion="3" targetSdkVersion="85">

Как вы видите, я являюсь элитарным ведроразработчиком, так как могу компилять свои приложения с 85-й версией SDK!
Чего я не ожидал, так это то, что в файл добавляются поля о реальной версии SDK: compileSdkVersion="28" compileSdkVersionCodename="9"  platformBuildVersionCode="28" platformBuildVersionName="9" - в оригинальном файле, который проходит компиляцию, этих полей НЕТУ, потому немного палевно.
Готовых тулзов для такого извращения не знаю, но если надо быстро сделать "обновление", а исходники не собираются, то вполне можно заморочиться с хекс-редактором. Конечно, можно запатчить еще и minSdkVersion, но надо понимать, что если рантайм наткнется на вызов, которого не понимает, то будет все плохо. Еще надо помнить, что после патча, система начинает думать, что вы реально смогли такое скомпилять и может применять повышенные требования безопасности, так что выдать все пермишшены таким образом не выйдет. А вот завышать версию targetSdkVersion можно до небес.


text:
Q: What is the reason and the meaning to use static non-member functions in C++? I would like to know what is the meaning of using static non-member functions in C++
and also why one would use those instead of non static ones.
For reference I am reading this question and this question in other site and in there it says

It means that you can't call it from another cpp file

In my situation I have a .h file and a "main" cpp file.
I have implemented a function in the h file both as a static and non-static non-member one and I can call it from the cpp file and the results don't vary
So I am wondering why and what is the difference or effect of static
Note: Please, this question does not involves static in:

*

*C

*member functions

*variables

A: The differences will be seen when linking the whole program and when the functions are called from multiple places.
In case of both foo.cpp and bar.cpp including implementation.h, with static int baz() { return 0; }, the method baz will live independently in the compilation units of foo.cpp and bar.cpp.
When the method is non-static (and non-inline) the method baz is considered to be linkable by all compilation units, which know the prototype. In this case compiling gcc foo.cpp bar.cpp will result in linking error of multiple references for baz.

A: In most C++ implementations, each .cpp file is compiled into a corresponding .o file.  The .o file contains the object code for the functions of the .cpp file -- i.e. the machine-code instructions the CPU will need to execute in order to execute those functions.
For non-static functions, the .o file also contains linker-readable metadata; i.e. a list of (mangled) function names that are present in the .o file, where those functions are located within the file, etc.  At link-time, the linker will use this metadata to resolve calls to these functions that were made from within other .cpp files.
For static functions, OTOH, the .o file does not contain any metadata; as far as the linker is concerned, the static functions do not exist.  The static functions are effectively "secret", available only to the other code from the same .cpp file (which does not depend on the linker to gain access to the static functions as it is compiled as part of the same compilation-unit and can therefore just reference them directly)
In your case you implemented your static function in a .h file, which means that a separate copy of the function is being included in the .o file of every .cpp file that uses that function, which is why it still "works" for you.
People often use static as a sort of private-namespace marker to guarantee that functions won't be called from outside of the .cpp file they appear in.  In C++, an anonymous namespace can be used to achieve a similar result.

A: As other people explained, in C++ if your code consist of multiple files, so all the global functions and variables are having external linking by default. For example a function defined in a file A.cpp can be called in file B.cpp by automatic linking by compiler. Remember you have to compile both files separately, and later you will tell the compiler to link these objects .o files. Compiler will stitch everything together. As I did in the Makefile below.
But if you want to disable external linking you will make your function static so now your function or variable is just available for the file in which it is declared. This is called internal linking.
Internal linking is used where you have to have global variables, but you do not want that your global variable accessed outside of this file, and some other file modify it accidentally.
For better understanding how does this work play around with this code:
first.cpp
#include <iostream>
/*static*/ void hello(){ //static will not let this code compile
    std::cout << "Hello I am external linking" << std::endl;
}

main.cpp
void hello();
int main(){
    hello();
}

Makefile
program: first.o main.o
    g++ main.o first.o -o test

main.o: main.cpp
    g++ -g -c main.cpp -o main.o

first.o: first.cpp
    g++ -g -c first.cpp -o first.o

This works as you expected. But if you put static in the start of hello() in first.cpp, this will become internal linking so you will get linking error by the compiler.


text:
Q: Lubuntu minimize all show desktop keyboard shortcut? Is there a show desktop (also known as minimize all) keyboard command in Lubuntu? I looked around in lubuntu-rc.xml, but I didn't have any luck.
If there is one, and it's a Super key, then is there a way to change it? I'm using a Model M keyboard, which is pre-Super key.

A: In 13.04, "show desktop (also known as minimize all)" is found in ~/.config/openbox/lubuntu-rc.xml:
<keybind key="W-d">
  <action name="ToggleShowDesktop"/>
</keybind>

Try changing W-d to some other combination.  Only you know which combinations are free on your system.
W = window/super
C = control
S = shift
A = alt


text:
Q: Explanation of tac --before
-b, --before
The separator is attached to the beginning of the record that it
  precedes in the file.

And I can't understand the following output:
$ echo -e "Hello\nNew\nWorld\n!" > file
$ tac file
!
World
New
Hello
$ tac -b file

!
World
NewHello

Why there is no newline between New and Hello?

A: That does look strange partly due tac works in somewhat counter-intuitive way as to me. Let's make use of clearly visible separators — commas.
What would I expect to see as the result of the following command:
% echo -ne 'A,B,C' | tac -s,

?
Well, I see it as there's A separated from B separated from C. Thus (I conclude) being printed in reverse, they should constitute C,B,A. Let's check. Alas, it prints differently instead:
% echo -ne 'A,B,C' | tac -s,
CB,A,

We can conclude tac sticks for original separators placement: A still has it afterwards, as well as B does, but C didn't have it and hence it's printed as is.
What happens if I run tac with -b this time?
% echo -ne 'A,B,C' | tac -bs,
,C,BA

Seemingly it works this way for -b: it's going through the input in backward direction till it finds a separator. As it's found it's printed:
,. Then it prints the text it skipped while searching:
C. Then the cycle repeats:
,B. As there're no separators left, just the remainder is printed:
A.

Why there is no newline between New and Hello?

According to the explanation I've given above New would be on a new line because it was prefixed with new-line, but since Hello wasn't — it'd be printed as is.

A: tac works with records and their separators, attached, by default after the corresponding record. This is somewhat counter-intuitive compared to other record-based tools (such as AWK) where separators are detached.
With -b, the records, with their newline attached, are as follows (in original order):

*

*Hello

*\nNew

*\nWorld

*\n!

*\n
Output in reverse, this becomes
\n\n!\nWorld\nNewHello

which corresponds to the output you see.
Without -b, the records, with their newline attached, are as follows:

*

*Hello\n

*New\n

*World\n

*!\n
Output in reverse, this becomes
!\nWorld\nNew\nHello\n


text:
Q: Background Firebase Push Notifications in Cordova I am using a phonegap-plugin-push for receiving notifications in Cordova Application. I am deploying on android Marsh-mellow for testing.
I want to see and store the contents of the Notifications received through Firebase Console when the app is in background.
Here is my Code -
    document.addEventListener("deviceready",onDeviceReady,false);
    function onDeviceReady(){

       var push = PushNotification.init({ "android": {"senderID": "91254247XXXX"}});

       push.on('registration', function(data) {
           console.log(data.registrationId);
           //document.getElementById("gcm_id").innerHTML = data.registrationId;
       });

       push.on('notification', function(data) {

           alert("On Notification function!!");
             // data.message,
            // data.title,
            // data.count,
            // data.sound,
            // data.image,
            // data.additionalData
            console.log("notification event");
            console.log(JSON.stringify(data));
            alert(JSON.stringify(data));
           //Do something
       });

       push.on('error', function(e) {
           alert(e);
       });
    }

When the app is in foreground (on screen) I receive the contents (title, message, data, etc.) properly and I am able to see them in alert box directly in the app.
But when app is in background (not on screen but running in backround), I get the notification in Notification Area. When I click on the notification received, it is redirecting me to the last opened page in the app.
The function push.on('notification', function(data) {} is not called. No alert messages are shown. Can someone help me how to access the notification message and data?

A: I found the answer after 2 days of research. We have to set "content-available" to 1 in the data field. Else it wont call on notification block if app is in background.
And this is not possible as of now through Google Firebase Console.
We have to send our custom payload messages (data or notification or both) seperately using any one of the firebase servers.
Detailed info can be found on the plugin's GitHub Page on background notifications.
I used NodeJs firebase-admin. I followed these setup guidelines and these steps for sending messages and it worked for me.
Here is my working code (NodeJS) -
var admin = require("firebase-admin");

var serviceAccount = require("pushnotificationapp-xxxxx.json"); //this is the service account details generated from server

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://pushnotificationappxxxxx.firebaseio.com/" //your database URL here.
});

var registrationToken = "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX....."; //registration token of the device
var payload ={
    "data": {
        "title": 'Test Push',
        "message": 'Push number 1',
        "info": 'super secret info',
        "content-available": '1' //FOR CALLING ON NOTIFACATION FUNCTION EVEN IF THE APP IS IN BACKGROUND
    }
};

//send the notification or message
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
    console.log("Successfully sent message:", response);
})
.catch(function(error) {
    console.log("Error sending message:", error);
});

UPDATE :
I implemented the same using php server too.
Here is my working php code for sending notifications using HTTP POST to FCM server-
<?php

$url = 'https://fcm.googleapis.com/fcm/send';

$data =
    array(
          "to" => "eYjYT0_r8Hg:APA91bG0BqWbT7XXXXX.....",
          "data" => array(
                "title"=> 'Test Push',
                "message"=> 'Push number 1',
                "info"=> 'super secret info',
                "content-available"=> '1')

   );

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => array("Content-Type:application/json",
        "Authorization:key=AAAA1HfFM64:APA91XXXX...."), //this is the server authorization key from project settings tab in your Firebase Project
        'method'  => 'POST',
        'content' => json_encode($data)
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

if ($result === FALSE) { echo "Caught an error"; }
else{
    echo $result;
}
?>

A: i was going through the same issue but i added "content-available": '1' also but my phone was not receiving any background push.
Finally i found that it was issue with my phone as mentioned here: https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/PAYLOAD.md#huawei-and-xiaomi-phones
Huawei and Xiaomi Phones
These phones have a particular quirk that when the app is force closed that you will no longer be able to receive notifications until the app is restarted. In order for you to receive background notifications:
On your Huawei device go to Settings > Protected apps > check "My App" where.
On your Xiaomi make sure your phone has the "Auto-start" property enabled for your app.
On your Asus make sure your phone has the "Auto-start" property enabled for your app.
Hope it will help someone.


text:
Q: NSFetchedResultsController is driving me crazy i've been building an app since 1 month using NSFetchedResultsController and i was testing the app on the 3.1.2 SDK. The poblem is that i've been using NSFetchedResultsController everywhere in my app and was working on the 3.1.2 version of the SDK, now my client say that i should make it compatible with the 3.0 version and the deadline is almost there.
But is crashing everytime i change an object handled by the contoller, the application is crashing with very weird errors.
The problem occure when removing the last object in a section and when a change make an object love to another section.
I've been using a sample code from "More iPhone 3 Development Tackling iPhone SDK 3" by Dave Mark and Jeff LaMarche. I've also included some changes from link text
Here is a sample output of the console when the application is crashing.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections.  The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (2), plus or minus the number of sections inserted or deleted (2 inserted, 0 deleted).'
2010-03-14 16:23:29.758 Instaproofs[5879:207] Stack: (
    807902715,
    7364425,
    807986683,
    811271572,
    815059090,
    815007323,
    211023,
    4363331,
    810589786,
    807635429,
    810579728,
    3620573,
    3620227,
    3614682,
    3609719,
    27337,
    810595174,
    807686849,
    807683624,
    839142449,
    839142646,
    814752238
)
If i knew that NSFetchedResultsController is so buggy, i would never used it.
So basicaly i need the my NSFetchedResultsControllerDelegate to work fine on the 3.0 and above SDKs.
It would be life saver if someone help me figure out what i'm doing wrong.

A: It appears from your error messages that you are inserting sections into the table when you should be deleting them.  Your tableView dataSource is only supplying one section after the updates even though you have told the tableView to expect a total of four sections.
I don't think this is a case of NSFetchedResultsController being buggy, but rather that it is tricky to implement outside of simple use cases.  Your crashes are almost certainly occurring as a result of your controller:didChangeObject:atIndexPath:forChangeType:newIndexPath delegate method.  The key to successfully implementing this method (at least in my experience) is to keep in mind that the changeTypes are both object and indexPath driven.  This makes "updates" and "moves" tricky conceptually.
Consider the situation where a managed object is changed such that it sorts under a new sectionNameKeyPath.  Conceptually, we think of the object as having "moved" to a new section since the fetchedResultsController now sorts it under a new heading in the tableView.  If the object's indexPath does not change, however, the fetchedResultsController considers this an "update" and not a "move".
What's worse is that even though the managed object that changed still retains the same indexPath, other objects in the fetchedResultsController may now have new indexPaths because they were bumped around by the change.  This means that you will have to manually handle section insertions and section deletions in the "update" section of your delegate method.  Similar problems will need to be addressed in the "move" section of your delegate method.
Without trying to explain it in so many words, LaMarche's fix is attempting to address this problem in a generic way that accommodates as many use cases as possible.  By trying to understand the problem as it pertains to your use case, you may be able to significantly reduce the complexity of the code that LaMarche uses.  Focus specifically on the "update" and "move" sections of your delegate method, as these are the most likely culprits for your problem.

A: Check out this resource:
http://iphonedevelopment.blogspot.com/2009/11/i-know-youre-tired-of-hearing-about.html
Helped me tremendously.


text:
Q: Overwrite web.config setting Environment: IIS 7, .Net 4.0
In web.config of our application, it has this section:
<system.webServer>
  <httpProtocol>
   <customHeaders>
     <add name="cache-control" value="no-cache" />
   </customHeaders>
  </httpProtocol>
</system.webServer>

Most of our application requires no-cache, but there is only one page that requires cache-control to be Private. Is a way to do it?
Appreciated for any input

A: You cannot apply or override settings from web.config to a particular page, however you can do this for all pages inside a folder, by following settings.
<system.webServer>
  <httpProtocol>
   <customHeaders>
     <remove name="cache-control" />
     <add name="cache-control" value="no-cache" />
   </customHeaders>
  </httpProtocol>
</system.webServer>

However, you can override the cache-control settings in Page_Load event of a particular page.
Response.CacheControl = "Private";

A: You can also change response caching for a page by setting the location attribute of @outputcache directive.
<%@ OutputCache Location="Server" %>


text:
Q: JavaScript Code Explanation I use a script called "imageLightbox" and in this Script is a line:
var description = $( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' ).attr( 'alt' );

Can anybody tell me what's happened there?

A: Assuming #imagelightbox is the id of an image:
$( '#imagelightbox' ).attr( 'src' ) returns the src (source) of an image, say "bla/foo.jpg".
The second bit of code the uses the src as part of its selector, so
$( 'a[href="' + $( '#imagelightbox' ).attr( 'src' ) + '"] img' )

effectively would become
$( 'a[href="bla/foo.jpg"] img' )

which finds an a tag with an href of bla/foo.jpg and gets the img element within it.
Finally the .attr( 'alt' ); on the end, grabs the alt tag text from that element, which is returned and set in to the description variable.

A: It gets the alt attribute of an img which is contained within an anchor with the same href as the src of #imagelightbox.
Broken down a bit:
// get the src attribute of the #imagelightbox element
var imagelightSrc = $( '#imagelightbox' ).attr( 'src' );

// get an img contained in a anchor with an href equal to imagelightSrc
var img = $( 'a[href="' + imagelightSrc + '"] img' );

// get the alt attribute of that image
var description = img.attr( 'alt' );

Useful links:
Attribute Selector
attr documentation

A: Broken into pieces
// get imageLightbox
var $imageLightbox =   $( '#imagelightbox' );

// get src of imageLightbox
var srcOfimageLightbox = $imageLightbox.attr( 'src' )

// find corresponding anchor
var $correspondingAnchor = $( 'a[href="' + srcOfimageLightbox + '"]')

// find correspponding image
var $correspondingImage = $correspondingAnchor.find('img')

// get alt attribute of correspponding image
var altOfcorrespondingImage = $altOfcorrespondingImage.attr( 'alt' )

// the description is taken from the alt attribute of the corresponding image
var description = altOfcorrespondingImage

A: it is looking for an img node, which could be in all descent child nodes of an a node like:
$( 'a img' )

but not in any kind of a node, only those with a specfic href attribute:
$( 'a[href=...] img' )

that attribute is the value of src attribute of a node name with imagelightbox as its id:
var src = $( '#imagelightbox' ).attr( 'src' );
$( 'a[href="' + src + '"] img' )

which is probably another img node because of src node.
at the end when it finds the image it gets it alt attribute.
var src = $( '#imagelightbox' ).attr( 'src' );
var altValue = $( 'a[href="' + src + '"] img' ).attr( 'alt' );


text:
Q: WPF Unable to refresh usercontrol from main window using MVVM
This is my model

public class PersonModel : INotifyPropertyChanged
{
    private string _firstname;
    public string FirstName
    {
        get {return _firstname; }
        set { _firstname = value; RaisePropertyChanged("FirstName"); }
    }

    private string _lastname;
    public string LastName
    {
        get { return _lastname; }
        set { _lastname = value; RaisePropertyChanged("LastName"); }
    }

    public string FullName
    {
        get { return string.Format("{0} {1}", FirstName, LastName); }
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

I have a view basically a user control

<UserControl x:Class="WpfApplication1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfApplication1"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300"
         Visibility="{Binding HideStatus, Mode=TwoWay}">
<UserControl.DataContext>
    <local:PersonViewModel></local:PersonViewModel>
</UserControl.DataContext>
     <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="117*"></RowDefinition>
        <RowDefinition Height="33*"></RowDefinition>
        <RowDefinition Height="75*"></RowDefinition>
        <RowDefinition Height="75*"></RowDefinition>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Text="FirstName"></TextBlock>
    <TextBox Text="{Binding FirstName,Mode=TwoWay}" Name="txtFirstName" Margin="115,0,0,67" DataContext="{Binding Path=Person}" Background="#FFF0F0F0" />
    <TextBlock Text="FirstName" Margin="0,71,0,0" Grid.RowSpan="2"></TextBlock>
    <TextBox Text="{Binding LastName,Mode=TwoWay}" Name="txtLastName" Margin="115,90,0,12" Background="#FFF0F0F0" DataContext="{Binding Path=Person}" Grid.RowSpan="2" />
    <Button Grid.Row="3" Content="Button" Height="29" HorizontalAlignment="Left" Margin="12,23,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding UpdateView}" />
</Grid>

In Main window which has one button "Update From Main UI" and the usercontrol which we have created already

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="MainWindow" Height="350" Width="525"

    xmlns:model="clr-namespace:WpfApplication1"
    >
<Grid>
    <Grid.DataContext>
        <local:PersonViewModel/>
    </Grid.DataContext>
    <local:UserControl1 x:Name="control1" />
    <Button Content="Update From Main UI" Height="23" Command="{Binding UpdateView}" HorizontalAlignment="Left" Margin="358,276,0,0" Name="button1" VerticalAlignment="Top" Width="145" />
</Grid>

The problem is if i click on the button inside the usercontrol its refreshing the changes, but the same thing is not happening when i tried to click the button from main window. What is the problem?

A: The DataContext of your main Window is another class instance of PersonViewModel than the DataContext of your UserControl. Therefore, executing UpdateView from the main window does not update your UserControl.
You should write this in your main window:
<Button Command="{Binding Path=DataContext.UpdateView, ElementName=control1}" ... />

Via ElementName, you tell the Binding to refer to the user control. Via DataContext.UpdateView, you are refering to the user control's UpdateView command.


text:
Q: Install Centrify 5.8.0 package for AIX I am not able to find the CentrifyDC package for AIX to install.
Can someone help me to find it ?
Required version - 5.8.0
I tried to find it all over but couldn't find the related one.


text:
Q: C++11 constexpr to obsolete template meta-programming? As I understand it, constexpr is not Turing complete unlike template metaprogramming, so I believe these are not the same. So the question is to what extent does constexpr make template metaprogramming obsolete?

A: constexpr is absolutely Turing-complete. Recursion is allowed. It a convenient way to define functions that work at compile time as well as runtime. constexpr functions, being mere functions, cannot perform operations on types, though. (Unless you use template metaprogramming to define said function, of course.)
Both class templates and constexpr can be used to contain compile-time constant expressions, but there the similarity ends. They are not redundant and TMP won't be going away anytime soon.
Some particularly ugly compile-time calculations might be more elegantly rewritten as proper functions, though.


text:
Q: How are UTF strings literals interpreted in C? Say, I want to interpret(i.e. through stdout) a UTF32-encoded string: zß水, taking the examples found on cppreference.
With U prefix, it's straightforward:
printf("%ls",U"zß水")

However, it won't work unless an appropriate "locale" being set before print:
setlocale(LC_ALL, "XXX.UTF-8")

My simplified question is that, why should we use XXX.UTF-8 locale settings, instead of some others like XXX.UTF-32?

My confusion arises when I was testing the code below:
#include <stdio.h>
#include <locale.h>
#include <wchar.h>
#include <uchar.h>

void test2() {
    char32_t w_str[] = U"zß水";

    printf("wchar width: %d\n", __WCHAR_WIDTH__);
    if(__STDC_UTF_32__) printf("confirmed: utf32 used.\n");

    printf("(with '   C' locale) wide string is interpreted as: ");
    /* set locale */ if (setlocale(LC_ALL, "C") == NULL) perror("setlocale");
    if (printf("[%ls]", w_str) == -1) { perror("            ERROR('C' locale)"); clearerr(stdout); }
    printf("\n");

    printf("(with 'utf8' locale) wide string is interpreted as: ");
    /* set locale */ if (setlocale(LC_ALL, "en_US.UTF-8") == NULL) perror("setlocale");
    if (printf("[%ls]", w_str) == -1) { perror("            ERROR('utf8' locale)"); clearerr(stdout); }
    printf("\n");
}

int main(){test2();}

Along with output:
# gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)

wchar width: 32
confirmed: utf32 used.
            ERROR('C' locale): Invalid or incomplete multibyte or wide character
(with '   C' locale) wide string is interpreted as: [
(with 'utf8' locale) wide string is interpreted as: [zß水]

According to C11-6.4.4.4-9:

Prefix  : Corresponding Type
U : char32_t

and C11-6.10.8.2-1:

_ _ STDC_UTF_32 _ _ The integer constant 1, intended to indicate that values of type
char32_t are UTF−32 encoded.

My complete question is that, I've already specified an exact UTF32 string literal (and I'm 100% certain that they are exactly UTF32 encoded, by checking the assembly output of the code listed above), isn't it more appropriate to use some locale settings like XXX.UTF-32? If not, then why XXX.UTF-8 is qualified to decode the UTF32 byte sequence?


text:
Q: Background-size: cover effect in HTML email I'm working on a newsletter for my photo community website. In the newsletter, I want to have a grid of images. Here's an unfinished rendering in an email client. As you can see it has problems, this is only to illustrate what I'm trying to build.

The image files in reality are about twice the resolution as shown in the email. Furthermore, they can be in any aspect ratio and orientation. What I would like to achieve:

*

*Force all images into 200 x 200px cells

*Do not distort the image, the aspect ratio must be maintained

*The cell must always be filled, both horizontally and vertically

*Background sizing should be centered

*Elements must be clickable, leading to that particular photo

*Should be robust and work in most popular email clients

In normal web technology (as opposed to HTML in email), this would be a matter of setting the image container to the fixed dimensions and using background-size: cover. I've learned about many HTML email limitations yet am trying to persist in finding one way or another.
Am I really on an impossible mission here?
What I've tried so far:

*

*Setting the image as a background on the a that wraps around the img tag. With some tweaks it can come to a reasonable result, yet centering is a problem and outlook.com does not show the images at all.

*Using normal img tags with "a" around it and trying to control max width and height on the image and its wrapper. Here too centering is the main problem

I really hope this can be done, one way or another (not that server-side resizing is not an option in my case).

A: Since this is on an email client, you can't use any scripting language. This mean that manipulating the image is impossible on the client side of thing.
You will have to manually create thumbnails for your pictures or make some code that creates thumbnail server side before creating the email.
This is as much as I can tell you without knowing how you are creating your emails.


text:
Q: Dynamic Field names and Setting an autofill ID possible I currently have a form for naming alt text on uploaded images, this number is unlimited so fields are named alt-1 TO alt-XXXXXXX pulling in the ID if the image from the database.
I used to upload one image at a time and add the alt text, this would allow browser autofill to key on the field name "alt".  Of course the fields names are all different now making autofill not work.  I trield setting autofill="altext" in the input but that did not work, also tried setting all the fields with the same ID..
My only thought is to possible try to use my dynamic value for the ID, then use javascript on submit to rename the field names the the dynamic value but I hope there is a more sound solution.

A: For those who search for this insane "feature here is a shor script that I call on the form line with onsubmit = "replaceAlt()"
I named the ID in the Input fields what I want the names to be, then used "alt" for all the input fields that I want to be altered.
<script>
function replaceAlt() {
var x = document.getElementsByTagName("input");
var arrayOfInputNames = [];

  for (var i = 0; i < x.length; i++) {
    var n = x[i].name;
    if (n == "alt"){
      x[i].name = x[i].id;
    }
  }
}
</script>


text:
Q: Tag friend as "with—" on Facebook post I forgot to tag a friend as "with—" on a two-photos post. The post got likes and comments so I cannot delete/repost. I tagged the friend on the single photos, but on my wall it has not the "with <friend name>" caption.
If I GET /v2.1/<post-id>/tags:
GET /v2.1/<post-id>/tags
{
  "data": [
  ]
}

where on another post with tagged friends I get:
{
  "data": [
    {
      "id": "<friend-id>",
      "name": "<friend-name>"
    },
    {
      "id": "<friend-id>",
      "name": "<friend-name>"
    },
    …
}

Can I tag my friend via Graph API?


text:
Q: noobie array question i have a 2 data classes
first:
public class Question {

    public CharSequence question;
    public Answer answers[];

}

second:
public class Answer {

    public CharSequence text;
    public int number;
}

now i want to save an Answer to Question:
Question qstn.answers = new Answer[2];

[...]

But i got an NullPointerException. Whats wrong? Can't I change the length of an Array in an other class?

A:
Can't I change the length of an Array
  in an other class?

That is not the problem.
The problem is that you haven't initialized qstn yet.
What you should be doing is:
Question qstn = new Question();
qstn.answers = new Answer[2];

A: Have you created a new instance of Question first e.g.
Question qstn = new Question();
qstn.answers = new Answer[2];

Also unless you're optimising judiciously, then you'd probably want to give encapsulation a go and make the instance variables private.  Access through a public API e.g. getters or/and setters.
Also you may want to instantiate answers when the Object is created e.g.
public class Question {

    public CharSequence question;
    public Answer answers[] = new Answer[2];

}

Or you could do this in the constructor of Question (you'd need to add a Constructor, as the compiler will be generating you a non-arg Constructor by default with the way things stand).

A: You need to instantiate your Question class, first:
Question qstn = new Question();

A: Try this:
Question qstn = new Question();

qstn.answers = new Answer[2];

A: Your trying to access the array incorrectly.
 Question qstn = new Question();
 qstn.answers = new Answer[2];

A: Yes. You can change the length of arrays in another class.
Please check whether you have initialized the variable qstn.
Question qstn = new Question();