Q: PowerShell sends empty JSON payload I am calling GraphAPI to update keycredentials for a service principal. I create the JSON payload through combining data from a GET call and a custom JSON object.
I have a variable that is not empty, but when I make an API call I get an "empty payload" error. Why is my $body variable considered empty when it clearly isn't?
Below is the information on how I populate this variable.
Information
Here is the script:
. .\GetSecretToken.ps1
. .\pull_cert_data.ps1

$response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/{id}"  -Method Get -Headers $Header

$current_keys = $response.keycredentials

$key_credentials = $current_keys + $new_KeyCredentials

$key_credentials | ConvertTo-Json | Out-File .\checkkeys.txt

$hash_body =
    @{"keyCredentials" = $key_credentials
    "passwordCredentials" = $password_credentials}

$body = $hash_body | ConvertTo-Json -Depth 5
$body | out-file .\checkvalue.txt
$body

$json = $body

$update_cert = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/servicePrincipals/{id}" -Method Patch -Headers $Header -Body $json

If I use the $body variable in the $update_cert call, I get an empty payload error:
    {"error":{"code":"BadRequest","message":"Empty Payload. JSON content | expected."

However, if I use the $json variable, which just equals the $body variable, my call is successful. It will also print the contents of the $body variable in the terminal, so I know it isn't empty. The script creates two files that were originally done to make sure the JSON formatting was correct.
Here is the output of the $body variable:
{
  "keyCredentials": [
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Verify"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Sign"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Verify"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "displayName": "<CN>",
      "endDateTime": "<EXPIRY_DATE>",
      "key": null <EXISTING_CERT>,
      "keyId": "<GUID>",
      "startDateTime": "<START_DATE>",
      "type": "AsymmetricX509Cert",
      "usage": "Sign"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "endDateTime": "<EXPIRY_DATE>",
      "type": "X509CertandPassword",
      "key": "<NEWCERT-PrivateKey>",
      "displayName": "<CN>",
      "startDateTime": "<START_DATE>",
      "keyId": "<GUID>",
      "usage": "Sign"
    },
    {
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT>",
      "endDateTime": "<EXPIRY_DATE>",
      "type": "AsymmetricX509Cert",
      "key": "<NEWCERT-PublicKey>",
      "displayName": "<CN>",
      "startDateTime": "<START_DATE>",
      "keyId": "<GUID>",
      "usage": "Verify"
    }
  ],
  "passwordCredentials": [
    {
      "endDateTime": "<EXPIRY_DATE>",
      "secretText": "<PASSPHRASE_FOR_NEW_CERT>",
      "startDateTime": "<START_DATE>",
      "keyId": "<KEY_ID_OF_PRIVATE_KEY>",
      "customKeyIdentifier": "<HASH_OF_THUMBPRINT_OF_NEW_CERT>"
    }
  ]
}

Note: The $new_keyCredentials and $password_credentials variables are arrays that contain the hashtables of the new keycredentials and password credentials of those keys and are imported from the pull_cert_date.ps1 script.  The $Header is coming from GetSecretToken.ps1 script.

A:
PowerShell sends empty JSON payload

This error states that the PowerShell that the command is wanting the Json and the input provided is empty.
I have reproduced your requirement in my environment, and I have faced similar issue as you.
So, when I displayed the body i got the below as output:

And if I send this as the Json in invoke command, I get similar error as you got.
Then I used ConvertTo-Json and I got expected results as below:

Here what I observed is when I converted \n are added and it worked as expected.
References:

*

*"Empty Payload. JSON content expected" when uploading an item to OneDrive from a URL · Issue #745 · OneDrive/onedrive-api-docs · GitHub


Q: combining jackson objectmapper and stream parsing I have an android application, where parsing a json block takes around 250ms. It contains an array, and I only really need the first 6-7 values available immediatly. And I really need to speed up getting to those pieces of the data.
I have a data structure that essentially looks like:
class Data {
    List<Map> data = objectmapper_readvalue_data;

    public HashMap getItem(int i) {
        return data.get(i);
    }
}

I was really hoping to do something like this with a JsonParser:
    class Data {
        List data = new List();
        JsonParser p;
    public HashMap getItem(int i) {
        while (data.length < i) {
            data.append(p.parseOneBlockOfData());
        }
        return data.get(i);
    }
}

And only the first 5-6 values will be parsed at the first render, the others I can deal with later. However, I'm missing the "parseOneBlockOfData" function. Of course I can use a StringBuilder to buffer every value in the parse until I find the next entire block, then use a objectParser or that, but I'm not sure what the performance will be like.
Are there any non hackish ways of doing this?

A: incase anyone googles this:
JsonParser parser = objectMapper.getFactory().createJsonParser(inputStream);

// Keep going until we find filters:
String fieldName = null;
JsonToken token = null;
while (!"filters".equals(fieldName)) {
    token = parser.nextToken();
    while (token != JsonToken.START_ARRAY) {
        token = parser.nextToken();
    }
    fieldName = parser.getCurrentName();
}
// We're at the filters node

while (parser.nextToken() == JsonToken.START_OBJECT) {
    Map x = objectMapper.readValue(parser, Map.class);
}


Q: How to Get file from google drive I want to get file from drive use this code but not working.Some code given below -
public class PinFileActivity extends BaseDemoActivity {

        private static final int REQUEST_CODE_OPENER = NEXT_AVAILABLE_REQUEST_CODE;

        private static final String TAG = "PinFileActivity";

        private DriveId mFileId;

        /**
         * Starts a file opener intent to pick a file.
         */
        @Override
        public void onConnected(Bundle connectionHint) {
            super.onConnected(connectionHint);
            if (mFileId == null) {
                IntentSender intentSender = Drive.DriveApi
                        .newOpenFileActivityBuilder()
                        .setMimeType(
                                new String[] { "text/plain", "text/html",
                                        "application/pdf", "audio/mp3",
                                        "video/mp4", "text/plain",
                                        "application/msword", "image/jpeg",
                                        "image/png", "text/html" })
                        .build(getGoogleApiClient());
                try {
                    startIntentSenderForResult(intentSender, REQUEST_CODE_OPENER,
                            null, 0, 0, 0);
                } catch (IntentSender.SendIntentException e) {
                    Log.w(TAG, "Unable to send intent", e);
                }
            } else {
                DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
                        mFileId);
                Log.i("File Name is ", "===========>>>>" + file);
                file.getMetadata(getGoogleApiClient()).setResultCallback(
                        metadataCallback);
            }
        }

        /**
         * Handles response from the file picker.
         */
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
                case REQUEST_CODE_OPENER:
                    if (resultCode == RESULT_OK) {
                        mFileId = (DriveId) data
                                .getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);

                    } else {
                        finish();
                    }
                    break;
                default:
                    super.onActivityResult(requestCode, resultCode, data);
            }
        }

        /**
         * Handles the metadata response. If file is pinnable and not already
         * pinned, makes a request to pin the file.
         */
        final ResultCallback<DriveResource.MetadataResult> metadataCallback = new ResultCallback<DriveResource.MetadataResult>() {
            @Override
            public void onResult(DriveResource.MetadataResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Problem while trying to retrieve the file metadata");
                    return;
                }
                if (result.getMetadata().isPinnable()) {
                    showMessage("File is not pinnable");
                    Log.i("==========All Info is here", "mIME tYPE=====>>>"
                            + result.getMetadata().getMimeType() + "======>"
                            + result.getMetadata().getTitle() + "====="

                            + result.getMetadata().getAlternateLink() + "======"

                            + result.getMetadata().getWebContentLink() + "======>>"
                            + result.getMetadata().getQuotaBytesUsed());
                    return;
                }
                if (result.getMetadata().isPinned()) {
                    showMessage("File is already pinned");
                    return;
                }

                Log.i("==========All Info is here", "==========>>>");

                DriveFile file = Drive.DriveApi.getFile(getGoogleApiClient(),
                        mFileId);
                MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
                        .setPinned(true).build();
                file.updateMetadata(getGoogleApiClient(), changeSet)
                        .setResultCallback(pinningCallback);

            }
        };

        /**
         * Handles the pinning request's response.
         */
        final ResultCallback<DriveResource.MetadataResult> pinningCallback = new ResultCallback<DriveResource.MetadataResult>() {
            @Override
            public void onResult(DriveResource.MetadataResult result) {
                if (!result.getStatus().isSuccess()) {
                    showMessage("Problem while trying to pin the file");
                    return;
                }
                showMessage("File successfully pinned to the device");
            }
        };
    }

Here My BaseDemoActivity sample code
public abstract class BaseDemoActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "BaseDriveActivity";

    /**
     * DriveId of an existing folder to be used as a parent folder in
     * folder operations samples.
     */
    public static final String EXISTING_FOLDER_ID = "0B2EEtIjPUdX6MERsWlYxN3J6RU0";

    /**
     * DriveId of an existing file to be used in file operation samples..
     */
    public static final String EXISTING_FILE_ID = "0ByfSjdPVs9MZTHBmMVdSeWxaNTg";

    /**
     * Extra for account name.
     */
    protected static final String EXTRA_ACCOUNT_NAME = "account_name";

    /**
     * Request code for auto Google Play Services error resolution.
     */
    protected static final int REQUEST_CODE_RESOLUTION = 1;

    /**
     * Next available request code.
     */
    protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;

    /**
     * Google API client.
     */
    private GoogleApiClient mGoogleApiClient;

    /**
     * Called when activity gets visible. A connection to Drive services need to
     * be initiated as soon as the activity is visible. Registers
     * {@code ConnectionCallbacks} and {@code OnConnectionFailedListener} on the
     * activities itself.
     */
    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();
    }

    /**
     * Handles resolution callbacks.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
            mGoogleApiClient.connect();
        }
    }

    /**
     * Called when activity gets invisible. Connection to Drive service needs to
     * be disconnected as soon as an activity is invisible.
     */
    @Override
    protected void onPause() {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    /**
     * Called when {@code mGoogleApiClient} is connected.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "GoogleApiClient connected");
    }

    /**
     * Called when {@code mGoogleApiClient} is disconnected.
     */
    @Override
    public void onConnectionSuspended(int cause) {
        Log.i(TAG, "GoogleApiClient connection suspended");
    }

    /**
     * Called when {@code mGoogleApiClient} is trying to connect but failed.
     * Handle {@code result.getResolution()} if there is a resolution is
     * available.
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
        if (!result.hasResolution()) {
            // show the localized error dialog.
            GoogleApiAvailability.getInstance().getErrorDialog(this, result.getErrorCode(), 0).show();
            return;
        }
        try {
            result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
        } catch (IntentSender.SendIntentException e) {
            Log.e(TAG, "Exception while starting resolution activity", e);
        }
    }

    /**
     * Shows a toast message.
     */
    public void showMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    /**
     * Getter for the {@code GoogleApiClient}.
     */
    public GoogleApiClient getGoogleApiClient() {
        return mGoogleApiClient;
    }
}

