text:
Q: Trigger — is invalid and failed re-validation I am trying to create this simple trigger :
  CREATE OR REPLACE TRIGGER my_trig
  BEFORE DELETE OR INSERT OR UPDATE ON empcopy
  FOR EACH ROW
  WHEN (NEW.EID > 0)
  DECLARE
  sal_diff number;
  BEGIN

 sal_diff := :NEW.salary  - :OLD.salary;
 dbms_output.put_line('Old salary: ' || :OLD.salary);
 dbms_output.put_line('New salary: ' || :NEW.salary);
 dbms_output.put_line('Salary difference: ' || sal_diff);
 COMMIT;
  END;
  /

on execution it gives the result as:
   Trigger created

But when I update my table the following result is obtained:
  update empcopy
  set salary=salary+5000;

after execution:
  error at line 1
  ORA-0498:triiger 'HR.MY_TRIG' is invalid and failed re-validation.

A: You can't COMMIT without using a PRAGMA AUTONOMOUS_TRANSACTION in your DECLARE block.
If the database allowed committing in row-level triggers, this could enable committing part of the rows in a statement before the others had been evaluated and would disrupt the statement as a unit--all rows in an individual statement should complete their change and be committed together.
If you were to use an AUTONOMOUS_TRANSACTION in this trigger, this would allow the trigger to execute new UPDATEs, DELETEs, etc in a transaction independent from other active DML changes in the open transaction.
But note, in you're case, your TRIGGER isn't actually executing any mutational DML, nor even any reads, so you don't need a COMMIT at all.  All you need to do is drop your COMMIT as below.
CREATE OR REPLACE TRIGGER my_trig
BEFORE DELETE OR INSERT OR UPDATE ON empcopy
FOR EACH ROW
WHEN (NEW.EID > 0)
  DECLARE
    sal_diff number;
  BEGIN

    sal_diff := :NEW.salary  - :OLD.salary;
    dbms_output.put_line('Old salary: ' || :OLD.salary);
    dbms_output.put_line('New salary: ' || :NEW.salary);
    dbms_output.put_line('Salary difference: ' || sal_diff);
  END;
/

I would however suggest a couple other changes as well.
As other triggers can also change the NEW value, you might consider making this an AFTER TRIGGER, to only log the final state.
Also this trigger will not log any DELETEs, since DELETEs will all have a NULL :NEW.EID.  I'd suggest either dropping the AFTER DELETE if logging DELETEs is not intended, or handling DELETEs separately via a CASE WHEN DELETING statement.
CREATE OR REPLACE TRIGGER MY_TRIG
AFTER DELETE OR INSERT OR UPDATE ON EMPCOPY
FOR EACH ROW
  DECLARE
    SAL_DIFF NUMBER;
  BEGIN
    CASE WHEN DELETING
      THEN
        DBMS_OUTPUT.put_line('Log the delete here if you want.');
      WHEN (:NEW.EID > 0)
      THEN
        SAL_DIFF := COALESCE(:NEW.SALARY, 0) - COALESCE(:OLD.SALARY, 0);
        DBMS_OUTPUT.put_line('Old salary: ' || :OLD.SALARY);
        DBMS_OUTPUT.put_line('New salary: ' || :NEW.SALARY);
        DBMS_OUTPUT.put_line('Salary difference: ' || SAL_DIFF);
    ELSE NULL;
    END CASE;
  END;
/

Also DBMS_OUTPUT is transient logging.  In case you want to keep a record of changes to EMPCOPY more permanently, Oracle has tools available to automate and control change-tracking in your data, such as audit trail and FGA.
EDIT: examples below.
Create a test table:
CREATE TABLE EMPCOPY(
  EID NUMBER NOT NULL,
  SALARY NUMBER
);
Table EMPCOPY created.

Then create the trigger:
CREATE OR REPLACE TRIGGER MY_TRIG
AFTER DELETE OR INSERT OR UPDATE ON EMPCOPY
FOR EACH ROW
  DECLARE
    SAL_DIFF NUMBER;
  BEGIN
    CASE WHEN DELETING
      THEN
        DBMS_OUTPUT.put_line('Log the delete here if you want.');
      WHEN (:NEW.EID > 0)
      THEN
        SAL_DIFF := COALESCE(:NEW.SALARY, 0) - COALESCE(:OLD.SALARY, 0);
        DBMS_OUTPUT.put_line('Old salary: ' || :OLD.SALARY);
        DBMS_OUTPUT.put_line('New salary: ' || :NEW.SALARY);
        DBMS_OUTPUT.put_line('Salary difference: ' || SAL_DIFF);
    ELSE NULL;
    END CASE;
  END;
/
Trigger MY_TRIG compiled

Then test it:
SQL> --Should not log, EMPID is not greater than zero.
SQL> INSERT INTO EMPCOPY VALUES (-13, 50000);
1 row inserted.
SQL> --Should log, EMPID is greater than zero.
SQL> INSERT INTO EMPCOPY VALUES (1919, 75000);
Old salary:
New salary: 75000
Salary difference: 75000
1 row inserted.
SQL> -- The statement you provided.  This should log for EMPID=1919 but not EMPID=-13
SQL> update empcopy
  2  set salary=salary+5000;
Old salary: 75000
New salary: 80000
Salary difference: 5000
2 rows updated.
SQL> -- This should log a PLACEHOLDER value for each row on delete.
SQL> DELETE FROM EMPCOPY;
Log the delete here if you want.
Log the delete here if you want.
2 rows deleted.


text:
Q: How to bring my first column to my automate email in App Scripts? Some weeks ago I developed a code that takes some information from a spreadsheet each time a user submit a form, and then, send me an email with the information completed. It works really well.
However, I am intending to add a Ticket number in the first column of the sheet (without adding it in the google form) but it is not being recognized by my code.

Do you have any clue about how could I add this first column to my email each time I receive a new submit?
I attach my code.

function formSubmitReply(e) {

  // VARIABLES
    var ticketNo;
    var alUser = e.values[1];
    var country = e.values[3];
    var language = e.values[2];
    var category = e.values[4];
    var title = e.values[5];
    var questions = e.values[6];
    var attach = e.values[7];
    var entityEn = e.values[8];
    var categoryEn = e.values[9];
    var titleEn = e.values[10];
    var questionsEn = e.values[11];
    var attachEn = e.values[12];

    var userEmail = "nam.hr@airliquide.com";

    var msgFr =
  // Add table style and format the cells with th and tr
  "
" +
    "
" +
      "Employé AL	" +
      "Sélection du pays	" +
      "Langue préférée	" +
      "Catégorie	" +
      "Sujet	" +
      "Contenu de la demande	" +
      "Pièce jointe	" +
      "#	" +
    "
" +
    "
" +
      "" + alUser + "	" +
      "" + country + "	" +
      "" + language + "	" +
      "" + category + "	" +
      "" + title + "	" +
      "" + questions + "	" +
      "" + attach + "	" +
      "" + ticketNo + "	" +
    "
" +
  "
";

var msgEn =

  // Add table style and format the cells with th and tr
  "
" +
    "
" +
      "AL user	" +
      "Country	" +
      "Preferred Language	" +
      "Category	" +
      "Title	" +
      "Question	" +
      "Attachments	" +
      "#	" +
    "
" +
    "
" +
      "" + alUser + "	" +
      "" + entityEn + "	" +
      "" + language + "	" +
      "" + categoryEn + "	" +
      "" + titleEn + "	" +
      "" + questionsEn + "	" +
      "" + attachEn + "	" +
      "" + ticketNo + "	" +
    "
" +
  "
";

    MailApp.sendEmail({
      to: userEmail,
      subject: 'NAM HR Mailbox | ' + categoryEn + category,
      htmlBody: (language=="English") ? msgEn : msgFr,
      name: alUser,
      replyTo: alUser
    });
}