I am getting user select popup only.

select the user after also show this popup how to fix this one.
I get this error:

ConnectionResult{statusCode=SIGN_IN_REQUIRED,
  resolution=PendingIntent{2af2f49: android.os.BinderProxy@462504a}}


Q: Want to know the number of times a value appears on a given date I will try to explain this in as simple a way as possible. I want to be able to count how many times a value is entered into my database table for each day.
Basically, if the data is entered once it would count as a single, if the data was entered twice it would count as a double and if the data was entered three times it would count as a treble.
I then want to be able to count how many singles, doubles and trebles appear within a certain time frame (April to April each year). Then of course echo them out on to the php page like so:
Singles - 23
Doubles - 69
Trebles - 3
I tried adding a round_id column in the database table as I thought if that was default 1 and I could somehow count each day how many 1's appeared that would work but I am totally stuck.
Any help would be greatly appreciated!

A: If I'm understanding you right, to start, we can get a count by day:
SELECT COUNT(*) AS cnt, `date`
FROM `table`
GROUP BY `date`

That will give you the count of records for each day.
Then we can wrap that in another query:
SELECT dailycount.daycnt AS `type`, COUNT(*) AS cnt
FROM (
    SELECT COUNT(*) AS daycnt, `date`
    FROM `table`
    GROUP BY `date`
) dailycount
WHERE `date` BETWEEN start_date AND end_date
GROUP BY daycnt

This will give you something like this:
type cnt
1    23
2    69
3    3

where type would be your singles, doubles, etc.

A: Without knowing the structure, here's the best SQL I could come out with:
SELECT COUNT(DISTINCT field) FROM table GROUP BY field
That will count the number of field appearances for each value.


Q: C# Regex specify allowed start and end condtions I'm trying to create a regex expression with the following requirements:
The value:

*

*Must start with a-z or _, numbers are OK after the first character

*Can have parentheses if they are opened and closed with number inside at the end of string, i.e SomeVar(10) is OK, SomeVar(10 is not OK.

*Can have a . but only one at a time, and only between letters or numbers. SomeVar.InnerVar is OK, SomeVar..Innevar is not OK.

My try at the regex:

*

*[a-zA-Z_]

*??

*??

A: Assuming you want to match an entire string, you may use something like the following:
^[a-zA-Z_](?:\w|(?<=\w)\.(?=\w))*(?:\(\d+\))?$

Demo.
If you want to match partial strings, you'd need to decide what boundaries are allowed. Otherwise, "SomeVar(10" would have a match (i.e., what comes before (), for example.
Notes:

*

*\w matches a lowercase/uppercase letter, a digit, or an underscore. But it also matches Unicode letters and numbers. If you don't want that, you could use [a-zA-Z0-9_] instead.

*Similarly, \d matches any Unicode digit. You either use it or use [0-9] depending on your requirements.

A: Use
^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*(\([^()]*\))?$

See proof.

*

*[a-zA-Z_][a-zA-Z0-9_]* - a letter or underscore, then zero or more letters, digits, underscores

*(\([^()]*\))? - optional group, parens may be present or absent

*(\.[a-zA-Z_][a-zA-Z0-9_]*)* - dot is allowed between letter/digit/underscore.


Q: Delete a row javascript using row id Hi guys I have a table created by php in this way:
  foreach ($query as $row): ?>
                <tr id="<?php echo  $row->aic;?>" >

                    <?php echo $row->aic; ?>
                    <?php echo $row->denominazione ?>
                    <?php echo $row->quantita; ?>
                    <?php echo $row->alert; ?>

                            <img src="<?php echo base_url(); ?>template/images/Modifica.png">

                           "
                                  class="btn btn-default btn-xs"
                                  data-toggle="tooltip"
                                 data-placement="top"
                                 title=""
                                 data-original-title="Elimina"
                                 onclick="deleteRow(<?php echo $row->aic ?>))">

                            <img src="<?php echo base_url(); ?>template/images/Elimina.png">

            <?php

            endforeach; ?>

I need to delete row by rowId. This table has the dynamics id.
The columns ids are the same id of the sql table; in effect aic is id of sql table! In this way I are sure that the HTML row id is unique.
This is script
function deleteRow(rowID)
{   var row = document.getElementById(rowID);
    row.parentElement.removeChild(row);
        alert(rowID);

            }
}

this code don't delete row.

A: Change this:
onclick="deleteRow(deleteRow(<?php echo $row->aic ?>))">

to
onclick="deleteRow(<?php echo $row->aic ?>)">

Another potential issue is that this:
<?php echo $row->aic ?>

may not be a number. So, you need to quote it. That is, change:
onclick="deleteRow(<?php echo $row->aic ?>)">

to:
onclick="deleteRow(\"<?php echo $row->aic ?>\")">

A: 2 issues -

*

*The one that might be causing issue - Incorrect Function Name

*Other one - Calling deleteRow() twice - within each other (this should not cause any issue though)

So, just change -
function eliminaProdotto(rowID)

to -
function deleteRow(rowID)

Edit:
Based on modified question -
Is $row->aic a string? If yes, then add quotes around it...
onclick="deleteRow('<?php echo $row->aic ?>')"


Q: Undefined Reference to vtable with abstract class When building my C++ program, I'm getting the error message.

undefined reference to vtable

I have two virtual abstract classes called and I can't quite figure out what I'm doing wrong if I'm doing anything wrong.
I'm getting errors from both of the classes that are inheriting from the abstract class.
My abstract class is

undefined reference to `vtable for hittable_list'
undefined reference to `vtable for sphere'

hittable.h
     #ifndef HITTABLE_H
        #define HITTABLE_H

    #include "ray.h"

    struct hit_record {
        hit_record() {}
        ~hit_record() {}
        float t;
        vecfloat p;
        vecfloat normal;
        float MAXFLOAT = 100.0;
};

    //Abstract Class containing Sphere and hittablelist
    class hittable
    {
     public:
            virtual ~hittable() = 0;

            virtual bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const = 0;
 };

        #endif

Classes inherting from my abstract class are.
sphere.h
 #ifndef SPHERE_H
#define SPHERE_H

#include "hittable.h"

class sphere : public hittable
{
public:
    sphere() {}
    ~sphere() {}
    sphere(vecfloat cen, float r) : center(cen), radius(r) {}
    bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const;

protected:
    vecfloat center;
    float radius;
};

#endif

sphere.cc
#include "include/sphere.h"

bool sphere::hit(const ray &r, float t_min, float t_max, hit_record &rec) const
{
    vecfloat oc = r.origin() - center;
    float a = oc.dot_product(r.direction());
    float b = oc.dot_product(oc) - radius * radius;
    float c = oc.dot_product(oc) - radius * radius;
    float discriminant = b * b - a * c;
    if (discriminant > 0)
    {
        float temp = (-b - sqrt(b * b - a * c)) / a;
        if (temp < t_max && temp > t_min)
        {
            rec.t = temp;
            rec.p = r.point_at_parameter(rec.t);
            rec.normal = (rec.p - center) / radius;
            return true;
        }
        temp = (-b + sqrt(b * b - a * c)) / a;
        if (temp < t_max && temp > t_min)
        {
            rec.t = temp;
            rec.p = r.point_at_parameter(rec.t);
            rec.normal = (rec.p - center) / radius;
            return true;
        }
    }
    return false;
}

hittable.h
#ifndef HITTABLELIST_H
#define HITTABLELIST_H
#include "hittable.h"

class hittable_list : public hittable
{
public:
    hittable_list() {}

    hittable_list(hittable **l, int n)
    {
        list = l;
        list_size = n;
    }
    bool hit(const ray &r, float t_min, float t_max, hit_record &rec) const;
    ~hittable_list() {}

protected:
    hittable **list;
    int list_size;
};

#endif

hittable.cc
#include "include/hittablelist.h"

bool hittable_list::hit(const ray &r, float t_min, float t_max, hit_record &rec) const
{

    hit_record temp_rec;
    auto hit_anything = false;
    auto closet_so_far = t_max;
    for (int i = 0; i < list_size; i++)
    {
        if (list[i]->hit(r, t_min, closet_so_far, temp_rec))
        {
            hit_anything = true;
            closet_so_far = temp_rec.t;
            rec = temp_rec;
        }
    }
    return hit_anything;
}

A: Solution
Change
virtual ~hittable() = 0;

into
virtual ~hittable() = default;

or
virtual ~hittable()
{
    // does nothing
}

The destructor can remain pure virtual, but it must have a definition.
hittable::~hittable()
{
    // does nothing
}

So what happened?
We can crush the given code down to the following example (Note I can't reproduce the missing vtable with this code or the given code, but regardless, the above will fix it)
Minimal example:
class hittable
{
public:
    virtual ~hittable() = 0; // here we have a destructor,
                             // but there's no implementation
                             // so there is nothing for the
                             // destructors of derived classes
                             // to call

    virtual bool hit() const = 0;
};

class sphere: public hittable
{
public:
    bool hit() const;

};

bool sphere::hit() const
{
    return false;
}

destructors call any base class destructors, and when shpere goes to call ~hittable, it finds that while ~hittableis declared, there is no implementation. Nothing to call.


Q: query: get author of a song and count total of songs for that author I'm not sure how to do the following query. I have 3 tables:
song (song_id, title, is_draft)
author (author_id, name)
song_author (song_id, author_id, display_order)

There are songs, and a song can have multiple authors and an author can write multiple songs
I want to output the authors of a specific song with the total numbers of songs that each author wrote.
So, if i pick song_id: 598, i want to have a result set like this
author_id    name           total songs he wrote
------------------------------------------------
234          Michael Lord   58
589          Lama Turc      12

NOTE: The total number of songs each author wrote must exclude songs were song.is_draft equals 1 and order the result set by song_author.displayorder
From my research, i think i have to do 2 queries (sub queries) but that's as far as i got...
Thanks

A: SELECT  author.author_id, author.name, count(song.song_id)
FROM song, author, song_author,
WHERE song.song_id = $id
AND song.song_id = song_author.song_id
AND song_author.author_id = author.author_id
AND song_author.display_order != 1
GROUP BY song_author.author_id, author.name
ORDER BY author.author_id asc;

A: try this..
select b.author_Id, b.name, COUNT(a.Song_Id) as 'total'
FROm song_author as a
INNER JOIN author as b
    ON a.author_id = b.author_id
where a.song_id IN (select s.song_id
                    From songs as s
                    Where s.Song_Id = 598
                    AnD s.is_draft = 1)
GROUP bY b.author_Id, b.name

A: New to SQL too, but off the top of my head maybe this?  This doesn't explicitly spell out joins, but I've found it works for my purposes.  Maybe someone can let me know if this is bad practice?
Select author.author_id
, author.name
, count(author.author_id)
from song, author, song_author
where song.song_id = song_author.song_id
and author.author_id = song_author.author_id
group by author.authorid, author.name
order by author.author_id asc;


Q: stub random value in rspec with secure_random I am trying to write specs for my gem, which generates otp and saves it in db. Now i am writing specs for it. so basically i have three methods generate_otp!, regenerate_otp!, verify_otp(otp). what generate_otp! does is it calls a method generate_otp which contains three variables

*

*otp_code - basically a random value generated using secure_random

*otp_verified - a boolean value to set the status whether otp is verified or not

*otp_expiry_time - sets expiry time for otp which can be set by rails app in configuration.

these all three are columns of my db also.
Now after generate_otp i am calling active_records's save method to save values to db.
Now for testing i am using in :memory: and storing values in table. after testing i am dropping the db. Now i am not getting how to stub the randomly generated value and test whether value is assigned or not to all three columns, i.e, otp_code , otp_verified, otp_expiry_time.
Here is code for my methods which i need to test.
def generate_otp
    self.otp_verified = false
    self.otp_expiry_time = OtpGenerator::configuration.otp_expiry_time
    self.otp_code = SecureRandom.hex(4)
  end

def generate_otp!
   generate_otp
   save
end

Any help with this ? I have also checked this question, but not much helpful. It's first time i am writing specs and really don't have that much experience with rspecs. I have also studied the official documentation for mock and stub, but i am really getting confused.
update : otp_spec code
require 'spec_helper'

describe OtpGenerator do

  let(:user) { build_mock_class.new() }
  before(:all) { create_table }
  after(:all) { drop_table }

  describe '#generate_otp' do
    it 'generate otp and save it' do
      user.generate_otp!

    end
  end

  describe '#regenerate_otp' do
    it 'regenerate otp and save it' do

    end
  end

  describe '#verify_otp' do
    it 'verifies otp' do

    end
  end

  def build_mock_class
    Class.new(ActiveRecord::Base) do
      self.table_name = 'mock_table'
      include OtpGenerator
    end
  end

  def create_table
    ActiveRecord::Base.connection.create_table :mock_table do |t|
      t.string :otp_code
      t.boolean :otp_verified
      t.datetime :otp_expiry_time
    end
  end

  def drop_table
    ActiveRecord::Base.connection.drop_table :mock_table
  end
end

A: A direct approach to stubbing out the SecureRandom method in rspec would be as follows:
before { allow(SecureRandom).to receive(:hex).with(4).and_return('abcd1234') }

You can then check that 'abcd1234' is stored in the database. In order to keep the test DRY, you may also wish to reference this as a variable, e.g. let(:random_value) { 'abcd1234' }.


Q: Pygame: Character Centered Movement System (Diablo II like click-to-move) I am currently working on a new RPG game using Pygame (my aim here is really to learn how to use object oriented programming). I started a few days ago and developed a movement system where the player clicks a location and the character sprite goes to that location and stops when it get's there by checking if the sprite 'collides' with the mouse position.
I quickly found however that this greatly limited the world size (to the app window size).
I started having a look into making a movement system where the background would move with respect to the player, hence providing the illusion of movement.
I managed to achieve this by creating a variable keeping track of my background map position. The map is much bigger than the app window. And each time I want my player to move I offset the background by the speed of the player in the opposite direction.
My next problem now is that I can't get my character to stop moving... because the character sprite never actually reaches the last position clicked by the mouse, since it is the background that is moving, not the character sprite.
I was thinking of spending some time coding in a variable that would keep track of how many displacements it would take the character sprite to reach the mouse clicked position if it was to move. Since the background moves at the character sprite's speed it would take as many displacement of the background in the x and y directions to center the clicked position on the background to the character sprite at the center of the screen.
It would be something like that:
If MOUSEBUTTON clicked:
   NM = set number of moves needed to reach the clicked position based on character sprite distance to click and character sprite speed.
If NM != 0:
   Move background image
Else:
   pass

This would mean that when my background has moved enough for the character sprite to now be just over the area of the background that was originally clicked by the player, the movement would stop since NM == 0.
I guess that my question is: Does that sound like a good idea or will it be a nightmare to handle the movement of other sprites and collisions ? And are there better tools in Pygame to achieve this movement system ?
I could also maybe use a clock and work out how many seconds the movements would take.
I guess that ultimately the whole challenge is dealing with a fixed reference point and make everything move around it, both with respect to this fixed reference, but also to their own. e.g. If two other sprites move toward one another, and the character of the player also "moves" then the movement of the other two sprites will have to depend both on the position of the other sprite and also on the offset of the background caused by the movement of the player's character.
An interesting topic which has been frying my brain for a few nights !
Thank you for your suggestions !

A: You actually asking for an opinion on game design. The way I look at it, nothing is impossible so go ahead and try your coding. Also it would be wise to look around at similar projects scattered around the net. You may be able to pick up a lot of tips without re inventing the wheel. Here is a good place to start.
scrolling mini map


Q: Android Open and Save files to/from Google Drive SDK I've spent the last six hours pouring over documents from Google and I still don't know how to get started with this. All I want to do is make it so my existing Android app can read files from Google Drive, upload new files to Google Drive, and edit existing files on Google Drive.
I've read that Drive SDK v2 was focused solely on making it easy for Android (and mobile in general) developers to use it, and yet there seems to be virtually nothing in their documentation about it.
Ideally, I'd like someone to point at some decent documentation, example, or tutorial covering how to do this (keep in mind I'm using Android. They have plenty of stuff on how to use Drive with the Google App Engine; I have already looked at it and I have no idea how to go from that to an Android app.)
I need to know which libraries I need to download and add to my project, what I need to add to my manifest, and how I can ultimately get a list of files from Google Drive, download one, and then upload a modified version.
Ideally, I'd like it to handle accounts automatically, the way that the officially Google Drive app does.

A: Edit: Claudio Cherubino says that Google Play Services is now available and will make this process a lot easier. However, there's no sample code available (yet, he says it's coming soon... they said Google Play Services was "coming soon" 4 months ago, so there's a good chance this answer will continue to be the only completely working example of accessing Google Drive from your Android application into 2013.)
Edit 2X: Looks like I was off by about a month when I said Google wouldn't have a working example until next year. The official guide from Google is over here:
https://developers.google.com/drive/quickstart-android
I haven't tested their methods yet, so it's possible that my solutions from September 2012 (below) are still the best:
Google Play Services is NOT REQUIRED for this. It's a pain in the butt, and I spent well over 50 hours (edit: 100+ hours) figuring it all out, but here's a lot of things that it'll help to know:
THE LIBRARIES
For Google's online services in general you'll need these libraries in your project: (Instructions and Download Link)

*

*google-api-client-1.11.0-beta.jar

*google-api-client-android-1.11.0-beta.jar

*google-http-client-1.11.0-beta.jar

*google-http-client-android-1.11.0-beta.jar

*google-http-client-jackson-1.11.0-beta.jar

*google-oauth-client-1.11.0-beta.jar

*guava-11.0.1.jar

*jackson-core-asl-1.9.9.jar

*jsr305-1.3.9.jar

For Google Drive in particular you'll also need this:

*

*google-api-services-drive-v2-rev9-1.8.0-beta.jar (Download Link)

SETTING UP THE CONSOLE
Next, go to Google Console. Make a new project. Under Services, you'll need to turn on two things: DRIVE API and DRIVE SDK! They are separate, one does not automatically turn the other on, and YOU MUST TURN BOTH ON! (Figuring this out wasted at least 20 hours of my time alone.)
Still on the console, go to API Access. Create a client, make it an Android app. Give it your bundle ID. I don't think the fingerprints thing is actually important, as I'm pretty sure I used the wrong one, but try to get that right anyways (Google provides instructions for it.)
It'll generate a Client ID. You're going to need that. Hold onto it.
Edit: I've been told that I'm mistaken and that you only need to turn on Drive API, Drive SDK doesn't need to be turned on at all, and that you just need to use the Simple API Key, not set up something for Android. I'm looking into that right now and will probably edit this answer in a few minutes if i figure it out...
THE ANDROID CODE - Set Up and Uploading
First, get an auth token:
AccountManager am = AccountManager.get(activity);
am.getAuthToken(am.getAccounts())[0],
    "oauth2:" + DriveScopes.DRIVE,
    new Bundle(),
    true,
    new OnTokenAcquired(),
    null);