A: Solution:
You need to add the first column manually in the spreadsheet then add this code to fill up the values every form submit:
function formSubmitReply(e) {
  var ss = SpreadsheetApp.getActive();
  var id = e.range.getRow();
  var startNum = 850; // to start the entries from T0850
  var control = startNum + id - 2;
  var ticketNo = "T"+control.toString().padStart(4,"0");
  ss.getActiveSheet().getRange(id,1).setValue(ticketNo);

  // VARIABLES
    var alUser = e.values[1];
    var country = e.values[3];
    .....

The rest of the code should be the same as with your question.
Sample Output:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change from static array to vector here's my code:
vector<int> Edge[1000000]; //size of array must be very high

scanf("%d%d",&N,&M );
//N = size of workable index numbers for Edge
for( i=1;i<=M;i++){

    scanf("%d%d",&u,&v );
    Edge[u].push_back( v );
}

But as you can see, it's a static array of vectors.
If i change it to this:
vector<vector<int>> Edge;

How can i do that for cycle and pushback? I need to create a vector of N+1 size and each position is also a vector.

A:
I need to create a vector of N+1 size and each position is also a vector.

Considering that you know the size of the external container at compile time, you can also use std::array to store the vectors:
std::array<std::vector<int>, N + 1> Edge;

If you don't know the size at compile time, you could use:
std::vector<std::vector<int>> Edge;

but as a general rule of thumb, tend to avoid vectors of vectors, as they don't usually work nicely.

A: You can construct vectors of a given size by passing an int to their constructor. Then afterwards you can use a loop to initialize the subvectors.
int size;
vector<vector<int>> Edge(size); //Initializes Outer Array to have 'size' elements

for(auto i:Edge)
{
    // i is a vector within Edge
}

The advantage is that you don't have to push back. If you still wanted to push_back in order (not have to track an iterator/int) you could use vector.reserve() instead.


text:
Q: Showing an histogram using opencv or pyplot I have a trained face recognizer.
After doing face_recognizer.getHistograms() I want to show them.
How can I do this?
Thanks ahead!

A: To plot histogram of an image, use you use pyplot.hist:
If you're image is in grayscale where gray scale intensities vary from 0 to 255, use:
from matplotlib import pyplot as plt
plt.hist(img.ravel(), 256, [0,256])

If it's a color image, you can also use opencv's calcHist function:
color = ('b', 'g', 'r')
for i,col in enumerate(color):
    histr = cv2.calcHist([img],[i],None,[256],[0,256])
    plt.plot(histr,color = col)
    plt.xlim([0,256])

The image intensity of each channel should be between [0, 255]

A: It's possible to simulate histogram collection via opencv using the OpenCV-Flow online tool.
See results here:


text:
Q: service mysql start failed on ubuntu Here is my dilemma (somehow similar to this resource and I tried everything, but nothing helped):
root@vuxomys01:~# service mysql status
mysql start/running

When I'm looking for the process:
root@vuxomys01:~# ps ax | grep mysql
2263 pts/0    S+     0:00 grep --color=auto mysql

I checked the logs and /var/log/mysql/error.log is empty, but there is weird stuff in /var/log/syslog ...
root@vuxomys01:~# grep mysql /var/log/syslog
...
Dec  8 15:24:17 vuxomys01 init: mysql post-start process (1963) terminated with status 1
Dec  8 15:24:17 vuxomys01 kernel: [  460.182640] type=1505 audit(1323375857.580:28):  operation="profile_replace" pid=2098 name="/usr/sbin/mysqld"
Dec  8 15:24:17 vuxomys01 init: mysql main process (2102) terminated with status 1
Dec  8 15:24:17 vuxomys01 init: mysql main process ended, respawning
Dec  8 15:24:47 vuxomys01 init: mysql post-start process (2103) terminated with status 1

... and /var/log/daemon.log
root@vuxomys01:~# grep mysql /var/log/daemon.log
...
Dec  8 15:24:17 vuxomys01 init: mysql post-start process (1963) terminated with status 1
Dec  8 15:24:17 vuxomys01 init: mysql main process (2102) terminated with status 1
Dec  8 15:24:17 vuxomys01 init: mysql main process ended, respawning
Dec  8 15:24:47 vuxomys01 init: mysql post-start process (2103) terminated with status 1

Any other ideas would be really appreciated. Thanks in advance!

*

*Eugene.

A: I think you have an infinite loop in the post-start script due to an incomplete migration of MySQL. Check this thread, i'm sure the solution is there.


text:
Q: Excel connection. Issues with data getting into excel-table from SharePoint I'm working on a project for a client. This client uses a form in SharePoint to enter and save data from certain projects into SharePoint lists.
This data is setup to connect to an Excel file, that is working as a report on the data (pivottables, graphs etc).
The connection between the spreadsheet and SharePoint is established. The problem arises when my client enter new columns in SharePoint (to hold new data) to existing (and future) projects. When the Excel file is opened and tables are refreshed to fill in the new data, an error pops up. The error message is in danish, but translated it sounds like this:

The action is not allowed. The action tries to move cells in a table in the spreadsheet.

I reckon this has something to do with the current table doesn't fit the data-structure from SharePoint?
What can I do about this? Does the connection with Excel has to be rebuilt? Or can an automatic solution be set up, so that the Excel table always fits the SharePoint data, even when additional columns with data are added in SharePoint?
I have no experience or expertise with SharePoint, but I'm fairly good at Excel.
Unfortunately I'm not able to upload any file or reveal any SharePoint data, since this is very confidential.
Any help on this subject will be greatly appreciated

A: I take it the Excel file has a data connection to a specific view. Does the Excel table have any calculated columns appended to the imported table? If new SharePoint columns are added to the view used by the connection, this could be the reason for the error.
If you do NOT have any Excel calculations in the table:
In SharePoint, try to place any new columns of the list after already existing columns in the view that is used for the export. This way, the Excel table will simply need to expand to the right and no existing data will be touched.
Inserting new columns between two existing columns may cause problems.
If you DO have Excel calculations in the table, you may need to temporarily remove the calculated columns, then refresh the data connection to accommodate new columns and then put the calculated table columns back into the table.


text:
Q: Apache Storm : maximum tuple size What is the maximum tuple size Apache Storm can handle (if any)?
I couldn't find any information about this in official Storm documentation, which leads me to think there is no limit (beside the heap size of course). On the storm-user mailing list, I found a thread asking about this, but it turned out the user's error was due to a serialization issue.
My topolgy needs to process tuples of a few megabytes and send them to Kafka. I'm currently hitting Kafka limit of 1MB, but before working on it, I want to know if there is any limit on Storm's side.

A: I don't believe there's a limit. Storm uses either Java serialization (not recommended for production workloads, but useful for prototyping) or Kryo to send tuples between workers.


text:
Q: Syncfusion is causing build errors after migrating to AndroidX on Xamarin Forms I am getting build errors after migrating my Xamarin Forms project to AndroidX.  The errors are all dependency references in several packages:
Can not resolve reference: `Xamarin.Android.Support.v7.RecyclerView`, referenced by `Syncfusion.SfAutoComplete.Android`. Please add a NuGet package or assembly reference for `Xamarin.Android.Support.v7.RecyclerView`, or remove the reference to `Syncfusion.SfAutoComplete.Android`.    Voltsec.Android
Can not resolve reference: `Xamarin.Android.Support.Compat`, referenced by `Syncfusion.SfListView.XForms.Android`. Please add a NuGet package or assembly reference for `Xamarin.Android.Support.Compat`, or remove the reference to `Syncfusion.SfListView.XForms.Android`.    Voltsec.Android
Can not resolve reference: `Xamarin.Android.Support.SwipeRefreshLayout`, referenced by `Syncfusion.SfPullToRefresh.XForms.Android`. Please add a NuGet package or assembly reference for `Xamarin.Android.Support.SwipeRefreshLayout`, or remove the reference to `Syncfusion.SfPullToRefresh.XForms.Android`.  Voltsec.Android
Can not resolve reference: `Xamarin.Android.Support.v4`, referenced by `XLabs.Forms.Droid`. Please add a NuGet package or assembly reference for `Xamarin.Android.Support.v4`, or remove the reference to `XLabs.Forms.Droid`.  Voltsec.Android
Can not resolve reference: `Xamarin.Android.Support.v7.AppCompat`, referenced by `Syncfusion.Buttons.XForms.Android`. Please add a NuGet package or assembly reference for `Xamarin.Android.Support.v7.AppCompat`, or remove the reference to `Syncfusion.Buttons.XForms.Android`.  Voltsec.Android
Can not resolve reference: `Xamarin.Android.Support.v7.RecyclerView`, referenced by `Sharpnado.Presentation.Forms.Droid`. Please add a NuGet package or assembly reference for `Xamarin.Android.Support.v7.RecyclerView`, or remove the reference to `Sharpnado.Presentation.Forms.Droid`.

It looks like the offenders are Syncfusion, XLabs and Sharpnado.
I am not completely sure how to resolve this issue.  Here are the packages I currently have installed on my Android project:
    <PackageReference Include="Autofac">
      <Version>5.1.2</Version>
    </PackageReference>
    <PackageReference Include="Newtonsoft.Json">
      <Version>12.0.3</Version>
    </PackageReference>
    <PackageReference Include="Plugin.CurrentActivity">
      <Version>2.1.0.4</Version>
    </PackageReference>
    <PackageReference Include="Plugin.Permissions">
      <Version>6.0.0-beta</Version>
    </PackageReference>
    <PackageReference Include="Refit">
      <Version>5.1.54</Version>
    </PackageReference>
    <PackageReference Include="Rg.Plugins.Popup">
      <Version>1.2.0.223</Version>
    </PackageReference>
    <PackageReference Include="RtspClientSharp">
      <Version>1.3.3</Version>
    </PackageReference>
    <PackageReference Include="Sharpnado.Presentation.Forms">
      <Version>1.4.0</Version>
    </PackageReference>
    <PackageReference Include="Syncfusion.Xamarin.Buttons">
      <Version>18.1.0.42</Version>
    </PackageReference>
    <PackageReference Include="Syncfusion.Xamarin.SfAutoComplete">
      <Version>18.1.0.42</Version>
    </PackageReference>
    <PackageReference Include="Syncfusion.Xamarin.SfBusyIndicator">
      <Version>18.1.0.42</Version>
    </PackageReference>
    <PackageReference Include="Syncfusion.Xamarin.SfChart">
      <Version>18.1.0.42</Version>
    </PackageReference>
    <PackageReference Include="Syncfusion.Xamarin.SfListView">
      <Version>18.1.0.42</Version>
    </PackageReference>
    <PackageReference Include="Syncfusion.Xamarin.SfPullToRefresh">
      <Version>18.1.0.42</Version>
    </PackageReference>
    <PackageReference Include="Xam.Plugin.DeviceInfo">
      <Version>4.2.0-beta</Version>
    </PackageReference>
    <PackageReference Include="Xam.Plugin.Media">
      <Version>5.0.1</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.Core">
      <Version>1.2.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.SwipeRefreshLayout">
      <Version>1.0.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.Legacy.Support.V4">
      <Version>1.0.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.AppCompat">
      <Version>1.1.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.CardView">
      <Version>1.0.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.RecyclerView">
      <Version>1.1.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.AppCompat.Resources">
      <Version>1.1.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.Lifecycle.LiveData">
      <Version>2.2.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.MediaRouter">
      <Version>1.1.0</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.AndroidX.Migration">
      <Version>1.0.3</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.Essentials">
      <Version>1.5.2</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.FFImageLoading">
      <Version>2.4.11.982</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.FFImageLoading.Forms">
      <Version>2.4.11.982</Version>
    </PackageReference>
    <PackageReference Include="Xamarin.Forms" Version="4.6.0.529-pre3" />
    <PackageReference Include="Xamarin.Google.Android.Material" Version="1.1.0-rc3" />
    <PackageReference Include="XLabs.Forms">
      <Version>2.3.0-pre05</Version>
    </PackageReference>

I am targeting Android 10.0(Q)
Any suggestions to try?

A: To resolve the compilation error related to syncfusion controls , you can add the below packages in android project
Xamarin.Android.Support.v7.RecyclerView
Xamarin.Android.Support.Compat
Xamarin.Android.Support.SwipeRefreshLayout
Xamarin.Android.Support.v7.AppCompat

A: Try using Android 9 as Target Framework. I faced the same issue today and after setting Target Framework to Android 9 (it was Android 10) everything magically started building.
Also I've reported it to syncfusion support. I'll update this answer when they respond.
UPDATE: Response from syncfusion support

We would like to let you know that our buttons (SfButton,
SfCheckBox,SfRadioButton,SfSegmentedConntrol,SfChipGroup,SfChip)
controls are compatible with AndroidX support. But currently we are
facing this problem related with dependent package of AppCompat.
We have planning to upgrade our source control XF to the latest for
resolving this dependent package issue that will be available in our
Volume 3,2020 release.
To resolve this, now, please add the
required NuGet package manually.
Manually install Xamarin.Android.Support.v7.AppCompat

UPDATE 2: Issue is now resolved. Syncfusion no longer requires support Nugets


text:
Q: Azure Search doesnt work when searching by text using dot as a second last character in a wild card search IN Azure search when searching for a name within the index record if you end up putting a dot at the end of the search term, the search logic cannot find the item even if it exists. (Please note we are appending wildcard at the end of all search term.)
For e.g. if we have a indexed record with a name companyltd. and we run a query as shown below
        _index.Documents.SearchAsync<testDto>("companyltd*", new SearchParameters());

This returns the record with a name companyltd.
However if we run the query
       _index.Documents.SearchAsync<testDto>("companyltd.*", new SearchParameters());

It cannot find the record with the name companyltd.
Could someone please explain why this is the case and what should the search query be like to get the result back as expected?


text:
Q: Host Office apps in a WPF Application I am currently working on a project that requires a text editor. All of the computers that will be running this app will have the whole office suite installed, more specifically Office365.
I started building my own text editor but it would take a lot of time to implement some QOL Microsoft Word has so I started looking up ways to somehow host Microsoft Word inside a WPF Window or at least make it look like it is docked. So far I have found stuff from 10+ years ago mentioning OLE and what not but I figured it is probably way outdated.
Can anyone here please point me in the right direction ?

A: You can't host Office365 product in your app, Microsoft does not offer such a service.
Since you want a text editor, you can look for off-the-shilf products like avalonEdit:TextEditor, download it via NuGet and use it in your view just like this..
<avalonEdit:TextEditor
    xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
    Height="400"
    FontFamily="Consolas"
    FontSize="12pt" />

Another lovely open source WPF-based text editor is Notepads, but there is no ready-to-use usercontrol similar to avalonEdit:TextEditor. You have to include it in your solution as a class library then embed it in your windows application (can't predict how much effor/time can it take).


text:
Q: Cant figure out stacking order issue on Chrome My collapsed dropdown menus are being hidden behind a sequence.js slider on Chrome and Safari.  Issue doesn't appear to be happening on Firefox.  Tried changing z-index on just about every object related to slider and menu.  Much love to anyone who can inspect my site and tell me what I am doing wrong.
https://www.shopinspired.co/

A: It's not actually being hidden behind the slideshow.
This is due to the "sticky" class being removed from your header when you scroll to the top of the page.  If #header always has .sticky, the menu shows fine.
It looks like your styles at the top of the page are targeting "header.sticky", not just "header".
Fix: Manually add the css:
#header {
  position: fixed;
  left: 0;
  right: 0;
  top: 0px;
  box-shadow: 0 5px 5px -5px #333;
}

or change the CSS in the page head to target "header".

A: Explanation
Its is coming from the sticky header and a mismatch of positioned objects and forced heights.
By default, without the sticky header, the submenu is being hidden because it is a child element of a parent with a forced height due to some media queries. The overflow is being hidden.
When the sticky header is added, the header gets a position of fixed. You can not use absolute positioning relative to fixed elements. I am guessing your element is being positioned relative to the document window which is why it is now showing with the fixed attribute.


text:
Q: Python: Pass `gridlines=false` when downloading a PDF using `export_media` (Google Drive API) I've followed the Drive API v3 docs to Download a Google Document.  I am able to sucessfully download a spreadsheet in PDF format, as per the example, building the request as follows:
from googleapiclient.discovery import build

drive_service = build('drive', 'v3', credentials=creds)

SPREADSHEET_ID = 'mySpreadSheetID'
request = drive_service.files().export_media(fileId=SPREADSHEET_ID,
                                             mimeType='application/pdf',
                                             )

I wish to pass the custom params from this answer as part of the request, specifically to set gridlines=false.
I found from the docs for googleapiclient.http.HttpRequest that I can inspect the request further with:
request.to_json()

which gives me:
('{"uri": '
 '"https://www.googleapis.com/drive/v3/files/mySpreadSheetID/export?mimeType=application%2Fpdf&alt=media", '
 '"method": "GET", "body": null, "headers": {"accept": "*/*", '
 '"accept-encoding": "gzip, deflate", "user-agent": "(gzip)", '
 '"x-goog-api-client": "gdcl/1.7.11 gl-python/3.7.4"}, "methodId": '
 '"drive.files.export", "resumable": null, "response_callbacks": [], '
 '"_in_error_state": false, "body_size": 0, "resumable_uri": null, '
 '"resumable_progress": 0}')```

I suspect &gridlines=false needs to be appended to the uri before the request is made, however I'm unsure how to modify this.
Am I on the right track, and if not, is there another way to pass these parameters from the Python library?

A: *

*You want to export the Google Spreadsheet as a PDF file.

*You want to use the query parameter of gridlines=false.

*You want to achieve this using python.

*Your access token can be used for exporting the Google Spreadsheet.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Modification point:

*

*In this modification, the PDF file with gridlines=false is exported by directly modifying the endpoint of requests.

Modified script:
SPREADSHEET_ID = "###"  # Please set the Spreadsheet ID.

drive_service = build('drive', 'v3', credentials=creds)
request = drive_service.files().export_media(fileId=SPREADSHEET_ID, mimeType='application/pdf')

# Here, the endpoint is modified.
request.uri = "https://docs.google.com/spreadsheets/d/" + SPREADSHEET_ID + "/export?format=pdf&gridlines=false"

fh = io.FileIO('sample.pdf', mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print('Download %d%%.' % int(status.progress() * 100))

*

*In this case, you can also use request = drive_service.files().export_media(fileId="", mimeType=""). Because the endpoint is modified.

If I misunderstood your question and this was not the direction you want, I apologize.


text:
Q: Is it possible to add HTTP headers to a Socket.io handshake? I'm trying to secure the channel between my socket.io client and the node.js side. The main web application is in Drupal so I can't pass the cookies to node.js if node.js is on another host. I'd like to add some custom headers to he Socket.io HTTP handshake (like the PHP session).
Do you know if it is possible?
Using Socket.io 0.7

A: P.S: I am just brainstorming here a little bit. I like this problem and am going to think a little bit more about this. I only thought about it yet from node.js same domain only...
Github issue
I don't know(don't think so) if it is possible to add headers.
P.S: I think you should also try to fill issue at https://github.com/LearnBoost/socket.io/issues. The nice thing about github is that author will receive an email when somebody posts an issue. Also the people at learnboost are really nice people who like to help you out.
Proxy
Proxy all your request so that request come from same domain.
Refererer
The refererer is passed so you can pass information from this. This can also be spoofed so you better create something you can validate(only once) from Drupal. I guess this would be pretty easy to implement...
only allow message-flowing after verification.
What I know you can do is disconnect sockets via socket.disconnect(). Open connection and retrieve socket.io's id, but only accept messages after identity has been approved. I would make a route available via express which Drupal can curl post socket.io's id to to (keep route private). Because you are inside Drupal's domain you can access Drupal's session information.
// v0.7.x
var sid = socket.id;

To make this secure the only option is to use SSL(that is the only way you can make any communication link secure anyway). If you trust both domain's SSL is probably not really necessary. Then if socket.io's id is allowed you will allow message-flowing else I would just disconnect the connection.
PusherApp
Another option would be to implement/clone pusherapp authentication => http://pusher.com/docs/client_api_guide/client_channels#subscribe-private-channels

P.S: I will to try and upload an example later, but for now it is time for me sleep. Hopefully this made any sense :)...


text:
Q: Configuring .htaccess for React+Vite in Cpanel I created a project in React.js and Vite.js and I want to deploy it using CPanel, but when get the content of the dist folder out to the root the app doesn't get .env variables, so I figured out that I need to keep content of dist folder inside of it and create .env outside for the app to recognize it.
But I couldn't figure out a way to configure .htaccess file to reference the files inside dist.
folder structure I have in Cpanel file manager
dist
| |___assets
| |___index.html
|
|__.env
|__.htaccess

I need some help please to get .htaccess to work or .env to be recognized


text:
Q: How to ignore null array elements with Newtonsoft JSON serializer I'm attempting to serialize an object array, but I need it to ignore null elements. I realize I could simply have logic upon deserialization that checks for the nulls, however I don't want to write unnecessary data over the network. The array can have a maximum of 9 elements, but all 9 indices are not used in every instance. I understand that a list could be utilized, but for efficiency sake I do not wish to do that.
Per similar questions I've browsed on this site, I've attempted to add the following tag to the array: [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
However, this approach does not ignore null elements.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Node[] Nodes { get; }
public void Init()
{
    Nodes = new Node[9];
}
public string Encode()
{
    return JsonConvert.SerializeObject(Nodes, Formatting.None);
}

Is there an elegant solution to this?

A: The simplest solution is just to filter the array just before you serialize it.  You can do this in your Encode method, without instantiating a new array:
public string Encode()
{
    return JsonConvert.SerializeObject(Nodes.Where(n => n != null), Formatting.None);
}

Fiddle: https://dotnetfiddle.net/dj8lnP
If you don't like that idea, for whatever reason, you can use a custom JsonConverter similar to  the one in Excluding specific items in a collection when serializing to JSON to do the filtering.


text:
Q: Windows 8.1 - Setting zoom levels via CSS So ever since I upgraded to 8.1, all of my sites have been showing up way zoomed in.  I was wondering if there was a CSS value I could set to always ensure the proper zoom level is set.  Thanks.

A: You can use the zoom property
body { zoom:0.9; -moz-transform: scale(0.9); }

As mentioned, Firefox doesn't support zoom so use -moz-transform instead.


text:
Q: Chai as promised not waiting for promise to be fulfilled An output of my console. Note that the console logs are out of order (1,3,4,2 instead of 1,2,3,4)

Code here
  it('can store file', () => {
    console.log('1) file storage start')
    return filestore.store.q(file).then(() => {
      console.log('2) file storage done')
    }).should.eventually.be.fullfilled
  })

  describe('block number', () => {

    beforeEach(() => {
      console.log('3) check blockNumber')
      return web3.Q.all([
        web3.eth.getBlockNumber.q().then((_blockNumber) => {
          blockNumber = _blockNumber
        }),
        web3.eth.getMining.q().then((isMining) => {
        })
      ])
    })

    it('can retreive files block number', () => {
      console.log('4) retreive')
      return filestore.getBlockNumber.q(fileHash).should.eventually.bignumber.equal(blockNumber)
    })

  })

A: This turned out to be a stupid typo. I typed fullfilled instead of fulfilled

A: I suspect you are getting a side-effect from Chai. Try testing without it first, for example:
const assert = require('assert');

it('can store file', () => {
    console.log('1) file storage start')
    return filestore.store.q(file).then(() => {
      // Promise should have fulfilled. Nothing more to do.
      // Using should and chai after this is probably causing the problem.
      // But you should really add some sort of assertion here to
      // be able to detect regressions.
      console.log('2) file storage done')
    });
  });

  describe('block number', () => {
    let blockNumber;

    beforeEach(() => {
      console.log('3) check blockNumber')
      return web3.Q.all([
        web3.eth.getBlockNumber.q().then((_blockNumber) => {
          blockNumber = _blockNumber
        }),
        web3.eth.getMining.q().then((isMining) => {
        })
      ])
    })

    it('can retreive files block number', () => {
      console.log('4) retreive')
      return filestore.getBlockNumber.q(fileHash)
        .then((result) => {
          // I'm not sure if assert.equal will work with big numbers.
          // You might need a different comparator here.
          assert.equal(result, blockNumber, 'should equal the blocknumber));
        });
    });
  });

Mocha knows how to handle a returned Promise so there's really no need for Chai. It's unnecessary sugar.


text:
Q: how event with if condition works in javascript? if(document.getElementById("ready_1").innerHTML && document.getElementById("ready_2").innerHTML =="Wait.."){
            document.getElementById("start").style.color = "black";
        }

I want to make #start black if #ready_1 & #ready_2's innerHTML == "wait.."
not using jQuery.

A: if ( (document.getElementById("ready_1").innerHTML == "Wait") &&
      (document.getElementById("ready_2").innerHTML =="Wait..") ){
            document.getElementById("start").style.color = "black";
}

Like that?
Note that you used "wait.." in your explanation, and "Wait.." in your code.

A: Maybe this solution is cleaner:
var firstReady = document.getElementById("ready_1").innerHTML;
var secondReady = document.getElementById("ready_2").innerHTML;

if (firstReady === secondReady && secondReady  === "Wait..") {
  document.getElementById("start").style.color = "black";
}


text:
Q: Create CIImage from CVImageBufferRef I am trying to create a CIImage object from CVPixelBuffer, everything went well up to step 3.
But in step 4:
[[CIImage alloc] initWithCVPixelBuffer:imageBuffer options:(__bridge_transfer NSDictionary *)attachments]

returns nil.
So please give me solution for my problem....Thanks in advance.
CMSampleBufferRef sampleBufferRef = [readerVideoTrackOutput copyNextSampleBuffer];

CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

CFDictionaryRef attachments = CMCopyDictionaryOfAttachments(kCFAllocatorDefault,
                            sampleBuffer, kCMAttachmentMode_ShouldPropagate);
CIImage *image = [[CIImage alloc] initWithCVPixelBuffer:imageBuffer options:(__bridge_transfer NSDictionary *)attachments];


text:
Q: JSON Schema - Apply a definition to an array conditionally? I need to apply a validation to an array, based on a property from a parent object. ex:
{
    "data": [{
        "account": {
            "type": "special"
        },
        "customers": [{
            "email": "test@test.com",
            "phoneNumbers": [
                "913 449-6602"
            ]
        }]
    }]
}

If account === 'special', then email and phoneNumbers need to be present inside customers. (email != null, and phoneNumbers.length > 1. no regex validation necessary)
else, i dont care.
I've sifted through dozens of previous questions and haven't found anything that solves this use case.
I am curious if applying a definition conditionally is possible? ex: Apply one definition when account.type is "special", another when it isn't. I don't think "If-then-contains" works, since I need the validation applied to ALL customers, not just one.
thanks in advance and let me know if more clarification needed.
relevant Q's that helped:
jsonSchema attribute conditionally required depends on parent object
jsonSchema attribute conditionally required

A: You can apply a condition to all items - just wrap it in the items keyword:
{
  "if": {
    "required": ["account"],
    "properties": {
      "account": {
        "required": ["type"],
        "properties": {
          "type": { "const": "special" }
        }
      }
    }
  },
  "then": {
    "required": ["customers"],
    "properties": {
      "customers": {
        "type": "array",
        "items": {
           ... check email and phoneNumbers here ...
        }
      }
    }
  }
}

In pseudocode: if the account type is "special", then apply the extra definition to all customer items.
More info here:

*

*https://json-schema.org/understanding-json-schema/reference/conditionals.html

*https://json-schema.org/understanding-json-schema/reference/array.html


text:
Q: transpose array using malloc I think I my code was right but I still can not transpose my array
do I code right for the variable of malloc transpose?
int *arr = (int *)malloc(r * c * sizeof(int));
int *transpose = (int *)malloc(c * r * sizeof(int));

this is my input:
for (i = 0; i < r; i++) {
    for (j = 0; j < c; j++) {
        cout << "Element at x[" << i << "][" << j << "] : ";
        cin >> *(arr + i * c + j);
    }
}

does the transpose code right?
for (i = 0; i < r; i++) {
    for (j = 0; j < c; j++) {
        *(transpose + j + i * c) = *(arr + i * c + j);
    }
    cout << endl;
}

and the print code was it right?
cout << endl << "transpose : " << endl;
for (i = 0; i < c; i++) {
    for (j = 0; j < r; j++) {
        cout << *(transpose + i * c + j ) << " ";
    }
    cout << endl;
}

A: Both the transpose and print are wrong.
+ j + i*c and + i*c + j are equivalent in adding integers to pointers, just the order is swapped.
It seems the original array has r rows and c columns, so the transposed array will have c rows and r columns.
One column of transposed array will have r elements, so r, not c, should be multiplied to the row index of transposed array.
Therefore, transpose should be
for(i=0; i<r; i++){
    for(j=0; j<c; j++){
        *(transpose + j*r + i)=*(arr + i*c + j);
    }
    cout<<endl;
}

and printing should be
cout<<endl<<"transpose : "<<endl;
for(i=0; i<c; i++){
    for(j=0; j<r; j++){
        cout<<*(transpose + i*r + j )<<" ";
    }
    cout<<endl;
}


text:
Q: How can seq evaluate an inifinite list in Haskell? It is said that the Haskell seq function forces the evaluation of its first argument and returns the second. It is used to add strictness to evaluation of expressions. So how can the following simply return 5:
seq [1..] 5

Shouldn't it get stuck in trying to construct an infinite list?

A: seq evaluates to weak head normal form (WHNF), which essentially means it evaluates one layer of data constructors. In this case, it means that it forces evaluation of the first cons cell (the : data constructor).
I have a pretty long post explaining details around this at https://haskell.fpcomplete.com/tutorial/all-about-strictness


text:
Q: When does a type get promoted to an unsigned int? This article says:

If all values of the original type can be represented as an int, the
  value of the smaller type is converted to an int; otherwise, it is
  converted to an unsigned int

All values of signed/unsigned char and signed/unsigned short can be represented as an int, so when does a type gets promoted to an unsigned int?

A: A short cannot be longer than an int but on some platforms it may be the same size. The same goes for int and long. This means that if the "smaller" one is unsigned, the "larger" one must be too.

A: The article is using sloppy terminology. The source type doesn't have to be "smaller" than int. Here is what the C++11 standard says:

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion
  rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all
  the values of the source type; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.

There are platforms on which, say, unsigned short and int are both 16 bits long. Nevertheless, unsigned short has lower rank than int by definition and is subject to integral promotion. In this case, int cannot represent all values of type unsigned short, so the promotion is to unsigned int.
Edit: C99 has similar wording:

The following may be used in an expression wherever an int or unsigned int may
  be used:

*

*An object or expression with an integer type whose integer conversion rank is less
  than or equal to the rank of int and unsigned int.

*A bit-field of type _Bool, int, signed int, or unsigned int.

  If an int can represent all values of the original type, the value is converted to an int;
  otherwise, it is converted to an unsigned int. These are called the integer
  promotions. 48) All other types are unchanged by the integer promotions.

A: well, if sizeof(char) == sizeof(int), then unsigned char shall be promoted to unsigned int


text:
Q: PCA with "zero-spike" variables I have a large number of predictors that are hypothesized to be important in determining my binary outcome variable (here's a bit more about my goal, the predictors and the outcome).  The problem is that considering the number of "positive cases" that I have, I have too many predictors (I have about 450 cases in total, about 100 positive cases, and more than 20 predictors.)
I'd like to use PCA to reduce my data, but many of my predictors are non-negative with a spike at zero and a long tail. For instance, the value for "the number of cigarettes per day smoked in the past 30 days" is zero for about 75% of the respondents and 99+ for a few.
I understand that there's nothing conceptually wrong with using PCA with such variables. But PCA finds the directions of maximum variance in data and I'm not sure that variance is the right measure of dispersion for this kind of data. (These variables also cause all sorts of errors and warnings to be generated when I use other data reduction software.)
I'd like to find a non-response-variable-driven way to deal with these variables. What I've tried already is to use $x \rightarrow log(x + 1)$ transformation followed by restricted cubic spline transforms (as implemented by $transcan$ function in Hmisc package in R), but they don't improve the situation much.  I've seen this paper by Royston et al. that explicitly deals with this problem, but their approach is response-variable driven, which is something I'd like to avoid.
I'd love to hear everyone's thoughts, experiences, and suggestions.
Thanks!


text: Q: Classification of surface curves? Having a genus $g$ closed orientable surface $\Sigma$ (connected sum of $g$ tori), how do I encode any embedded closed curve up to planar isotopy? For $g=1$ we can just state the coefficient $k \in \mathbb{Q} \cup \{\infty\}$, i.e. the coefficient of the line on the fundamental square (or as the $p/q$-curve. But how to do so for a general surface? Is this connected to the mapping class group $MCG(\Sigma)$?


text:
Q: Code Igniter 2 Libraries Email got error Good Evening,
I'm using CodeIgniter 2 on IIS 8.5 and MSSQL Server,
When i tried to send an email in the process, it shows the error:

Severity: Notice
Message: A non well formed numeric value encountered
Filename: libraries/Email.php
Line Number: 1689

I've been using this code for some projects in the same server, and it's working properly. But when i tried to implement on this one it always shows this error everytime there's sending email process.
And here's my controller:
function reset_pass() {
    if (!IS_AJAX) {
        display_nonajax_stop();
        exit;
    } else {
        $settings = $this->m_setting->get_setting_array();
        $min_pass_length = (int) $settings["acc_pass_min_length"];
        $data = $this->input->post();
        $id = $data['id'];
        $hasil = array();

        $kondisi = array(
            "usr_id" => $id
        );
        $current_time = waktu_sekarang();
        $baris = $this->m_ess->get_user_employee_row($kondisi);
        $user = $baris;
        if ($user->usr_email === NULL) {
            $hasil['pesan'] = "User  does not have valid email associated . Please contact Administrator.";
            $hasil['status'] = 0;
        } else {
            $this->load->helper('email');
            if (!valid_email($user->usr_email)) {
                $hasil['pesan'] = "User does not have valid email associated . Please contact Administrator.";
                $hasil['status'] = 0;
            } else {

                $hasil['pesan'] = "Username and email is ok";
                $hasil['status'] = 0;

                $this->load->library('rndconditionpass');
                $tmppass = $this->rndconditionpass->get_random_string($min_pass_length);
                $new_password = $this->bcrypt->do_hash($tmppass);

                $mail_data['random'] = $tmppass;
                $mail_data['username'] = $user->usr_name;
                $mail_data['full_name'] = $user->emp_name;
                $mail_data['password'] = $tmppass;

                //prepare data to be used in leo_mail library
                $param = array();
                $param['recipient'] = $user->usr_email;
                $param['content'] = $this->load->view("template/mail/mail_reset_pass", $mail_data, TRUE);
                $param['subject'] = "Reset Password";

                $this->load->library('leo_mail');
                $kirim = $this->leo_mail->kirim($param);

                if ($kirim['status'] == 1) {

                    #password history
                    $insert_pass = array(
                        "pas_usr_name" => $user->usr_name,
                        "pas_password" => $new_password,
                        "pas_date" => $current_time,
                        "pas_opid" => $this->session->userdata("usr_name"),
                        "pas_update" => $current_time
                    );
                    $this->m_pass->insert_pass($insert_pass);

                    $hasil['pesan'] = "Password has been reset and user has been notified via email. ";
                    $hasil['status'] = 1;
                    //update the database, store the reset code
                    $update = array();
                    $update['usr_last_cpass'] = date("Y-m-d H:i:s");
                    $update['usr_needchgpwd'] = "Y";
                    $update["usr_password"] = $new_password;

                    $kondisi = array("usr_name" => $user->usr_name);
                    $q = $this->m_ess->update_user($update, $kondisi);
                } else {
                    $hasil['pesan'] = "Fail to send email your password reset code.";
                    $hasil['status'] = 0;
                }
            }
        }

        echo json_encode($hasil);
    }
}

and here's the '$this->leo_mail->kirim function
function kirim($param) {

        $q=$this->ci->m_smtp->get_mail_konfig();
        $hasil=array();
        if($q->num_rows()<1) {
            $hasil['pesan']="Your SMTP configuration has not been set up properly";
            $hasil['status']=0;
        } else {
            if(valid_email($param['recipient'])) {
                $config=array();
                $config_data= $q->row();
                $config['protocol'] = "smtp";
                $config['useragent'] = "HRISSMTPLIB";
                $config['smtp_port'] = $config_data->smt_smtp_port;
                $config['smtp_host'] = $config_data->smt_smtp_host;
                $config['smtp_user']= $config_data->smt_smtp_user;
                $config['smtp_pass']= $this->ci->leo_enkripsi->decrypt($config_data->smt_smtp_pass,$this->key);

                $config['newline']="\r\n";
                $config['wordwrap'] = FALSE;
                $config['starttls']=($config_data->smt_encrypt_type==3)?TRUE:FALSE;
                $config['mailtype'] = "html";

                $this->ci->email->initialize($config);
                $this->ci->email->from($config_data->smt_email,$config_data->smt_name);
                $this->ci->email->to($param['recipient']);

                $this->ci->email->subject($param['subject']);
                $this->ci->email->message($param['content']);

                if($this->ci->email->send()) {
                     $hasil['pesan']="Email sent";
                     $hasil['status']=1;
                } else {
                     $hasil['pesan']= $this->ci->email->print_debugger();
                     $hasil['status']=0;
                }
            } else {
                $hasil['pesan']="Recipient email is not valid";
                $hasil['status']=0;
            }
        }
        return $hasil;
    }

Sorry for my bad english.
Thank you in advance.


text:
Q: How to return sum of two highest value in List in most efficient way? C# I'm trying to pass a pre-written test with focus on performance. What is the most efficient way to return the sum of the two highest numbers in a List of int? I have tried the following and according to the test it wasn't fast enough when it comes to larger lists:
1.  list.Sort();
    list.Reverse();
    return list[0] + list[1];

2.  return list.OrderByDescending(num => num).FirstOrDefault() + list.OrderByDescending(num => num).Skip(1).FirstOrDefault();

3.  var secondHighest = list.Distinct()
                            .OrderByDescending(i => i)
                            .Skip(1)
                            .First();

    return list.Max() + secondHighest;

A: Any straightforward sorting operation would be O(n*log(n)) (OrderBy(Descending), Sort) at best (on random data) though current task is achievable in O(n) with a simple loop (assuming there are at least 2 items in the list of course, for the case when there are 2 or less elements just return list.Sum()):
var first = int.MinValue;
var second = int.MinValue;
foreach(var i in list)
{
    if(i > first)
    {
        second = first;
        first = i;
    }
    else if(i > second)
    {
        second = i;
    }
}

var result = first + second;

Also it worth noting that there can be implementation depended LINQ optimizations for some of cases like combination of OrderBy(Descending)with operators like First(OrDefault) or possibly Take (see one, two, three).

A: Well, I'm proposing this algorithm:
highest = 0
highestSet = false
secondHighest = 0
secondHighestSet = false
foreach item in list
    if item >= highest or !highestSet
        if highestSet
          secondHighest = highest
        highestSet = true
        highest = item
    else if item >= secondHighest or !secondHighestSet
        secondHighestSet = true
        secondHighest = item

return highest + secondHighest

Input set of [3, 2, 3, 2], it will return 6. This is O(n) time complexity.
For a set of [3], it will return 3.

A: LINQ can be a very good solution for it.
long sum = 0;
if(list.Count > 1)
  sum = list.OrderByDescending(z=>z).Take(2).Sum();
else
  sum = list.Sum();

A: You can try this simple way:
list.Sort();
list.Reverse();
var secondHighest=list.Take(2).Sum();

return secondHighest;

or
 list=list.OrderByDescending(o=>o).ToList();
 var secondHighest=list.Take(2).Sum();

return secondHighest;

At first, it sorts your list, then reverses it , now you have descending sorted list , than it will take 2 highest elements and aggregate them .


text:
Q: Perl: Checksum of complex data-structure Is there a package/function in Perl that gives me in an easy way

*

*a short information (e.g. a number, short string)

*like a hashvalue/checksum (e.g. MD5)

*with good distinction (e.g. cryptographic hash like MDx, SHAx)

*representing the content of a complex datastructure (e.g. hash of arrays of hashes).

Best idea I have in mind is

*

*serialize my structure to a string (e.g. with Data::Dumper)

*Hash over the string with MDx
But maybe there is some more elegant way.

A: In the past, I used the Data::Dumper (with sorted keys, as pointed by @mob) + Digest::MD5 approach for creating checksums of complex data structures. In my case, the purpose was to compare two or more data structures for equality.
(Very) Simple snippet:
use Data::Dumper qw( Dumper ) ;
use Digest::MD5 qw( md5_hex) ;

sub digest {
    my $data = shift ;
    local $Data::Dumper::Sortkeys = 1;
    return md5_hex( Dumper($data) ) ;
}

Synopsis:
my $cplx_data_checksum = digest({
    c => 1 ,
    b => [ 1 , { a => 2 } ]
}) ;

For insights about Digest algo's speed please take a look to the Digest Perl module at https://metacpan.org/pod/Digest#Digest-speed
Hope this helps

A: I would consider using
Sereal Encoder
I've used it for a similar problem and was very happy with it,
it is fast, offers all the options I could think of needing,
and did not take me long to get going at all.
For example, it allows you to choose how to deal with objects,
and whether to sort keys on hashes which can be very useful.
Have fun!


text:
Q: Why go get in a repository with go.work throws warning package is not used in this module? My goal is to create a repository with multiple folders.
|- go.work
|- websocket
|  |- go.mod
|  |- go.sum
|  |- server.go
|- channel
|  |- main.go

The websocket uses github.com/gorilla/websocket package.
So, I need to do in the websocket folder.

*

*$ go mod init github.com/kidfrom/learn-golang/websocket

*$ go get github.com/gorilla/websocket@v1.5.0

*$ go work use .
The problem is, the websocket/go.mod throws warning
github.com/gorilla/websocket is not used in this module

If I do go mod tidy, the websocket/go.mod will be cleaned out and websocket/server.go will throws error
could not import github.com/gorilla/websocket (no required module provides package "github.com/gorilla/websocket")

TLDR
websocket/go.mod
module github.com/kidfrom/learn-golang/websocket

go 1.19

require github.com/gorilla/websocket v1.5.0 // indirect

websocket/go.sum
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=

websocket/server.go
go.work
go 1.19

use (
    ./websocket
)

A: First, make sure your server.go is in package main, as the original gorilla/websocket/examples/echo/server.go is.
Second, test if the name of the folder (which is also websocket) is an issue (conflicting with the websocket.xxx calls).
For testing, try and change it (and update go.work accordingly)


text:
Q: UIView and UITableView I'm having trouble trying to code in my tableView. I'll explain... I'm using storyboard and want to make an RSS Feed into my 2nd tab. I'm running through Ray W's tutorial for RSS Feed found here RSS Tutorial

I'm almost finished with the ASIHTTPRequest part of the tutorial and am up to the point where I need to write this bit of code
`- (void)requestFinished:(ASIHTTPRequest *)request {
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:request.url.absoluteString
                                           articleTitle:request.url.absoluteString
                                             articleUrl:request.url.absoluteString
                                            articleDate:[NSDate date]] autorelease];