Next, OnTokenAcquired() needs to be set up something like this:
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
    @Override
    public void run(AccountManagerFuture<Bundle> result) {
        try {
            final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
            HttpTransport httpTransport = new NetHttpTransport();
            JacksonFactory jsonFactory = new JacksonFactory();
            Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
            b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
                @Override
                public void initialize(JSonHttpRequest request) throws IOException {
                    DriveRequest driveRequest = (DriveRequest) request;
                    driveRequest.setPrettyPrint(true);
                    driveRequest.setKey(CLIENT ID YOU GOT WHEN SETTING UP THE CONSOLE BEFORE YOU STARTED CODING)
                    driveRequest.setOauthToken(token);
                }
            });

            final Drive drive = b.build();

            final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
            body.setTitle("My Test File");
    body.setDescription("A Test File");
    body.setMimeType("text/plain");

            final FileContent mediaContent = new FileContent("text/plain", an ordinary java.io.File you'd like to upload. Make it using a FileWriter or something, that's really outside the scope of this answer.)
            new Thread(new Runnable() {
                public void run() {
                    try {
                        com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
                        alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
                    } catch (IOException e) {
                        if (!alreadyTriedAgain) {
                            alreadyTriedAgain = true;
                            AccountManager am = AccountManager.get(activity);
                            am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
                            am.getAuthToken (same as before...)
                        } else {
                            // Give up. Crash or log an error or whatever you want.
                        }
                    }
                }
            }).start();
            Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
            if (launch != null) {
                startActivityForResult(launch, 3025);
                return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
            }
        } catch (OperationCanceledException e) {
            // Handle it...
        } catch (AuthenticatorException e) {
            // Handle it...
        } catch (IOException e) {
            // Handle it...
        }
    }
}

THE ANDROID CODE - Downloading
private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
    if (gFile.getDownloadUrl() != null && gFile.getDownloadUrl().length() > 0 ) {
        if (jFolder == null) {
            jFolder = Environment.getExternalStorageDirectory();
            jFolder.mkdirs();
        }
        try {

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(gFile.getDownloadUrl());
            get.setHeader("Authorization", "Bearer " + token);
            HttpResponse response = client.execute(get);

            InputStream inputStream = response.getEntity().getContent();
            jFolder.mkdirs();
            java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + getGFileName(gFile)); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
            FileOutputStream fileStream = new FileOutputStream(jFile);
            byte buffer[] = new byte[1024];
            int length;
            while ((length=inputStream.read(buffer))>0) {
                fileStream.write(buffer, 0, length);
            }
            fileStream.close();
            inputStream.close();
            return jFile;
        } catch (IOException e) {
            // Handle IOExceptions here...
            return null;
        }
    } else {
        // Handle the case where the file on Google Drive has no length here.
        return null;
    }
}

One last thing... if that intent gets sent off, you'll need to handle when it returns with a result.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 3025) {
        switch (resultCode) {
            case RESULT_OK:
                AccountManager am = AccountManager.get(activity);
                am.getAuthToken(Same as the other two times... it should work this time though, because now the user is actually logged in.)
                break;
            case RESULT_CANCELED:
                // This probably means the user refused to log in. Explain to them why they need to log in.
                break;
            default:
                // This isn't expected... maybe just log whatever code was returned.
                break;
        }
    } else {
        // Your application has other intents that it fires off besides the one for Drive's log in if it ever reaches this spot. Handle it here however you'd like.
    }
}

THE ANDROID CODE - Updating
Two quick notes on updating the last modified date of a file on Google Drive:

*

*You must provide a fully initialized DateTime. If you do not, you'll get a response of "Bad Request" from Google Drive.

*You must use both setModifiedDate() on the File from Google Drive and setSetModifiedDate(true) on the update request itself. (Fun name, huh? "setSet[...]", there's no way people could mistype that one...)

Here's some brief sample code showing how to do an update, including updating the file time:
public void updateGFileFromJFile(Drive drive, File gFile, java.io.File jFile) throws IOException {
    FileContent gContent = new FileContent("text/csv", jFile);
    gFile.setModifiedDate(new DateTime(false, jFile.lastModified(), 0));
    gFile = drive.files().update(gFile.getId(), gFile, gContent).setSetModifiedDate(true).execute();
}

THE MANIFEST
You'll need the following permissions: GET_ACCOUNTS, USE_CREDENTIALS, MANAGE_ACCOUNTS, INTERNET, and there's a good chance you'll need WRITE_EXTERNAL_STORAGE as well, depending on where you'd like to store the local copies of your files.
YOUR BUILD TARGET
Right click your project, go into it's properties, and under Android change the build target to Google APIs if you must. If they aren't there, download them from the android download manager.
If you're testing on an emulator, make sure its target is Google APIs, not generic Android.
You'll need a Google Account set up on your test device. The code as written will automatically use the first Google Account it finds (that's what the [0] is.) IDK if you need to have downloaded the Google Drive app for this to have worked. I was using API Level 15, I don't know how far back this code will work.
THE REST
The above should get you started and hopefully you can figure your way out from there... honestly, this is just about as far as I've gotten so far. I hope this helps A LOT of people and saves them A LOT of time. I'm fairly certain I've just written the most comprehensive set up guide to setting up an Android app to use Google Drive. Shame on Google for spreading the necessary material across at least 6 different pages that don't link to each other at all.

A: Check this video from Google I/O to learn how to integrate your Android app with Drive:
http://www.youtube.com/watch?v=xRGyzqD-vRg
Please be aware that what you see in the video is based on Google Play Services:
https://developers.google.com/android/google-play-services/

A: It's 2015, things have changed!
Get the 'Drive API for Android' with gradle:
compile 'com.google.android.gms:play-services-drive:7.8.0'

There's some new doco (although still lackluster IMO):
https://developers.google.com/drive/web/quickstart/android
And for those about to go caving...the biggest problem I encountered thus far is that there is absolutely no way of distinguishing folders that have been permanently deleted from folders that are normal...you can find them, you can create folders and files within them, only writing to the file DriveContents will always fail.

A: Take a look at Google's DrEdit Example, which has a folder called android/. Copy it, follow the readme, and it should work (works for me on an Android emulator with KitKat).
.
P.S.
Sorry for reviving this, but the new Google Drive Android API doesn't support full Drive access, only drive.file and drive.appdata authorization scopes, so if you need full access you have to go back to the good 'ol Google API's Client for Java (which the DrEdit example uses).


Q: How to create an rray of composites strings Hi everyone: I have a collection of 50 strings that represent comments in a text file where each line represents a separate comment with different sentences .
Each string is a user review of a product, and each string or review has several several sentences.
How could I to create an array with these strings using Python?
Example of reviews:
Review 1.  "I was disapointed with the product. The quality was reality bad and the price was not fair.  Never in my life I'll buy again this brand.
Review 2. "I'm really happy with this product.  It's all what i desired.  Thanks brand J"
.... and so far.
Desired Results:

*

*[('disappointed', 'product'), ('quality', 'really', 'bad', 'price', 'fair')]

*[('happy', 'product'), ('all', 'desired'), ('thanks', 'brand')]

*...

I want each processed comment in a separate line to save it in a csv file

A: One of my first projects was similar to this. I believe your asking for help in getting the text file lines as an array.
To open the file for reading:
file = open("/path/to/file", "r")
I would then split on spaces so:
for line in file:
      print line.split(' ')

this would give you an array of words from each line in the txt file.
Then use the csv module in python to input into a csv file.
References:

*

*Python the Hard Way - Opening and Closting Files

*split() function

*CSV Module


Q: How to allocate 4k aligned Memory malloc() allocates a memory chunk which is virtually contiguous inside the process memory space. malloc() takes a size as a parameter in bytes and returns pointer to that allocated memory space but what if the requirement is to allocate memory which is 4k aligned?

A: That would almost certainly be achieved using something like posix_memalign.

A: Since 4Kbytes is often the size of a page (see sysconf(3) with _SC_PAGESIZE or the old getpagesize(2) syscall) you could use mmap(2) syscall (which is used by malloc and posix_memalign) to get 4Kaligned memory.

A: you can not allocate physically contiguous memory in user space. Because in User space kernel always allocates memory from highmem zone. But if you are writing a kernel module or a system space code then you can use _get_page() or _get_pages().


Q: Django can't multiply sequence by non-int of type 'str' I have this logic in my views and models, in my views i get the data of what the user inputted, and in my models, i have an automatic computation of discount_price_formula, and other_discount_price_formula why i am having this error? can't multiply sequence by non-int of type 'str'. how do i solve this problem?
this is my views.py
otherdiscountpercentage = request.POST.get("otherdiscountpercentage")
S_price = request.POST.get("price")
otherdiscountprice = request.POST.get("otherdiscountprice")
discountpercentage = request.POST.get("discountpercentage")
discountprice = request.POST.get("discountprice")

insert_data = Product(
    price=S_price,
    discount_percentage=discountpercentage,
    discount_price=discountprice,
    Other_discount_percentage=otherdiscountpercentage,
    Other_discount_price=otherdiscountprice,
)

this is my models.py
class Product(models.Model):

    price = models.FloatField(null=True, blank=True, verbose_name="Unit Price")

    discount_percentage = models.FloatField(max_length=500, null=True, blank=True)

    discount_price = models.FloatField(null=True, blank=True)

    Other_discount_percentage = models.FloatField(null=True, blank=True)

    Other_discount_price = models.FloatField(null=True, blank=True, default=0.0)
    discount_price_formula = models.FloatField(null=True, blank=True)
    other_discount_price_formula = models.FloatField(null=True, blank=True)

    def save(self, *args, **kwargs):
        self.discount_price_formula = self.price - (self.price * self.discount_percentage)

        self.other_discount_price_formula = (self.price - (self.price * self.discount_percentage)) - ((self.price - (self.price * self.discount_percentage)) * self.Other_discount_percentage)
        return super(Product, self).save(*args, **kwargs)

    def __str__(self):
        suser = '{0.product}'
        return suser.format(self)

this is my traceback
Traceback:

File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Desktop\onlinestoreapp\customAdmin\views.py" in InsertProduct
  293.     insert_data.save()

File "C:\Users\Desktop\onlinestoreapp\customAdmin\models.py" in save
  209.         self.discount_price_formula = self.price - (self.price * self.discount_percentage)

Exception Type: TypeError at /InsertProduct/
Exception Value: can't multiply sequence by non-int of type 'str'

A: Values coming from a request are by default str type but Django does the conversion directly. Since you're overwriting the save method, you need to convert them to int, like this:
otherdiscountpercentage = request.POST.get("otherdiscountpercentage")
if otherdiscountpercentage:
    otherdiscountpercentage = float(otherdiscountpercentage)

Beware that using request.POST.get('param_name') means the param is optional. So you should put some condition or give a default float value before any calculation.

A: you can do this
otherdiscountpercentage = request.POST.get("otherdiscountpercentage")
S_price = request.POST.get("price")
otherdiscountprice = request.POST.get("otherdiscountprice")
discountpercentage = request.POST.get("discountpercentage")
discountprice = request.POST.get("discountprice")

insert_data = Product(
    price=float(S_price),
    discount_percentage=float(discountpercentage),
    discount_price=float(discountprice),
    Other_discount_percentage=float(otherdiscountpercentage),
    Other_discount_price=float(otherdiscountprice),
)


Q: How to get Country name from ip address using ipinfo? I am using Laravel package for getting location using IP Address.
composer require ipinfo/ipinfolaravel

But when I hit request to get data of location it return null for local host. I have use this,
public function index(Request $request)
{
    dd($request->ipinfo->all);
}

and get out put as,
array:5 [▼
    "ip" => "127.0.0.1"
    "bogon" => true
    "country_name" => null
    "latitude" => null
    "longitude" => null
]

and if I use code like this
public function index(Request $request)
{
    dd($request->ipinfo->country_name);
}

it return
null

How can i solve this issue?


Q: tKinter How disable the Entry while checkbutton is unchecked and enable it while the checkbutton is checked from tkinter import *
window=Tk()
nac = {}
ent = {}
for i in range(10):
    de = IntVar()
    nac[i]=IntVar()
na=Checkbutton(window, text='%s' % (i), borderwidth=1,variable =
nac[i], onvalue = 1, offvalue = 0,command=lambda e=ent,
v=nac[i]:naccheck(e,v))
na.grid(row=i, column=0)
ent[i]=Entry(window,textvariable=de, state = DISABLED)
ent[i].grid(column=1,row=i,padx=20)

window.mainloop()

A: Try this:
from tkinter import *

def entry():
    ent[i].configure(state = NORMAL)

window=Tk()

nac = {}
ent = {}

for i in range(10):
    de = IntVar()
    nac[i]=IntVar()

na=Checkbutton(window, text='%s' % (i), borderwidth=1,variable = nac[i],
               onvalue = 1, offvalue = 0,command=entry)
na.grid(row=i, column=0)
ent[i]=Entry(window,textvariable=de, state = DISABLED)
ent[i].grid(column=1,row=i,padx=20)
window.mainloop()


Q: What is universal binary for iOS how iOS work at run time with them? A universal binary in ios contains executable for both armv7 and arm64. How iOS run architecture based executable.what is the concept of universal binary?
Xcode creates the universal by compiling for both architecture armv7 and arm64 then create the universal binary that contains executable for both in a single file. So my question is what happens when this universal file will run in deep, if anyone have any document related to it please share the link.
thanks in advance.


Q: ExtJs(4.2): Persist Time While Displaying Date time in DateColumn I have datecolumn in a grid.
I am getting value from backend in following format: Y-m-d H:i:s. I have to display it as d.m.Y. And While sending back I have to again send it as Y-m-d H:i:s.
My code is as following:
Model
{
    name: 'REA_LIT_URSPR',
    type: 'date',
    dateFormat:'Y-m-d H:i:s.0'
}

View
{
    xtype: 'datecolumn',
    format:'d.m.Y',
    text: 'Ursp. LT',
    align: 'center',
    flex:1,
    dataIndex: 'REA_LIT_URSPR',
    editor: {
        xtype: 'datefield',
        format:'d.m.Y',
        editable: false
    }
}

Now issue is that if I get this value 2016-04-05 23:15:03.0, it is displayed properly. But as soon as I click it to edit it(and cancel it without selecting new date), I lose the Time 23:15:03.0 and it is changed to 00:00:00.0.
I want to persist this time, in case when user click on cell to change date but change his mind and click somewhere else without changing date.
I am using Ext.grid.plugin.CellEditing for making grid editable.
Can someone tell me what I am doing wrong or how can I achieve my goal?

A: ExtJS CellEditing plugin does not support "canceling" an edit by the user - whenever you click into the field and then leave, the field is validated, and if that does not fail, it is "edited". This is different in RowEditing, where a cancel button is shown that would cancel the edit and fire the canceledit event without validating the input.
So you would have to use the beforeedit and validateedit events on the CellEditing plugin. How to use them is described very well in the ExtJS docs, which documents how to access the date field, the record and the store all at the same time. Example code:
beforeedit:function( editor, context, eOpts ) {
  editor.oldTime = context.record.data.REA_LIT_URSPR;// Save old value.
},
validateedit:function ( editor, context, eOpts ) {
    if(editor.context.value == editor.oldTime) // Compare Values and decide
        context.cancel = true;                 // whether to save it or not

}

A: {
    xtype: 'datecolumn',
    format:'Y-m-d g:i:s A',
    text: 'Ursp. LT',
    align: 'center',
    flex:1,
    dataIndex: 'REA_LIT_URSPR',
    editor: {
        xtype: 'datefield',
        format:'Y-m-d g:i:s A',
        editable: false

    }
}

Ok so the problem is on column date format, maybe you lose a part of date because g:i:s aren't saved from the datecolumn.
I haven't tryed the code, but if it doesn't work try to create a new date format using these docs http://docs.sencha.com/extjs/5.1/5.1.1-apidocs/#!/api/Ext.Date-method-parse    (same on extjs 4)
sorry for first answer, just not clear question


Q: Check list to see if element greater than specified number I'm trying to check if a specific element in the list is greater than a set value.
So
x=22
list=[10,20,30]

# check if anything in list is greater than x
# do something to the list

I'm just not sure what commands to use in this scenario to check every list element or if it's even possible in one line.

A: You ask for "if any element in the list is greater than x". If you just want one element, you could just find the greatest element in the list using the max() function, and check if it's larger than x:
if max(list) > x:
    ...

There's also a one-liner you can do to make a list of all elements in the list greater than x, using list comprehensions (here's a tutorial, if you want one):
>>> x = 22
>>> list = [10, 20, 30, 40]
>>> greater = [i for i in list if i > x]
>>> print(greater)
[30, 40]

This code generates a list greater of all the elements in list that are greater than x. You can see the code responsible for this:
[i for i in list if i > x]

This means, "Iterate over list and, if the condition i > x is true for any element i, add that element to a new list. At the end, return that new list."

A: Use any, Python's natural way of checking if a condition holds for, well, any out of many:
x = 22
lst = [10, 20, 30]  # do NOT use list as a variable anme

if any(y > x for y in lst):
    # do stuff with lst

any will terminate upon the first truthy element of the iterable it is passed and, thus, not perform any spurious iterations which makes it preferable to max or list comprehension based approaches that have to always iterate the entire list. Asymptotically however, its time complexity is, of course, still linear.
Also, you should not shadow built-in names like list.

A: You could use filter and filter your list for items greater than 22, if
the len of this filtered list is > 0 that means your original list contains a value larger than 22
n = 22
lst = [10,20,30]

if len(list(filter(lambda x: x > n, lst))) > 0:
    # do something to lst

A: List comprehension would suit your use case.
In [1]: x=22

In [2]: l=[10,20,30]

In [3]: exist = [n for n in l if n > x]

In [4]: if exist:
   ...:     print "elements {} are greater than x".format(exist)
   ...:
elements [30] are greater than x

If your list is very long, use generator so that you do not have to iterate through all elements of the list.
In [5]: exist = next(n for n in l if n > x)

In [6]: if exist:
    print "Element {} is greater than x".format(exist)
   ...:
Element 30 is greater than x


Q: How to get App's Permission for each app? how to do it programmatically on Android? How to get App's Permission Detail for each app? how to do it programmatically?
I want to display "App's Permission Detail for each app" on TextView.
But I try it but Not Ok??
Hello.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.content.Intent;
import android.content.Context;
import android.content.pm.*;
import android.widget.TextView;
import java.util.*;

public class HelloSakez extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final ListView lw = (ListView) findViewById(R.id.listView1);
final List<ResolveInfo> pkglist = lw.getContext().getPackageManager().queryIntentActivities(mainIntent, 0);
final TextView tw = (TextView) findViewById(R.id.textView1);
Iterator it = pkglist.iterator();
while(it.hasNext()){
ResolveInfo rf = (ResolveInfo)it.next();
tw.append(rf.toString());
}
}
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<ListView android:id="@+id/listView1" android:layout_height="wrap_content" android:layout_width="fill_parent"></ListView>
<TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>

A: You need to use PackageManager's GET_PERMISSIONS flag.
Check this question.