int insertIdx = 0;
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
                      withRowAnimation:UITableViewRowAnimationRight];

}`
My problem is that an error comes up when I type in self.tableView. The error is: **Property 'tableView' not found on object of type 'SecondViewController'
**
The SecondViewController.h file has @interface SecondViewController : UIViewController { so I think that is why the error comes up. When I chance the @interface part to UITableViewController, the error disappears but when I run the project and click on the RSS Feed tab, it will crash with the following error Terminating app due to uncaught exception 'NSInternalInconsistencyException'
Does anyone have a fix for this? Thanks.

A: PLease add tableView as a property in the sendViewController and then set its data source
in view did load as:
add in SecondViewController.h
@property (weak) IBOutlet UITableView *tableView;

add in SecondViewController.h
-(void)viewDidLoad
{
    self.tableView.dataSource = self;
    .
    .
    .
    .
    .// your code here...
}

and finally connect this tableview in your interface builder with the table view..
Hope this Helps.... :)


text:
Q: webpack TS2304 Cannot find name 'Map', 'Set', 'Promise' I have the following webpack.config.js
var path = require("path");
var webpack = require('webpack');

module.exports = {
  entry: {
    'ng2-auto-complete': path.join(__dirname, 'src', 'index.ts')
  },
  resolve: {
    extensions: ['', '.ts', '.js', '.json', '.css', '.html']
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: "[name].umd.js",
    library: ["[name]"],
    libraryTarget: "umd"
  },
  externals: [
    /^rxjs\//,    //.... any other way? rx.umd.min.js does work?
    /^@angular\//
  ],
  devtool: 'source-map',
  module: {
    loaders: [
      { // Support for .ts files.
        test: /\.ts$/,
        loaders: ['ts', 'angular2-template-loader'],
        exclude: [/test/, /node_modules\/(?!(ng2-.+))/]
      }
    ]
  }
};

and the following tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "noEmitHelpers": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "pretty": true,
    "allowUnreachableCode": true,
    "allowUnusedLabels": true,
    "noImplicitAny": false,
    "noImplicitReturns": false,
    "noImplicitUseStrict": false,
    "noFallthroughCasesInSwitch": false,
    "allowSyntheticDefaultImports": true,
    "suppressExcessPropertyErrors": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "dist",
    "baseUrl": "src"
  },
  "files": [
    "src/index.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "buildOnSave": false
}

When I run tsc command as the following, it all works fine.
ng2-auto-complete (master)$ tsc --declaration
ng2-auto-complete (master)$

When I run webpack command, it shows typescript compile errors.
ng2-auto-complete (master)$ webpack
ts-loader: Using typescript@2.0.0 and /Users/allen/github/ng2-auto-complete/tsconfig.json
Hash: bd6c50e4b9732c3ffa9d
Version: webpack 1.13.2
Time: 5041ms
                       Asset     Size  Chunks             Chunk Names
    ng2-auto-complete.umd.js  24.4 kB       0  [emitted]  ng2-auto-complete
ng2-auto-complete.umd.js.map  28.4 kB       0  [emitted]  ng2-auto-complete
    + 11 hidden modules

ERROR in /Users/allen/github/ng2-auto-complete/node_modules/@angular/platform-browser/src/dom/dom_renderer.d.ts
(18,37): error TS2304: Cannot find name 'Map'.

ERROR in /Users/allen/github/ng2-auto-complete/node_modules/@angular/platform-browser/src/dom/dom_adapter.d.ts
(96,42): error TS2304: Cannot find name 'Map'.

ERROR in /Users/allen/github/ng2-auto-complete/node_modules/@angular/platform-browser/src/web_workers/worker/location_providers.d.ts
(21,86): error TS2304: Cannot find name 'Promise'.
...
ng2-auto-complete (master)$

I don't know what I am missing for webpack and typescript compilation.
node_modules has been excluded in tsconfig.json
"exclude": [
    "node_modules"
  ],
and type definitions are there in node_modules
  "devDependencies": {
    "@types/core-js": "^0.9.32",
    "@types/node": "^6.0.31"

I also tried to use typings.json and typings directory without success.
{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160815222444"
  }
}

FYI, versions
$ node --version
v5.7.1
$ npm --version
3.6.0
$ tsc --version
Version 2.0.0

How do I get rid of TS2304 errors with webpack command?

A: I had to install the core-js typings from npm to solve the issue
npm install @types/core-js

explanation:
The goal of @types npm packages is to obtain type definitions with npm. Using these type definitions is a TypeScript 2.0 feature .
@types replace current tools such as typings and tsd, though these will continue to be supported for some time.

A: Map, Set and Promise are ES6 features.
In your tsconfig.json you are using:
"target": "es5"

This causes the compiler to use the normal es5 lib.d.ts, which lacks the definitions for the above types.
You want to use the lib.es6.d.ts:
"target": "es6"

A: Just add:
 "lib": ["es6"] // means at least ES6

Don't change target.
Target is used to tell Typescript into which version of ECMAScript to compile your .ts files. Of course, you can change it, if the browser your application will be running in, will support that version of ECMAScript.
For example, I use "target": "es5" and "lib": ["es6"].

Another reason could be:
That your .ts file is not under "rootDir": "./YourFolder",

A: https://stackoverflow.com/a/44800490/9690407
npm install typings -g
typings install

is deprecated in npm 5.6.0!
Instead use the npm install @types/core-js syntax.

A: Since the answer directly to the OP has been answered already, I figured I would add what fixed it for me. My situation was slightly different in that I was not using WebPack and was getting these errors when trying to use tsc. The answer everyone else is giving (add "es6" to lib) did not resolve it for me. The problem for me was that I had v9.11.1 of node installed on my machine, but I had used npm to grab "@types/node", which got the most recent, v10+. Once I uninstalled that node typing and installed a specific v9 node typing file, this issue was resolved.

A: I'm using node.js v10.16.3. The problem for me was that the typescript compiler was ignoring my tsconfig.json file.
Three solutions worked for me:

*

*Install ts-node and use that instead to compile and run the file

*Do tsc filename.ts --lib "es6", "dom" when you compile the file

*Install @types/node which will allow you to run tsc filename.ts without errors.

A: To resolve this error change the following properties in tsconfig.json file.
"lib": [
      "es2018",
      "dom",
      "es5",
      "es6"
    ],
"module": "es2015",
"target": "es6"

After that run following command in the terminal.
npm install @types/es6-shim

ERROR RESOLVED.

A: If you are wondering why none of these fixes work for you keep in mind -- if you specify the file to compile on the command line or package.json tsc will NOT read your tsconfig.json file and therefore have no effect. Instead specify the "files" and "outDir" in your tsconfig.json and one of the "lib" fixes will probably work for you. Then compile with only:
tsc --sourcemaps

A: I added this to work in tsconfig.json, and it seems working without any error.
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "es6", "dom"],  <--- this
    ...
  }

I am not sure lib are for Typescript 2.0 function or not, but found out there are several libraries are available
From the typescript config schema (note the es2015.collection)
 "lib": {
      "description": "Specify library file to be included in the compilation. Requires TypeScript version 2.0 or later.",
      "type": "array",
      "items": {
        "type": "string",
        "enum": [ "es5", "es6", "es2015", "es7", "es2016", "es2017", "dom", "webworker", "scripthost", "es2015.core", "es2015.collection", "es2015.generator", "es2015.iterable",
                    "es2015.promise", "es2015.proxy", "es2015.reflect", "es2015.symbol", "es2015.symbol.wellknown", "es2016.array.include", "es2017.object", "es2017.sharedmemory" ]
      }
    }

This solves the compile errors, but I still wonder why tsc command works without any errors, but webpack does not. tsc searches for all possible libraries without using lib by tsconfig.json?

A: tsc index.ts --lib "es6"

If adding lib not working in tsconfig.json, using above command line option

A: In your tsconfig.json just change "target": "es5"  to "target": "es6"

A: To solve this you only need to import map method in your ts file like this:
import { map } from 'rxjs/operators';

A: for es6 use this
tsc filename.ts --lib es2015

A: For me the solution was to install @types/node:
yarn add @types/node --dev

Or if you prefer npm:
npm install @types/node --dev

However, I suppose that if you plan to continue using "Map", "Set" or "Promise", it's good practice to include "es6" in the "lib" array in tsconfig.json anyways.

A: In my case I had to run:
npm install typings -g
typings install

That solved my problem.


text:
Q: Mixcloud plugin to Rhythmbox there is SoundCloud plugin in Rhythmbox from 3.2 version.
Is there any similar plugin to Mixcloud? Or is there a way how to use this SoundCloud plugin to play music from MixCloud?
Thx!

A: There's a list of third party Rhythmbox plugins here. At time of writing, it doesn't look like there is a Mixcloud plugin available.
I don't believe it's possible to get the Soundcloud plugin to work with Mixcloud either - their APIs are likely completely different.


text:
Q: Use Quota in Ubuntu 16.04 in normal way I was trying to setup quota for my ftp users on fresh Ubuntu 16.04.
I was using this flow
But at the end came to flowing error, after running "quotaon /" i got error

quotaon: using //aquota.user on /dev/vda1 [/]: No such process
quotaon: Quota format not supported in kernel.

I found alternative tutorial here which uses
apt-get -y install linux-image-generic
apt-get -y install linux-headers-generic
apt-get -y install linux-image-extra-`uname -r`

kernel overwriting method which i think is not so good approach.
I wondered if there is not present some alternative to "quotaon" ? as it is removed from kernel then there should be some normal alternative functionality to it ? or some other way to enable quotaon without re installation  of "linux-image-generic ..." ?

A: If you are running the Virtual kernel inside a virtual machine, then this is
a known
bug
that can be fixed by installing the package linux-image-extra-virtual.
Otherwise, a better tutorial on enabling quota is found in the Stack Overflow post
Ubuntu quota format not supported in kernel,
which is more comprehensive than the one you found.
This does not involve modifying the Linux kernel, but it only causes
the quota modules to start with the boot, so that the quota command is enabled.
By default these kernel modules are not enabled, so that quota is unavailable.
For completeness, here is the relevant part of the answer:

We can install the full missing linux-generic package:
apt-get -y install linux-generic

Or only the extras packages (I prefer this):
apt-get -y install linux-image-generic
apt-get -y install linux-headers-generic
apt-get -y install linux-image-extra-`uname -r`

We need add the quota modules to start with boot:
echo quota_v1 >> /etc/modules
echo quota_v2 >> /etc/modules

reboot

Check if it's working:
sudo -s
cat /proc/modules | grep -i quota

quota_v1 16384 0 - Live 0xffffffffc037c000
quota_v2 16384 2 - Live 0xffffffffc0377000
quota_tree 20480 1 quota_v2, Live 0xffffffffc0250000

quotaon -pa

group quota on / (/dev/sda1) is on
user quota on / (/dev/sda1) is on

Both quotas are activated.


text:
Q: Is the empty set a member of any collection of sets? empty set is an subset of any sets maybe any collection of sets.
I wonder what about the case of the empty set being a member,not subset, of any collection (family) of sets.

A: This not true in general. For example, the empty set is a collection of sets that does not contain the empty set (because it does not contain any members).

A: Counterexample: the only element of $\{\{\emptyset\}\}$ is $\{\emptyset\}\ne\emptyset$.

A: $\varnothing\in\mathcal{P}(\varnothing)$ but $\varnothing\notin \varnothing$.


text:
Q: Copy multiple files to multiple destination based on text file I want to copy list of files specified in text file to list of destination by creating directory. I have one Excel file in which there are 2 columns, source and destination, each source has a destination.
Example Source:
\\10.0.0.1\share\abd.nsf
\\20.0.0.1\share\red.nsf

Example Dest:
\\10.0.0.2\share\abd\
\\10.0.0.2\share\red\

Currently I am using below code, but involves n number of lines so it is tedious.
copy-item "\\10.0.0.1\share\abd.nsf" -destination (New-item "\\10.0.0.2\share\abd\" -Type container -force) -force
copy-item "\\20.0.0.1\share\red.nsf" -destination (New-item "\\10.0.0.2\share\red\" -Type container -force) -force

A: $source = get-content c:\source.txt
$destination = get-content c:\destination.txt
$Count= $source.Count
$i = 0

For($i -eq 0;$i -Lt $count; $i++){
Try{new-item -itemtype directory $destination[$i]}
Catch {}
Finally{copy-item $source[$i] $destination[$i]}
}

Source and destination in text file  should be in same order

A: This is a rather simple one. Make your Excel file a 2 column csv where the columns are labelled Source and Destination. You don't have to use those just know that if yours differ that you need to adjust the properties called in the code.
$path = "c:\path\to\file.csv"
$jobs = Import-CSV $path
$jobs | ForEach-Object{
    # Check if the target folder exists. If not create it.
    If(-not (Test-Path -PathType Container $_.destination)){New-item "$_.destination" -Type Container -Force}

    # If the source file exists copy it to the destination directory.
    If(Test-Path $_.Source){Copy-Item $_.Source $_.Destination -Force}
}

Creates the destination directory if it does not exist (It is possible the path is still wrong but its better than nothing.). Then copy the file, assuming it also exists, to the destination.


text:
Q: Why does is think the column is the parameter value I get SQLite.SQLiteException: 'no such column: osborne' when I run this code. osborne is my search term, not the column. The column is LastName. Here is the queryasync code
public Task<List<DataItem>> GetItemByLastName(string s)
        {
            return Database.QueryAsync<DataItem>("SELECT * FROM [DataItem] WHERE [LastName] = "+s);
        }

s contains the search term osborne which I call via
var tItem = await App.Database.GetItemByLastName(s);

A: The problem is caused because you tried to concatenate the query string with a variable to get the final query. What you ended up was this SQL query:
SELECT * FROM [DataItem] WHERE [LastName] = Potato

Which is clearly invalid. It could be worse though. What if a malicious user passed 1; drop table DataItem;# ? That's how SQL injection attacks work.
You should never use string concatenation to pass values to a query. No amount of quoting is going to fix this problem either - what if someone is named O'Reilly? Quoting won't prevent a hacker from entering Robert; drop table Students;--. Look at Bobby Tables
The correct and safe way is to use parameterised queries (aka server-bound parameters). Parameters aren't string replacements. They're sent alongside the query to the database, preserving their type, precision etc. They allow you to send eg a decimal number or date as a strongly-typed decimal or DateTime and never worry about string formats and separators.
I suspect you used SQLite-net. The package's Github page shows how to use parameterised queries in this case, by using ? :
return Database.QueryAsync<DataItem>("SELECT * FROM [DataItem] WHERE [LastName] = ?", s);

? specifies a positional (ie unnamed) parameter. The parameter values you pass after the query text are used as the values for each ? parameter, in the order they appear

A: you need to delimit string parameters in SQL queries
return Database.QueryAsync<DataItem>
    ($"SELECT * FROM [DataItem] WHERE [LastName] = '{s}'");

as pointed out in the comments, parameterized queries are more secure
return Database.QueryAsync<DataItem>
    ("SELECT * FROM [DataItem] WHERE [LastName] = ?", s);


text:
Q: Integer expression expected in if statement I have a small shutdown script, if the Mac runs over 24 hours it will shutdown. I'm not really experienced in bash scripts, but I did this:
!/bin/bash

#Maximum number of days to be up
max=1

#Get the uptime days and assign it to a variable
uptime_days=`uptime | cut -d " " -f 5`

if [ $uptime_days -ge $max ]
  then
  shutdown -h now
fi

exit 0

now i get this error message:
./shutdown: line 9: (: days,: integer expression expected

Anybody can help?

A: This should work for macOS. We get the boot timestamp, then the current timestamp in seconds then some math and voila.
#!/bin/bash
BOOT_TIME=$(sysctl -n kern.boottime | sed -e 's/.* sec = \([0-9]*\).*/\1/')
CURR_TIME=$(date +%s)
MAX_UPDAYS=1 #Days

DAYS_UP=$(( ( $CURR_TIME - $BOOT_TIME) / 86400 ))
if [ $DAYS_UP -ge ${MAX_UPDAYS} ];then
   shutdown -h now
fi

A: The major bug in your script is cut should look like:
uptime_days=`uptime | cut -d " " -f 4`

Note the 5 became a 4.  This is because the cut was picking out the word days, not the number before it.
The way to catch errors like this is to add an echo into your code like:
echo uptime_days=$uptime_days

So when the output contains
uptime_days=days,

it is obvious some error in parsing has occurred.
There are also a couple of other things that could be improved to avoid issues later:
shebang
The top line of the script should start with #! for it to be read by the kernel.  Your code is being interpreted by the shell anyway, but if you run the command in a different way it might not so making the top line look like
#!/bin/bash

is a good idea.
double brackets
Using double brackets for conditionals in the shell is less error prone.  You can also move the then onto the same line with the if like so:
if [[ $uptime_days -ge $max ]]; then
     echo shutdown!
fi

A: This is the whole script:
#!/bin/bash
uptime | grep -q days && shutdown -h now


text:
Q: ExpandableListView has wrong groupPosition when trying to display child view in Android I am having an issue that I have been working on for a while. I am using an ExpandableListView with a ViewHolder. I know that the ExpandableListView reuses Views and that is what I think is happening with the problem that I have.
I have 3 views in the list and if I select 1 then 2 then 3, then everything is fine and it displays the correct child view. Although when I select 3 first, all of the other child views are the same with the same groupPosition. If I select 2 first, then 3 is correct, but 1 displays the third child view.
I want them to be all fixed to the correct groupPosition so that they don't change.
Here is my adapter for the ExpandableListView:
public class MenuListAdapter extends BaseExpandableListAdapter
{
private Context context;
private ArrayList<ListData> listData = new ArrayList<ListData>();

/**
 * Constructor for the class.
 *
 * @param refContext This is a reference to the context of the ExpandableListAdapter being used in.
 * @param refListData This is a reference to the ArrayList of ListData that will display the item data of the menu in the list.
 */
public MenuListAdapter(Context refContext, ArrayList<ListData> refListData)
{
    context = refContext;
    listData = refListData;
}

private static class ViewHolder
{
    TextView title;
    TextView description;
    ImageView image;
    ImageButton addItem;
}

@Override
public int getGroupCount()
{
    return listData.size();
}

@Override
public int getChildrenCount(int groupPosition)
{
    return 1; // There will only ever be 1 child in the group.
}

@Override
public Object getGroup(int groupPosition)
{
    return groupPosition;
}

@Override
public Object getChild(int groupPosition, int childPosition)
{
    return null;
}

@Override
public long getGroupId(int groupPosition)
{
    return groupPosition;
}

@Override
public long getChildId(int groupPosition, int childPosition)
{
    return childPosition;
}

@Override
public boolean hasStableIds()
{
    return true; // Stops child views from resetting
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
{
    final ViewHolder holder;

    if(convertView == null)
    {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.listview_item, parent, false);

        holder = new ViewHolder();
        holder.title = (TextView) convertView.findViewById(R.id.titleTextView);
        holder.image = (ImageView) convertView.findViewById(R.id.imageImageView);
        holder.addItem = (ImageButton) convertView.findViewById(R.id.addItemImageButton);

        /* The contents of the item View is set for every View in the list. */
        holder.title.setText(listData.get(groupPosition).getTitle());
        holder.image.setImageBitmap(listData.get(groupPosition).getImageBitmap());
        holder.image.setTag(listData.get(groupPosition).getImageRes()); // Sets tag for image resource.

        holder.image.setFocusable(false);// Enables the group view to be in focus in order to still be able to select the image and group.

        holder.image.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Integer imageResource = (Integer) holder.image.getTag(); // Get image resource from tag.
                int resource = imageResource.intValue(); // Creates primitive image resource from object Integer.

                Intent imageIntent = new Intent(context, ImageActivity.class);
                imageIntent.putExtra("image_resource", resource); // Adds image resource as Extra to Intent.
                context.startActivity(imageIntent);
            }
        });

        holder.addItem.setFocusable(false); // Enables the group view to be in focus in order to still be able to select the button and group.

        holder.addItem.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                /* AlertDialog that allows the user to select how many items they want of the item they selected. */
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                AlertDialog alertDialog;
                LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View customView = layoutInflater.inflate(R.layout.item_quantity, null);

                final NumberPicker quantityPicker = (NumberPicker) customView.findViewById(R.id.quantityPicker);
                quantityPicker.setMinValue(1);
                quantityPicker.setMaxValue(10);
                quantityPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); // Stops keyboard from appearing.

                alertBuilder.setTitle("Select quantity");
                alertBuilder.setView(customView);
                alertBuilder.setPositiveButton("Confirm", new DialogInterface.OnClickListener()
                {
                    public void onClick(DialogInterface dialog, int id)
                    {
                        int quantityAmount = quantityPicker.getValue(); // Gets value from NumberPicker.

                        /* Update checkout data. */
                        MainActivity mainActivity = (MainActivity) context;
                        mainActivity.updateCheckout(holder.title.getText().toString(), quantityAmount); // Updates checkout with added order.

                        dialog.cancel(); // Cancels AlertDialog.

                        Toast.makeText(context, "Order added to checkout!", Toast.LENGTH_SHORT).show();
                    }
                });

                alertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
                {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.cancel(); // Cancels AlertDialog.
                    }
                });

                alertDialog = alertBuilder.create(); // Creates the AlertDialog View.
                alertDialog.show(); // Shows the AlertDialog View.
            }

        });

        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    return convertView;
}

@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
{
    final ViewHolder holder;

    if(convertView == null)
    {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.listview_desc_item, parent, false);

        holder = new ViewHolder();
        holder.description = (TextView) convertView.findViewById(R.id.descriptionTextView);

        holder.description.setText(listData.get(groupPosition).getDescription()); // Sets description of item View.

        System.out.println("Group position: " + groupPosition);
        System.out.println("Child position: " + childPosition);

        convertView.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) convertView.getTag();
    }

    return convertView;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition)
{
    return false;
}

}

Please can someone help me with this issue.

A: the issue is the view recycling and you are only updating the view the first time you inflate the view try this
if(convertView == null)
{
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.listview_desc_item, parent, false);

    holder = new ViewHolder();

    convertView.setTag(holder);
}

    holder = (ViewHolder) convertView.getTag();
    holder.description = (TextView) convertView.findViewById(R.id.descriptionTextView);

    holder.description.setText(listData.get(groupPosition).getDescription());
    System.out.println("Group position: " + groupPosition);
    System.out.println("Child position: " + childPosition);

A: There are several issues:
You are returning null for getChild().
You are returning the group position instead of the Object that backs that group.
getChildrenCount() returns 1. This will only return one item for the child. You should return the total children count.
If you look at the getChild() gives you the parent and child position. You should use a data structure that adapts to that pattern.
Here is an example of how I implemented an ExpandableListView some time ago. It can be better. For example, passing the Context to the constructor is not needed.


text:
Q: How to convert a html page to a vue page? I am trying to convert the html page seen below to a vue.js file.
 <!DOCTYPE html>

<title>Process</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

File List

      <button style="display: inline-block;font-size: 16px;" type="button" onclick="createFolder()" >Create New Folder</button>

    <button style="display: inline-block;font-size: 16px;" type="button" onclick="location.href='./workfloweditor.html'" >Create New Process</button>

How do i rewrite this in vue.js?
What i have tried so far-
<template>

File List

      <button style="display: inline-block;font-size: 16px;" type="button" onclick="createFolder()" >Create New Folder</button>

          Create New Process

</template>

I dont know how to rewrite the document.addEventListener('click', function part and the axios.get() part of it in the mounted function in the vue js?. Plz help me rewrite this in the vue format and also mention if there are any other changes that i have to make in my vue file.


text:
Q: What is the difference in meaning between "I eat twice a day" and "I eat twice in a day"? Tell me please the difference in meaning between the following sentenced?

I eat twice a day.
I eat twice in a day.

I am sure that in a day is a valid phrase, but I cannot figure out the difference between it and a day as in my sentences.

A: It is a valid phrase, but they mean different things.

*

*"Twice a day" means every day.

*"Twice in a day" would normally mean a specific day.
For example:

I once ate six times in a day.

This refers to one specific occasion on which you ate 6 times in one day. It would not make sense to say "I once ate six times a day".
For some additional information on when to use a preposition with a verb, take a look at the answer to this recent question.


text:
Q: Hackenbush game strategy for stalk There are some piles of numbers. Numbers are divided in 2 groups, A and B. Player x plays with group A and player y plays with group B. x makes the move first. On each step a player chooses a pile and chooses a number of his group and remove all numbers smaller and equal to the number (number of both group A and B) from that piles only.
The person who can't make the move which means he finds no number of his group, loses.
Is that a nim game? What should be the strategy? Who will win?

A: It's not a nim game, it's an Hackenbush game (Blue-Red version if $A\cap B=\emptyset$)
Replace each number by a line segment of color red for number from $A$, and blue for $B$. To each pile of number, build a pile of line segment, by decreasing order of number.
For example, if $A$ are even numbers, and $B$ are odd numbers, the pile $[3,4,7,8,10]$ will be replace by ground-red(for 10)-red(for 8)-blue(for 7)-red(4)-blue(3).
Hackenbush games are not nim games. To each finite position can be assigned a dyadic number whose sign will give the player who can win.
EDIT : strategy explained for player x :
To each number (from $A$) in each pile, $x$ will assign a value that will be :

*

*$1$ if this the largest number of the pile

*$1$ if the next larger number was assigned 1 and is from the same set ($A$ or $B$)

*$2^{-n}$ where $n$ is the distance to the closest number with value $1$.

Example : in pile [10,8,7,4,3,1], 10 will have value 1 (by rule 1), 8 value 1 (by rule 2), and 4 value $\frac{1}{4}$ (by rule 3).
For player y, 7 will be assigned value $\frac{1}{2}$ (rule 2 does not apply here because the next larger number 8 is not from the same set, so rule 3), 3 value $\frac{1}{8}$, and 1 value $\frac{1}{16}$.
The best strategy is to remove the number of lowest value. (This is not the quickest strategy !)
If you add all values for player x and subtract all values for player y, a positive sum means player x has a winning strategy, negative sum is for player y while a zero sum means second player.


text:
Q: WindowsFormsHost Controls - Exception Handling I have a WPF Window which requires several WindowsFormHost controls. I noticed that if I model the control like this, then Exceptions do not bubble to the surface and are silently handled i.e. only visible using SharpDevelop's Debugging option 'Pause on handled Exceptions'.
How can I avoid this behaviour?
I have tested this by throwing an exception in the Window's Loaded Event Handler code. If I comment out one of the WindowsFormsHost controls, exception handling is as normal and the code breaks, but if left as shown in the code below, the Window is displayed as if the exception was caught.
<?xml version="1.0" encoding="utf-8"?>
    <Window
        x:Class="TEST.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TEST"
        Height="300"
        Width="300">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition
                    Height="150" />
                <RowDefinition
                    Height="150" />
            </Grid.RowDefinitions>
            <WindowsFormsHost Grid.Row="0" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
            <WindowsFormsHost Grid.Row="1" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" />
        </Grid>
    </Window>

/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(Window1_Loaded);
    }

    void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        throw new ApplicationException("TEST");
    }
}

A: This is due to the intermediary windows interop stack that the WindowsFormsHost creates to hande Windows Messages for Windows Forms technology.
It's based on an almost standard NativeWindow class, and unfortunately, this class just eats exception by default. You can have a look at it using Reflector or any other IL inspection tool. The heart of this class is this method:
private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
{
    try
    {
        // process message
    }
    catch (Exception exception)
    {
        this.OnThreadException(exception);
    }
    ...
}

By default, the OnThreadException method is ... empty. In theory you could create a class that derives from WindowsFormsHost, especially the BuildWindowCore method. I've tried to do it, but it does not work as WindowsFormsHost implementation uses a lot of private stuf....


text:
Q: Angular Adding items from multiple arrays into Json object I have 3 sets of Json data
data1 [{id:1, systemName: "foo", moreInfo: "blah},
       {id:2, systemName: "boo", moreInfo: "blahBlah}]

data2 [{systemName: "foo",count: 21},
       {systemName: "boo",count: 454}]

data3 [{systemName: "foo",count: 643},
       {systemName: "boo",count: 674}]

what I require is to take the counts from data 2 and 3 and add them to their respective objects in data1 with new name like data2Count and Data3Count
so data1 would look like this:
data1 [{id:1, systemName: "foo", moreInfo: "blah, data2Count: 21, data3Count: 643},
       {id:2, systemName: "boo", moreInfo: "blahBlah, data2Count: 454, data3Count: 674}]

Currently I can only achieve this:
data1 [{id:1, systemName: "foo", moreInfo: "blah"}
       {id:2, systemName: "boo", moreInfo: "blahBlah"} data2Count: 454]

Using:
angular.forEach(data1, function(value1, key1) {
    angular.forEach(data2, function(value0, key0) {
        if (value1.systemName === value1.systemName) {
            $scope.sysFlow.data2Count = value1.count
        }
    })
})

A: You can use Array#map to do something like this:

var data1 = [
    {id:1, systemName: "foo", moreInfo: "blah"},
    {id:2, systemName: "boo", moreInfo: "blahBlah"}
  ]

var data2 = [
    {systemName: "foo",count: 21},
    {systemName: "boo",count: 454}
  ]

var data3 = [
    {systemName: "foo",count: 643},
    {systemName: "boo",count: 674}
  ]

data1 = data1.map(function(obj) {

  obj.data2Count = data2.filter(function(o) {
    return o.systemName === obj.systemName
  })[0].count;

  obj.data3Count = data3.filter(function(o) {
    return o.systemName === obj.systemName
  })[0].count;

  return obj;
})

console.log(data1)


text:
Q: know which button was clicked (Xamarin.Forms) I have many images that works like a button and were created programatically and their data is from the webservice...Then, I don't know how many buttons I will have. Each Button represents one item of my webservice list...and, when the button is clicked, I need to know which item it represents. How can I do that?
I have something like this

And I need, when the user clicks on one of these images I receive a name of the object it represents...or a id...I dont know...
I am creating it with this code:
void eteste()
    {
        int column = 0;
        int row = 0;

        lstCategorias = lstCategorias.OrderBy(o => o.nome).ToList();

        foreach (var item in lstCategorias)
        {
            StackLayout stack = new StackLayout();
            stack.VerticalOptions = LayoutOptions.Center;

            Image textura = new Image();
            textura.Source = "pngteste";
            textura.AutomationId = item.idCategoria;
            textura.HorizontalOptions = LayoutOptions.Fill;
            textura.VerticalOptions = LayoutOptions.Fill;
            gridteste.Children.Add(new BoxView { Color = Color.FromHex(item.corFundo) }, row, column);

            gridteste.Children.Add(textura, row, column);

            var CliqueCategoria = new TapGestureRecognizer();
            CliqueCategoria.Tapped += (s, e) => {

            };

            textura.GestureRecognizers.Add(CliqueCategoria);

            gridteste.Children.Add(stack, row, column);

            stack.Children.Add(new Image { Source = item.imagem, VerticalOptions = LayoutOptions.StartAndExpand, HorizontalOptions = LayoutOptions.Fill });

            stack.Children.Add(new Label { Text = item.nome, TextColor = Color.FromHex(item.corTexto), BackgroundColor = Color.Accent, VerticalOptions = LayoutOptions.CenterAndExpand, HorizontalOptions = LayoutOptions.CenterAndExpand });

            if (row == 0)
            {
                row = 1;
            }
            else
            {
                row = 0;
                column++;
            }

        }
    }

I tried to use textura.AutomationId = item.id in the foreach in order to get the id after...and I used the CliqueCategoria.Tapped += (s, e) => with a **var x = s.AutomationId **, trying get the id of the item that the button represents, but it didn't work as well...

A: You need to add TapGestureRecognizer to each image and add this image to (probably) Grid. When image is tapped you will receive "Image" object in "sender" parameter. You can extend an Image providing new get/set extension method for Id or derive from Image and add Id. You also can use Source member of Image which you set to "Source = item.imagem"

A: I would probably use BindingContext property for such purposes:
    foreach (var item in lstCategorias)
    {
        ...

        Image textura = new Image();
        textura.BindingContext = item;

        ...

        var CliqueCategoria = new TapGestureRecognizer();
        CliqueCategoria.Tapped += (s, e) => {
            var image = s as Image;
            var itemFrom_lstCategorias = image.BindingContext as TypeOfTheItemFromForeach;
        };

        ...
    }


text:
Q: Summing corresponding pairs from two lists within a tuple - in Haskell I have a tuple containing two lists of numbers - ([1,2,3,4],[5,6,7,8])
I need to sum together the corresponding pairs of numbers from each list. ie (1+5), (2+6) etc. Outputting a list ie [6,8,10,12]. It should also work for any amount of elements within the lists (2 lists of 5, 2 lists of 6 etc).
I've been trying a function using "map sum . transpose" but can't seem to get the types correct (as it is within a tuple). I found a piece of code on here which works for a list of lists, but don't know how to do the same for a tuple of lists (is it possible?). When I attempt to change the types of "a" or use Int I compile to type-mismatch errors.
tupSums :: Num a => [[a]] -> [a]
tupSums = map sum . transpose

I'm fairly new to using Haskell so I don't quite understand the errors I'm getting, sorry if the question seems stupid.

A: This is a good candidate for zipWith, which takes two lists and combines the corresponding elements in the list using a particular operator. The following should work:
tupSums :: Num a => ([a],[a]) -> [a]
tupSums = uncurry $ zipWith (+)

zipWith (+) evaluates to a function that takes two arguments, each of them being lists, and returns an list of pairwise sums. uncurry takes a function of two args and turns it into a function that takes a single tuple. So uncurry $ zipWith (+) evaluates to a function that takes a tuple of lists and returns a list with the pairwise sums.