A: Use the following code in your activity:
I created StringBuffer appNameAndPermissions = new StringBuffer(); to append all the apps and permisssions info.
It's working fine. I tested it already. If you have any issues, please let me know.
StringBuffer appNameAndPermissions = new StringBuffer();
PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo applicationInfo : packages) {
    Log.d("test", "App: " + applicationInfo.name + " Package: " + applicationInfo.packageName);
try {
    PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);
    appNameAndPermissions.append(packageInfo.packageName+"*******:\n");

    //Get Permissions
    String[] requestedPermissions = packageInfo.requestedPermissions;
    if(requestedPermissions != null) {
        for (int i = 0; i < requestedPermissions.length; i++) {
            Log.d("test", requestedPermissions[i]);
            appNameAndPermissions.append(requestedPermissions[i]+"\n");
        }
    appNameAndPermissions.append("\n");
} catch (NameNotFoundException e) {
    e.printStackTrace();
}

 Use the following permission in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.GET_TASKS"/>

A: Zhocker
To uninstall any app use below code
Intent i = new Intent(Intent.ACTION_DELETE);
i.setData(Uri.parse("package:com.package name"));
startActivity(i);

And to get permissions use getInstalledPackages(int) with the flag GET_PERMISSIONS

A: *

*For App's permission go to Manifest file ans see.

2.for uninstall the app follow the below points:-
a. go to setting
b. then Open Application
c. then open Manage Application
d. then choose the app which you want to Uninstall
e. then click on Uninstall and Uninstall the app.


Q: How to prevent batch from skipping certain FOR loops? I'm currently working on a casual game in batch, and I'm running into a slight issue when recovering save data.
All the save data is stored in custom INI files (idea from fourth answer here, other code from first answer here). The INI file is first created when the user inputs the name for the save, and said name is set as a variable called savename. The INI file is made when a template, sdata.text, is copied over through type sdata.txt > saves\%savename%.ini.
The variable loadsave, of which is used when a user is loading a previous save file, is then set equal to savename (set loadsave=%savename%). The file then calls a separate file called lsdata.bat, and lsdata.bat takes values from the INI file and assigns them as variables for use in the game.
An example of the INI file would be:
[GameData]
lastfile=expo
lastsection=INTROGAME
nextsection=SECTWO
[PlayerData]
held=none
name=none
lname=none`

and lsdata.bat looks like
for /f "delims=" %%a in ('call get.bat saves\%loadsave%.ini GameData lastfile') do (
    set lastfile=%%a
    echo setting var lastfile...
)

for /f "delims=" %%a in ('call get.bat saves\%loadsave%.ini GameData lastsection') do (
    set lastsection=%%a
    echo setting var lastsection...
)

for /f "delims=" %%a in ('call get.bat saves\%loadsave%.ini GameData nextsection') do (
    set nextsection=%%a
    echo setting var nextsection...
)

Et cetera. The file get.bat is the exact same as ini.bat from the second link I mentioned up there.
The problem arises when recalling a modified save file. When creating a new save, lsdata.bat is called and everything runs smoothly (I can tell from the echoed lines of text that help me confirm the FOR loop was completed). However, when using a modified save file where all the values are not the defaulted ones, all of the FOR loops are skipped and the file skips to an ECHO and a CECHO I have at the bottom.
If the save file is created and exited before the game has a chance to overwrite some values, everything is recovered as it should. If even one value has been changed, though, it skips all the FOR loops and the variables are all equal to NUL. When the game first loads, all variables are set to NUL for testing purposes, and then can be reassigned values when a new save is created or an old one is loaded.
Delayed expansion is on, and if you try to call variables (with ! or %), it still shows them set equal to NUL.
How can I prevent the modified files from causing this weird bug?


Q: Special IF/THEN Statement And Data Validation List In VBA The best way I can explain what I need is this:

*

*If A1 = "" and A3 = "", then put a data validation list in cell A2.

*If A1 = "" and A3 <> "", then A2 = A3.

*If A1 <> "" and A3 = "", then A2 = A1

*If A1 <> "" and A3 <> "", then A2 = A1
I know I'm leaving out a lot of information, but if anyone could write this in VBA Code where it automatically updates when A1 or A3 are changes, I would appreciate it. I already have a named range that I want to use for the Data Validation List. I am working in Excel 2016, but I need this to work with Excel 2010 as well. I know, quite literally, nothing when it comes to coding.
Edit:
If it were possible to write this in a formula in cell A2, it would go as follows:
=if(and(A1="",A3=""),Named_Range,if(and(A1="",A3<>""),A3,if(and(A1<>"",A3=""),,A1,if(and(A1<>"",A3<>""),A1,""))))
Whereas "Named_Range" would make the cell a data validation list with the named range "Example 1". In every other instance, the data validation list would be deleted and would equal the respective cell.
However, I know that this is not possible (I think) without using Worksheet Change in VBA Code. I am not familiar with writing VBA code, but I do know you can write If/Then statements and Data Validation Lists in VBA code. I just need to make that "Formula" in VBA Code in excel.

A: For a non-coding solution you could add two additional rows (and swap row 2 & 3) to allow for the automation:
Row 1: Values
Row 2: Values
Row 3: =if(and(A1="",A2=""),"SELECT FROM DROPDOWN BELOW",if(and(A1="",A2<>""),A2,if(and(A1<>"",A2=""),,A1,if(and(A1<>"",A2<>""),A1,""))))
Row 4: Dropdown list where the first option is blank ""
Row 5: =IF(A3<>"SELECT FROM DROPDOWN BELOW", A3, IF(A4<>"",A4,"SELECTION NEEDED"))
Much taller, but fits the given requirements.


Q: How to set a custom npm directory for global packages in Dockerfile? I've just read the best practices about Global npm dependencies and tried to utilize this approach in my Dockerfile:
FROM node:carbon
...
ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
ENV PATH="/home/node/.npm-global:${PATH}"
...
RUN npm install -g nodemon
...
CMD ["nodemon", "server.js"]
USER node

But when I try to start the container I get:
ERROR: for my_project_node_1  Cannot start service my_project_node:
OCI runtime create failed: container_linux.go:296:
starting container process caused "exec: \"nodemon\":
executable file not found in $PATH": unknown

ERROR: for my_project_node  Cannot start service my_project_node:
OCI runtime create failed: container_linux.go:296:
starting container process caused "exec: \"nodemon\":
executable file not found in $PATH": unknown

I just don't understand what I do incorrectly..
How to set PATH environment variable in a Dockerfile I get from here https://stackoverflow.com/a/38742545/202550


Q: Common Lisp: Using (let) for evaluating recursive function So I wrote something that returns a maximal subset sum given a list of positive integers. However, I would like to use the (let) so that I make the code more efficient. I would like to know if or how that is possible.
(defun subset-sum1 (numbers capacity)
  (subset-sum numbers capacity 0))

(defun subset-sum (numbers capacity counter)
  (cond ((null numbers) counter)
        ((= counter capacity) counter) ;; return if counter 'hits' the capacity
        ((< capacity (+ (car numbers) counter))
         (subset-sum (cdr numbers) capacity counter)) ;; cdr if car branch exceeds capacity
        ((<= (subset-sum (cdr numbers) capacity counter)
             (subset-sum (cdr numbers) capacity (+ (car numbers) counter)))
         (subset-sum (cdr numbers) capacity (+ (car numbers) counter))) ;; choose car
        (t (subset-sum (cdr numbers) capacity counter)))) ;; choose cdr

The above code works fine in common lisp. But, I would like to do something like below, because I feel like using let will make the code better. But what I wrote goes into an infinite loop :(
This is an assignment for an introductory AI class... help out a novice please!
(defun subset-sum (numbers capacity counter)
  (let ((exclude (subset-sum (cdr numbers) capacity counter))
   (include (subset-sum (cdr numbers) capacity (+ (car numbers) counter))))
     (cond ((null numbers) counter)
       ((= counter capacity) counter)
       ((< capacity (+ (car numbers) counter)) exclude)
       ((<= exclude include) include)
       (t (exclude)))))

A: You get an infinite loop because of these lines:
(defun subset-sum (numbers capacity counter)
  (let ((exclude (subset-sum (cdr numbers) capacity counter))

You keep calling subset-sum recursively, and it never terminates.  Even when you get to the end of the list, and numbers is (), you keep going, because (cdr '()) is '().  You handled this in the original by checking (null numbers) (though it might be more idiomatic to use (endp numbers)).  Now you can do something like:
(defun subset-sum (numbers capacity counter)
  (if (endp numbers)
    counter
    (let ((exclude (subset-sum (cdr numbers) capacity counter))
          ;...
         )
      (cond ; ...
          ))))


Q: How does mmap interract with Go's garbage collector? Go has a garbage collector for slices that only frees the slice when all references to it are dead. It also has an Mmap function that returns a []byte that can be explicitly freed with Munmap(). So how does this work with Go's garbage collector.
What happens if I do this?
m := syscall.Mmap(...)
m2 = m[10:100]
syscall.Munmap(m)
a = m2[0]


Q: How to sort gridview item in flutter I know how to sort in listview while streaming from firebase by using orderBy properties, but when I try in in GridView.builder, it is not working. can any body please help
final CollectionReference _productss =
  FirebaseFirestore.instance.collection('donation');

     return StreamBuilder(
        stream: _productss
            .where('status', isEqualTo: "Approved")snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
          if (streamSnapshot.hasData) {
            return GridView.builder(
                itemCount: streamSnapshot.data!.docs.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: kDefaultPaddin,
                  crossAxisSpacing: 10,
                  childAspectRatio: 0.75,
                ),
                itemBuilder: (context, index) {


Q: NivoSlider IE7 push my CPU to 100% even after fade effect finishes I am using NivoSlider to create a nice rotating banner animation. In particular, I am using the "fade" animation.
It works well in all browsers except IE7.
In IE7, when the fade out / fade in effect occurred, the CPU on my computer goes to 100% and stays there.
In all other browser the CPU goes at 100% only while the effect is processing but goes back to a normal level afterwards.
Do what can I do to resolve this issue?


Q: Overriding previously set CSS My css:
.pic img:hover {
  border: 1px black solid;
}

My html:

I have an "overlay.jpg" that is placed in the bottom corner of the first image.
Problem with the css is that the overlay gets the :hover effect too.
The actual code is very complicated, I know the best solution would be to add a class to the first image and hover only that, but that will take more time than what i currently have to get this fixed.
The code has a class for the overlay images though, so I'm asking if theres a way to override the hover by setting some other css for the overlay class.
However .overlay:hover { border: none; } does not do the trick, even if i put it after the css above.

A: Your rule is less specific than the previous one so it is getting overridden.
You have to change it to:
.pic .overlay:hover { border: none; }

The concept
Specificity is the means by which a browser decides which
  property values are the most relevant to an element and gets to be
  applied. Specificity is only based on the matching rules which are
  composed of selectors of different sorts.
How is it calculated?
The specificity is calculated on the
  concatenation of the count of each selectors type. It is not a weight
  that is applied to the corresponding matching expression.
In case of specificity equality, the latest declaration found in the
  CSS is applied to the element.

Reference: Specificity

A: As long as overlay always comes after the first image, you can use :first-child to pick only the first image:
.pic img:first-child:hover {
  border: 1px black solid;
}

It's supported in everything (excluding IE6, but I don't count that as a thing.)

A: You can also use the :not selector:
.pic img:not(.overlay):hover {
  border: 1px black solid;
}

This way you won't have to worry about the order of the images and also don't have to worry about specificity by including another reset style.


Q: Reminder Email User for Password Expiration in AWS SES I am using AWS SES to send mail from my website (Using Laravel).
I want to set password expiry reminder before expiring (SES) password.
I have gone through some articles and documentation but did not get any solution.


Q: Installing Google Cloud SDK on Azure Web Apps I need to install https://cloud.google.com/sdk/ on my Azure Web App so we can execute > gcloud auth application-default loginand have our application running with communication between Google and Azure.
How can I install https://cloud.google.com/sdk/ to the Azure Web App container? been looking for a command configuration (as in linux) but can't seem to find any info.


Q: Arrays in array How can I create an array with Ruby (on Rails) in this form:
[[0,5], [1,5], [3,7]]

Edit:
I know how to define simple array and add some data:
posts = Array[] # or Array.new
posts << data.id # e.g. posts[1,2,3,4]

BUT i wanna know how to add (push) data to the array that is more complexive like in first array [[],[]].
Try to understand me, please. :)

A: num = [[0,5], [1,5], [3,7]] isn't working?

A: There is a lot of ways to resolve your issue. You're looking for an array of arrays. I think you're confused by how an array can be inside an array. You should keep in mind that an array is just an ordered list of objects. So storing in array in each index is not as foreign as a concept as it may seem.
A = [] #an empty array
A[0] = [1, 2]
A[1] = 1
A # => [[1,2], 1]

If you want to initialize an array with a default value as an array try
A = Array.new(2) {Array.new(2){0}} #This creates an array of size 2 with default values of arrays of size 2 with 0 in each entry.

A[0][1] # returns 0
A[0] # returns [0, 0]
A #returns [[0,0], [0,0]]


Q: Do bluetooth smart (4.0) provide the same services as plain old Bluetooth? What I want to ask is - Will a BLE device be able to answer calls, play music, etc... or that Bluetooth 4.0 is intended for a kind of NFC alternative?

A: Bluetooth 4.0 has all backwards compatibility with it's older versions.
BLE is a form of connect using low energy technology.
BLE = Bluetooth Low energy.
They are different technologies with different proposes. BLE tend to be used in heart rate monitors, bike computers, medicinal applications and etc. Whenever the power supply is limited.
BLE intent is not for headsets and similar devices. That's why you see on phone specifications Bluetooh 4.0 + BLE (or LE). Bluetooh is a technology, BLE is a 'protocol of communication'

A: Bluetooth Low Energy is part of the Bluetooth 4.0 specification.  Bluetooth 4.0 includes Classic Bluetooth, Bluetooth Low Energy and Bluetooth High Speed.
Bluetooth Low Energy (BLE) uses a different radio protocol with fewer, wider channels and a lower transmission rate and power than Bluetooth Classic (although it uses the same frequencies) and most importantly it implements a different set of profiles.
Classic Bluetooth has profiles such as Serial Port Profile (SPP) and Handsfree Profile (HFP) while the most commonly used profile in BLE is the Generic Attribute profile (GATT). This profile allows for the transfer of small amounts of data at relatively low speeds and is not suitable high-bandwidth time-critical applications such as audio streaming.
Dual-mode Bluetooth chipsets that support Classic Bluetooth and BLE are available although often they can only operate in one mode at a time.  Many BLE chipsets are BLE only, however as it reduces cost and complexity.
The short answer is that BLE can't support the classic Bluetooth functions you described.


Q: Getting textbox value from X-editable How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):

    print request.POST.get("test", "");
    return HttpResponse(json,content_type="application/json")

HTML
First Name

AJAX
$(document).ready(function() {

        $('#other1').editable({
            type: 'text',
            pk: 1,
            url: '/create_post/',
            ajaxOptions: {

                    data: {

                    csrfmiddlewaretoken: '{{ csrf_token }}',
                    test: "hi",
                    },

                },
            placement: 'top',
            title: 'New Expense',
            success: function(response, newValue) {
                if(response.status == 'error') return response.msg; //ms
            },

        });

    });

A: Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
First Name

AJAX
$(document).ready(function() {
    $('#other1').editable({
        type: 'text',
        url: '/create_post/',
        params : function(params) {
            params.csrfmiddlewaretoken = '{{ csrf_token }}';
            return params;
        },
        placement: 'top',
        title: 'New Expense',
        success: function(response, newValue) {
            if(response.status == 'error') return response.msg; //ms
        },

    });
});


Q: Bit confused with cloudfront and why my cert for the CNAME is not working I am getting this message on my main site, after I setup a CloudFront distribution. I created a certificate for cdn.example.com, chose custom and entered cdn.example.com for use with HTTPS.
I created a CNAME in my DNS configuration for cdn.example.com, and I added the validation record as requested by AWS. The certificate shows up as issued and validated.
    Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be “cdn.example.com”, which could put your confidential information at risk.

No images get loaded and the site does not render as it should. If I use the cloudfront url (i.e. d12345.cloudfront.net), all works fine. Do I need to add a SAN to my certificate, such as the main domain (i.e. example.com) in addition to cdn.example.com? If so, how does that work as I already use a SSL certificate for my www.example.com and example.com from Let's Encrypt.
I am using WordPress and wpfastestcache to integrate CloudFront with the website, where I specified cdn.example.com and the origin as example.com.

A: This question was confusing, since it seemed to describe a very unlikely condition.  How could a newly-configured CloudFront distribution with a new certificate from ACM offer an invalid certificate?
In truth, I was distracted by part of the "helpful" browser error message,  "You might be connecting to a server that is pretending to be..." I mistakenly assumed that this implied that the hostname in the certificate was correct ("pretending to be") but that the certificate was invalid for some other reason.
As it turns out, the certificate being offered was the default, generic *.cloudfront.net certificate, so the hostname in the cert didn't match the custom domain name.
After creating a certificate in ACM, it needs to be associated with the CloudFront distribution, as mentioned at https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html#DownloadDistValuesSSLCertificate.
Another hint to the nature of the problem would have been observable in the ACM console.  There, the certificate would have shown In Use? No.

In Use? – Whether the ACM Certificate is actively associated with an AWS service such as Elastic Load Balancing or CloudFront. The value can be No or Yes.
https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-list.html#gs-acm-list-console


Q: Upload file to drive with reactjs and nextjs I am using this https://github.com/rpldy/drive-uploady to update files but this library only shows an example where you have to upload files from local. If i have a file (base64 url) or a blob (which i get from a pdf file i got from google drive before) how can i use this. I have tried multiple resource but no thing can give me result.
Here: https://github.com/rpldy/react-uploady/tree/master/packages/ui/uploady

A: Drive-Uploady is mainly a sender for Uploady. Therefore, you are able to use most of Uploady's functionality. In this case, the upload context method -

import React from "react";
import DriveUploady, { useUploady } from "drive-uploady";

const MyButton = () => {
  const { upload } = useUploady();

  const onUpload = async () =>  {

    const myBlob = await getBlobFromSomewhere();

    upload(myBlob);
  };

  return <button onClick={onUpload}>Upload</button>
};

const App = () => {

  return <DriveUploady
          ...
          >
          <MyButton />
        </DriveUploady>
};

This will initiate the upload process once the button is clicked. Where you get the blob is your responsibility of course.


Q: Angular 5 view not displaying updated property value after initial change My view isn't showing the updated property value of a local property, bound model property, nor a value from observable. Logging from console shows all the values are updated.
This is a multi-step form and works great with exception of this annoying issue:
The first time I click on booth, clickBooth(e) is fired as expected and the view updates with the value.
I click on another booth to 'add' it, all the same code fires, but the view doesn't reflect the new updated value of selectedboothlabels or newbookingform.booths
Move on in the form, (using a continue button that fires a 'changeStep' method), then go back to this particular section of the form, the correct values of selectedboothlabels and newbookingform.booths are displayed in the view.
Tried so many things. I think I'm running in circles now. This is the latest of many versions of code:
Service:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs';

@Injectable()
export class SelectedBoothService {

  public boothlist = new Subject<string[]>();

  setBoothList(value: string[]) {
    this.boothlist.next(value);
  }
  getBoothList(): Observable<any> {
    return this.boothlist.asObservable();
  }
}

Relevant from View (very, very simplified):
{{selectedboothlabels}}<br>
{{newbookingform.booths}}

NOTE: I tried binding newbookingform.booths (which is part of the BookingForm ngModel on a form) to a simple text input. However the value is NOT updated through the input, so don't believe this does anything.
Relevant Code from Component:
import { SelectedBoothService } from '../../services/selectedbooths.service';
import { Subscription } from 'rxjs/Subscription';
import { BookingForm } from '../../models/booking.interface';

@Component({
    selector: 'reserve-booth',
    templateUrl: './reserve-booth.component.html'
})
export class ReserveBoothComponent implements OnInit {
    selectedboothlabels: string[] = [];
    boothlistsubscription: Subscription;
    newbookingform: BookingForm = new BookingForm();

    constructor(
        private _changedetector: ChangeDetectorRef,
        private _selectedboothService: SelectedBoothService) {

            this.boothlistsubscription =
              this._selectedboothService.getBoothList().subscribe(list => {
                     console.log("Subscribing to the boothlist: " + list); //shows most recent values perfectly
                     this.selectedboothlabels = list;
                     this._changedetector.markForCheck(); //no affect...
             });
    }

     //fired from an custom component. Works great.
     clickBooth(e) {
          let boothindex = -1;
          let targetid = e.currentTarget.id;
           //check our list of selectedbooths.
           if (this.selectedboothlabels != undefined) {
               boothindex = this.selectedboothlabels.indexOf(targetid);
           }
           if (boothindex == -1) {
              //add to our list
              this.selectedboothlabels.push(targetid);
              boothindex = this.selectedboothlabels.indexOf(targetid);
              this.newbookingform.booths = this.selectedboothlabels;
              this._selectedboothService.setBoothList(this.selectedboothlabels);
           } else {
             //already here. Remove it.
             this.selectedboothlabels.splice(boothindex, 1);
             this.newbookingform.booths = this.selectedboothlabels;
             this._selectedboothService.setBoothList(this.selectedboothlabels);

             boothindex = this.selectedboothlabels.indexOf(targetid);
          }

          this._changedetector.detectChanges(); //seems to have no affect
       }
     }


Q: Is there (and what are) a differences in developing in html5 and by using phonegap? What is the difference if we develop android apps in pure html5 without using phonegap libraries and what if we use Phonegap? This might sound noob but I'm really not getting the connection between these two?
Why do I need phonegap? Why not just creating html5 files and provide the path to it ?

A: PhoneGap give you a layer of abstraction so that you app is going to have access to non browserView accessible functionality like the camera for example.
And those will be the same on all mobile plateforme.

A: You can create application with pure html5 with webview and piece of java methods used to handle mobile events like Calling, Messaging, Sensors, etc,.
When you are using phonegap libraries, no need to do much work with java methods. The phonegap libraries will handle the java and you can only work with html5 and java script with little bit help of jquery mobile framework. All mobile events you can call directly in the javascript of html page.

A: Using HTML5 and PhoneGap you can implement different kinds of applications:

*

*Mobile applications using HTML5. You will need a server to back up your application and the users will run it through the device's browser.

*Native application using HTML5 and WebView. Using a server isn't necessary. In this case you write HTML5 code (HTML, CSS, Javascript) and you use a WebView to display it. You can interact with Java using a special interface.

*PhoneGap makes the above case easier. You don't need to know the details of WebView. You need PhoneGap APIs to interact with the phone's resources. As an added bonus you can easily port the application to other platforms. PhoneGap also creates native applications.


Q: why does height: auto not provide content area large enough to fit my content? When a user is logged out, the header shows a logo and a log-in form, which the header needs to be large enough to accommodate. When a user logs in, they see the full navigation on a header that no longer needs to be quite so large. I'd think that setting height:auto to "site-header" would accomplish this, but this just makes the form float over the header's bottom border.
html:

      <%= link_to full_title(yield(:title)), root_path, class: "logo" %>

      <% if user_signed_in? %>
        <%= link_to "Sell", new_item_path %>
        <%= link_to "FAQ", pages_faq_path %>
        <%= link_to "Settings", edit_user_registration_path %>
        <%= link_to "Log out", destroy_user_session_path %>
      <% end %>

      <% if !user_signed_in? %>
        <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

            <%= f.label :email %>

            <%= f.email_field :email, autofocus: true, class: 'peach' %>

            <%= f.label :password %>

            <%= f.password_field :password, autocomplete: "off", class: 'peach' %>
            <%= f.submit "LOG IN", class: 'button-functional' %>

            <%= render "devise/shared/forgotpass" %>

        <% end %>
      <% end %>

css:
header {
    background-color: white;
    top: 0;
    left: 0;
    right: 0;
    z-index: 0;
    border-bottom: 1px dashed black;
    .site-header {
        margin: 0 2em;
        padding: 1em 0;
        height: auto;
        nav {
            float: right;
            a {
                margin-right: 2em;
            }
            a:last-child {
                margin-right: 0;
            }
        }
        .log-in {
            float: right;
            .form {
                float: left;
            }
            input {
                margin-right: 1em;
            }
        }
    }
}

A: I made a Plunker with your example and it does fill the space.
https://plnkr.co/edit/QMiHzA89NZrDkpsrCefF
HTML

      <%= link_to full_title(yield(:title)), root_path, class: "logo" %>

      <% if user_signed_in? %>
        <%= link_to "Sell", new_item_path %>
        <%= link_to "FAQ", pages_faq_path %>
        <%= link_to "Settings", edit_user_registration_path %>
        <%= link_to "Log out", destroy_user_session_path %>
      <% end %>

      <% if !user_signed_in? %>
        <%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

            <%= f.label :email %>

            <%= f.email_field :email, autofocus: true, class: 'peach' %>

            <%= f.label :password %>

            <%= f.password_field :password, autocomplete: "off", class: 'peach' %>
            <%= f.submit "LOG IN", class: 'button-functional' %>

            <%= render "devise/shared/forgotpass" %>

        <% end %>
      <% end %>

CSS
header {
    background-color: white;
    top: 0;
    left: 0;
    right: 0;
    z-index: 0;
    border-bottom: 1px dashed black;
    .site-header {
        margin: 0 2em;
        padding: 1em 0;
        height: auto;
        nav {
            float: right;
            a {
                margin-right: 2em;
            }
            a:last-child {
                margin-right: 0;
            }
        }
        .log-in {
            float: right;
            .form {
                float: left;
            }
            input {
                margin-right: 1em;
            }
        }
    }
}

Maybe you have some other CSS messing around.


Q: Why 'return' is not working in generator method? def function(list):

    for x in list:
        yield x

    return 4

list = [1,2,3]
object = function(list)
print(next(object))
print(next(object))
print(next(object))
print(next(object))

In this code when I'm calling function for the 4th time I'm getting error.
But when I replace return 4 to yield 4 then it's working properly.
Why that's happening?
On the 4th call the for loop get exited and next line return 4 executed. Then what's the problem?

A: If you want to yield, and prematurely exit the function, you can use a bare return after you yielded:
def function(ls):
    for x in ls:
        yield x
    yield 4
    return
    some_code(that_wont, be_executed)

Generators don't return values, they yield them. The only reason to use return in a generator is to abort the execution / raise a StopIteration to signal to the caller that there are no more values.


Q: Do not refresh Inner Update Panel in asp.net I am using 2 Update Panel in Asp.net. Second Update Panel is inside main Update Panel. It is like as below :
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
   <ContentTemplate>
      <asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
         <ContentTemplate>
            // Google Map...
         </ContentTemplate>
      </asp:UpdatePanel>
   </ContentTemplate>
</asp:UpdatePanel>

UpdatePanel1 contains Dropdown and It is Autupostback=true so if user selects any Dropdown then it refreshs Google Map which is inside. I do not want to refresh inside Update Panel anyway.
Is it possible to do this ?

A: People often misunderstand the way UpdatePanel works. They mistakenly think that, there's no page reload   when anything triggering postback occurs inside an UpdatePanel. This is totally wrong. In fact a full page reload is taken place. It's not a coincidence that UpdatePanel is located under category called AJAX controls of the toolbox. But it does not work the same as AJAX does, it just imitates it. What you get when you use UpdatePanel is that the page does not flicker to the top of the page, which is the normal behavior of any full page reload, so you get a feeling of partial refresh. That's why, the Google Maps you're talking about gets refreshed. Using real AJAX will help you do just what you want. Jquery library has a very convenient way of doing AJAX. Or you can just use plain javascript.


Q: How do I open default browser to home page in C#? The question below has the answer to "How do I open the default Browser to a URL in C#?" But how do I open the default browser in C# without navigating to a URL? Desired behavior is for the default browser to open to the home page, or use the startup behavior (for example, defined in the Firefox option "When Firefox starts").
How to open in default browser in C#

A: This should do it:
Process p = new Process();
p.StartInfo = new StartInfo(url) {UseShellExecute = true};
p.Start();

EDIT: This will work for a valid URL. As the comment above say this will not work for http://about:home.
EDIT #2: I will keep the previous code in case it's helpful for anybody. Since the comment above I've been looking how to do it, and in deed was not so trivial, this is what I did in order to launch the default browser without navigating to any URL.
using (var assoc = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice"))
{
    using (var cr = Registry.ClassesRoot.OpenSubKey(assoc.GetValue("ProgId") + @"\shell\open\command"))
    {
        string loc = cr.GetValue("").ToString().Split('"')[1];
        // In windows 10 if Microsoft edge is the default browser
        // loc=C:\Windows\system32\LaunchWinApp.exe, so launch Microsoft Edge manually
        // 'cause didn't figured it out how to launc ME with that exe
        if (Path.GetFileNameWithoutExtension(loc) == "LaunchWinApp")
            Process.Start("explorer", @"shell:Appsfolder\Microsoft.MicrosoftEdge_8wekyb3d8bbwe!MicrosoftEdge");
        else
            Process.Start(loc);
    }
}

I tested it in my machine (Win10) and worked out for every default browser switch. Hope it helps now.