Q: How to load 1000+ items to a asp:GridView from SQL Server DB with high efficiency I have a function like below that I use to return a gridview (id: dgmenu) to the end users based on their role. Note that I am not allowed to apply pagination to the gridView, all items must be seen in one page.
protected DataTable MenuForUserRole(string userRole) {
  DataTable dtMenus = new DataTable();
  string connectionString = constr;
  try {
    using(SqlConnection cnn = new SqlConnection(connectionString)) {
      cnn.Open();
      string query = @"Select mycolumn1, mycolumn2, mycolumn3, mycolumn4m mycolumn5
                       From mytable
                       Where mykey = (select thekey from anothertable where role = @role)
                       order by myOrderColumn;
                       ";

      SqlCommand oCmd = new SqlCommand(query, cnn);
      oCmd.Parameters.AddWithValue("@role", userRole);

      using(SqlDataAdapter a = new SqlDataAdapter(oCmd)) {
        a.Fill(dtMenus);
      }

      cnn.Close();
    }
  } catch (Exception ex) {
    throw;
  }
  return dtMenus;
}

Usage:
dgMenu.DataSource = MenuForUserRole(ddlUserRoles.SelectedItem.Value.ToString());
dgMenu.DataBind();

My issue is performance-related: some of the GridViews returned has more than 1000 items, so it takes 5-6 seconds to load the complete gridView for those users, which is unacceptable. When I search online, I couldn't find more efficient code to load a gridView from SQL Server Database. Any help or advice that might increase the load speed when there is high amount of data to the gridview would be appreciated.
Used -> Visual Studio 2017 & SQL Server 2017

A: The most efficient way would be to realize that it is a bad idea.
1000 records is too much for any user to deal with. 1-2 Orders of Magnitude to much. There is no human on this planet, that could work with that much data at once. This data needs to be filtered, grouped or paginated way more before it comes in front of a user.
And those are all operations you should not be doing past the query. Those should be done in the query itself. Retrieving data you do not want to do filtering later just adds a tone of network load, adds race conditions, Database locks and is propably slower anyway (DBMS are really good at their job!). Worse, with ASP.Net and it's shared memory it can quickly lead to memory issues.

A: Profile your code. Understand where most of the time is spent. It could be SQL Server, it could be transmission over network, it could be binding the data to the control[s]. If it is SQL Server, we would need to see your schema to tell you how performance could be improved. Like, do you have an index on mykey? BTW, don't call it a key, key is something that uniquely identifies the record, which is obviously not the case here.

A: Use reporting (e.g. Reporting Services) and create a link to export the data into an excel spreadsheet.


Q: mailmerge in word from c# opens multiple instances I'm trying to automate mailmerge using a .net program. There's a one page letter in word document addressed to a particular person with a mailmerge field by name 'Person'. Our database has got multiple persons and each person name has to go into a copy of the letter. We want the one-page letters to be concatenated one after the other. Currently this code tries to use two persons with - name1 & name2. The code below opens a separate instance of word for every person name.
        object oMissing = System.Reflection.Missing.Value;
        //CREATING OBJECTS OF WORD AND DOCUMENT
        Word.Application oWord = new Word.Application();
        Word.Document oWordDoc = new Word.Document("C:\\Test\\AddressTemplate.docx");

        //SETTING THE VISIBILITY TO TRUE
        oWord.Visible = true;
        //THE LOCATION OF THE TEMPLATE FILE ON THE MACHINE
        Object oTemplatePath = "C:\\Test\\AddressTemplate.docx";

        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
        {
            if (field.Code.Text.Contains("Person"))
            {
                field.Select();
                oWord.Selection.TypeText(name1);
            }
        }

        oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field field in oWordDoc.Fields)
        {
            if (field.Code.Text.Contains("Person"))
            {
                field.Select();
                oWord.Selection.TypeText(name2);
            }
        }

Question: How can I change the code to open just one instance of word, fill in the mailmerge field and concatenate one letter at the end of the other?

A: If you call new Word.Application you're creating a new instance, if what you want is to create a new instance if there is none, but reuse one if there is already one open you can do the following:
        Application app;
        try
        {
            app = (Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
        }
        catch
        {
            app = new Application();
        }

Based on your comment i think you actually only have 1 instance of word open, it just opens both documents in different Windows (but a single application). Windows aren't the same as applications.
If you want it all in a single window you could reuse the previous document or else close it before you open a new one

A: Ronan's code above did the trick for me. I was doing new Application() every time, adding WINWORD instances (I know, should've known better). I speak both C# and VB, but here's the VB version I used in this project:
        ' Use same winword instance if there; if not, create new one
    Dim oApp As Application
    Try
        oApp = DirectCast(Runtime.InteropServices.Marshal.GetActiveObject("Word.Application"), Application)
    Catch ex As Exception
        ' Word not yet open; open new instance
        Try
            ' Ensure we have Word installed
            oApp = New Application()
        Catch eApp As Exception
            Throw New ApplicationException(String.Format("You must have Microsoft Word installed to run the Top Line report"))
        End Try
    End Try
    oApp.Visible = True


Q: How to change html href attribute value with jQuery? I am trying to change html href attribute value ?post=55 to ?post=44 with button click using jQuery, but don't know how.
HTML
<button class="button">button</button>

Post

JAVASCRIPT
$('.button').on('click', function() {

});

This is what I have
Post

This is what I want when clicking button
Post

A: A  Jquery function allows you to change an attribute of a tag. It is written as $("tag").attr('attr','newvalue').
In your case, you can do $("a").attr('href','posts.php?post=44') inside the click function (you should probably give the a tag an id too)

A: "on-click" handler has $(this) that you can use to navigate in the DOM tree if you know that the object you want to alter is relatively placed (from what I see you have  following <button/>.
$('.button').on('click', function() {
    $(this).parent().find('.post-link').attr('href', '#hello-world')
})

JSFiddle
If you want to change a link of the element that is somewhere on the page, I would suggest searching by id value (the id should be unique). Let's say you have ..., then:
$('.button').on('click', function() {
    $('#my-id').attr('href', '#hello-world')
})


Q: Trying to create a new page when horizontal pos. of i extends past right margin I am trying add a page when horizontal or the x position is greater than a counter in order to keep a right side margin. When I run the code I end up in an infinate loop of hundreds of pages all displaying the same first page graphics. Thinking it might have to do with my lack of understanding HasMorePages. I could use some help. Thanks.
    public static class PrintWave
{
    public static void PrintPreWave()
    {

        PrintDocument pd = new PrintDocument();

        if (WaveTools.MySettings == null)
        {
            pd.DefaultPageSettings.Landscape = true;
        }
        else
        {
            pd.DefaultPageSettings = WaveTools.MySettings;
        }
        pd.OriginAtMargins = true;

        pd.PrintPage += new PrintPageEventHandler(OnPrintPage);
        PrintDialog dlg = new PrintDialog();
        PrintPreviewDialog printPreviewDlg = new PrintPreviewDialog();
        printPreviewDlg.Document = pd;

        Form p = (Form)printPreviewDlg;
        p.WindowState = FormWindowState.Maximized;
        printPreviewDlg.ShowDialog();

    }

    private static void OnPrintPage(object sender, PrintPageEventArgs e)
    {
        string MyTag = string.Empty;
        MyTag = WaveActions.ActiveId;
        Wave MyWave = WaveHolder.FindWave(MyTag);
        int MyCount = 0;

        int xOffset = e.MarginBounds.Location.X;

        int yOffset = e.MarginBounds.Location.Y;

        if (MyWave != null)
        {
            Graphics g = e.Graphics;
            g.SetClip(e.PageBounds);

            Pen MyPen = new Pen(WaveTools.WaveColor, WaveTools.PenWidth);

            float dx = (float)e.PageBounds.Width / MyWave.NumSamples;
            float dy = (float)e.PageBounds.Height / 255;

            if (MyWave.Normal == false)
             {
               g.ScaleTransform(dx, dy);

            }

            for (int i = 0; i < MyWave.NumSamples - 1; i++)
            {

                g.DrawLine(MyPen, i, MyWave.Data[i], i + 1, MyWave.Data[i + 1]);
                MyCount = MyCount + 1;

                if (MyCount > e.MarginBounds.Width)
                {

                    e.HasMorePages = true;
                    MyCount = 0;
                    return;
                }
                else
                {

                    e.HasMorePages = false;
                    return;

                }

            }

        }

    }

}

}

A:        for (int i = 0; i < MyWave.NumSamples - 1; i++)

That's the core problem statement, you start at 0 every time PrintPage gets called.  You need to resume where you left off on the previous page.  Make the i variable a field of your class instead of a local variable.  Implement the BeginPrint event to set it to zero.
The else clause inside the loop need to be deleted.


Q: Strange behaviour when calling VB6.0 COM-component in C# (in python all is ok) I have some problems when working with COM-component in C#.
I have old (~2001-2003year developed) VB6 COM component, and unfortunately there is no source code for it. The component interacting with a service program (no source too). The main Application is written in VB6, and now I'm rewriting it on .Net.
I have imported (with TblImp) component into C# and calling it:
using System;
using System.Threading;
using System.Collections.Generic;
using System.Text;
using System.Runtime.CompilerServices;

using SrvCommDCG;

class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
        {
        System.Console.WriteLine("calling com");
        clsCommDCGService srv = new clsCommDCGService();
        srv.Check();
        System.Console.ReadKey();
        }
    }
}

When I'm running it on Windows 7, nothing happens (the component should show a messagebox when check is finished).
When I'm running it on Windows 8, program crashes without any exception.
I've tried different thread models: MTA, STA (using either [STAThread], or SetApartmentState()), calling DisableComObjectEagerCleanup() -- nothing helped.
After week of no result, I've tried to use my component in Python, and:
import win32com.client
tst = win32com.client.Dispatch("SrvCommDCG.clsCommDCGService")
tst.Check()

All is working, check is ok and MessageBox appeared.
Ofc, it works from VB 6.0 too.
I think, the problem is that python is single-threaded win32 app, and C# is multithreaded managed code. And I'm missing some point to understand what I should add to C# code, to make it work? Unfortunately I need to call it from .Net.
edit #1: I've tried on .Net 4.0 and 4.5, and also on .Net 2.0 frameworks
edit #2: when program crashing on Windows 8 there aren't any useful messages (even if i ran program from VS C# debugger), it's just write "Program occured a problem and will be closed" (have russian Win8, can't tell you the exact message in Windows). The Event log in Win8 says: Process was killed due to unhandled exception c0000005 at address 012E72CC. It's simple Access Violation.
edit#3: While C# program works bad on Win7/8, it works normal on Windows XP. Mysterios things.


Q: Get BoundingBox of ONLY visible area of map in osmdroid I am using osmdroid version 4 and I want to have BoundingBox of visible map. It seems that MapView.getBoundingBox method returns bounding box of all tiles that are visible or partially visible. Take a look at this picture:

Black rectangles are tiles, red rectangle with rounded corners is  device display.
I want to have only diagonal area shown by green line. What should I do?

A: I believe you are mistaken. getBoundingBox() returns the lat/long boundaries of what is visible on the screen. The code will take the pixel x,y value of the two corners and covert that into lat/long and that is what is used. It is not "snapped" to actual map tiles. The result of getBoundingBox() should return the area of the red box.


Q: Opens the map with a certain position of the camera I'm new to java, I installed Google maps in my application, but when you open the card, open a very large scale of the map, a function I need to use for that would map opened at a certain city? And just a second question - please tell me what the name of the function is responsible for determining the location the user

A: This question is rather vague but the API documentation should be able to help you here.
https://developers.google.com/maps/documentation/api-picker
Just pick out which API you need. It should be something like setLocation(Coordinates) in all of them.


Q: How can I eliminate duplicates using MAX function? I have these tables
recommendation_object_id, exhibitor_name, event_edition_id, timestamp
I want to hide/remove the duplicates in recommendation_object_id to make it a primary key.
I successfully removed most of the dups, but a few recommendation id's have a different event edition id so some id's are still duplicating as a result.
A colleague of mine said I could eliminate those further by using max(timestamp) but I could not pull it off :(
My current query is this:
SELECT DISTINCT r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type, max(r.timestamp)
FROM recommendations r
left join show_details sd on r.event_edition_id = sd.event_edition_id
left join exhibitor_details ed on r.recommended_object_id = ed.exhibitor_id
group by r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type
order by r.recommended_object_id

A: If you want one row per recommended_object_id, the one with the most recent timestamp, then use window functions:
select r.*
from (select r.recommended_object_id, ed.exhibitor_name, sd.event_edition_id, r.object_type,
           row_number() over (partition by recommended_object_id order by r.timestamp desc) as seqnum
      from recommendations r left join
           show_details sd
           on r.event_edition_id = sd.event_edition_id left join
           exhibitor_details ed
           on r.recommended_object_id = ed.exhibitor_id
     ) r
where seqnum = 1
order by r.recommended_object_id;


Q: How to get img alt text and data-src using Beautifulsoup? HTML snippet :

I want to extract all the alt text and data-src from the img class="profile_photo_img. My code:
ele = soup.find_all('img', class_='profile_photo_img')
    for i in ele:
        print i["data-src"]
        print i["alt"]

But it is printing nothing. How can I get the desired result?

A: Try the following code:
elements = soup.findAll('img', attrs={'class':'profile_photo_img'})
for element in elements:
    print element['data-src']
    print element['alt']

Also make sure that the soup is right parsed from the html by printing it before you are searching for elements


Q: How to get custom headers from axios post response? i'm using nuxt/axios with laravel as my backend. in my responses from laravel i send a custom header named _msg but i cant access it. in my console.log(response) i get only this:

but in my brower network i get the header:

how can i access it?
UPDATED
added this to my laravel middleware:
this is an example if request is from manager and admin
<?php

namespace App\Http\Middleware;

use Closure;
use App\Traits\UtilsTrait;

class ManagerPlus
{
    use UtilsTrait;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        return $next($request);
        if($this->isMoreManager()){
            $request->panelType = $this->addPanelType();
            $response = $next($request);

            $response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
            return $response;
        }
        return $this->permissionDenied();
    }
}

UPDATE AFTER EXPOSE:
i did as told with my laravel/fruitcake setting and middleware and this is my new header that i get from axios. but still not getting my _msg

A: What I think you need to do is:
if you are using the package https://github.com/fruitcake/laravel-cors you will have config/cors.php and there is where you should add
'exposed_headers' => ['_msg'],
and you have to create the middleware as it's explained in the issue https://github.com/fruitcake/laravel-cors/issues/308#issuecomment-490969761
$response->headers->set('Access-Control-Expose-Headers', '_msg');
I hope it works


Q: How to accept an array parameter in a GET request in Flask using Connexion I am using connexion to create a REST API via Flask.  At the moment I am passing a single identifier in.
/read/maa_valid_product_id/{drug_product_id}:
    get:
      operationId: registrations.read_maa_valid_product_id
      tags:
        - Marketing Applications
      summary: Read the entire list of non-passive marketing application registrations for a specified drug_product_id, which have a valid authorisation status
      description: Read the entire list of non-passive marketing application registrations for a specified drug_product_id, which have a valid authorisation status
      parameters:
        - in: path
          name: drug_product_id
          required: true
          schema:
            type: integer
          description: Numeric ID of the user to get
        - in: query
          name: length
          required: false
          schema:
            type: integer
          description: Numeric ID of the user to get
        - in: query
          name: offset
          required: false
          schema:
            type: integer
          description: Numeric ID of the user to get
      responses:
        '200':
          description: Successfully commpleted the list operation for non-passive valid MAAs, for the specified drug_product_id
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/marketing_application'

I need to pass an array of id values in, based on selections in a table.  Is this possible?
If it is possible, how would I access the array, the existing method call is:
def read_maa_valid_product_id(drug_product_id, length=0, offset=0):
    """
    This function responds to a request for /api/products
    with the complete lists of people

    :return:        json string of list of people
    """
    # conn_ariel = pool.acquire()
    conn_ariel = get_connection()
    cursor_ariel = conn_ariel.cursor()

    # Create the list of products from our data
    sql = """
        SELECT A.DRUG_PRODUCT_ID,
               B.PREFERRED_TRADE_NAME,
               B.PRODUCT_LINE,
               B.PRODUCT_TYPE,
               B.FLAG_PASSIVE AS PRODUCT_FLAG_PASSIVE,
               A.REGISTRATION_UID,
               A.COUNTRY_DISPLAY_LABEL,
               A.FLAG_PASSIVE,
               A.AUTHORIZATION_STATUS,
               A.DISTRIBUTION_TYPE AS PROCEDURE_TYPE,
               A.MAH_COMPANY,
               A.DOSSIER_REF_NUMBER AS REGISTRATION_NAME_DETAILS,
               A.APPLICATION_STAGE,
               A.APPLICATION_TYPE,
               A.RENEWAL_NOT_REQUIRED,
               TO_CHAR(A.NEXT_RENEWAL_DATE,'YYYY-MM-DD') AS NEXT_RENEWAL_DATE

               FROM DIM_REGISTRATION_SET A, DIM_DRUG_PRODUCT B, v_rep_az_183_01_reg_includes C
               WHERE A.DRUG_PRODUCT_ID = B.DRUG_PRODUCT_ID AND A.VERSION_SEQ = C.VERSION_SEQ
               AND A.DATA_STATE = 'C'
               AND A.FLAG_PASSIVE = '0'
               AND A.APPLICATION_TYPE = 'Marketing Application'
               AND A.AUTHORIZATION_STATUS LIKE 'Valid%'
               AND A.DRUG_PRODUCT_ID = :id
               ORDER BY B.PREFERRED_TRADE_NAME, A.COUNTRY_DISPLAY_LABEL ASC
        """
    cursor_ariel.execute(sql,{"id":drug_product_id})
    registrations = []
    names = [c[0] for c in cursor_ariel.description]
    cursor_ariel.rowfactory = collections.namedtuple("registrations", names)

    i = 0
    j = 0

    start = None

    if offset == 0:
        start = True
    else:
        start = False

    for row in cursor_ariel.fetchall():
        if start == True:
            registration = {
                "drug_product_id": row.DRUG_PRODUCT_ID,
                "preferred_trade_name": row.PREFERRED_TRADE_NAME,
                "product_line": row.PRODUCT_LINE,
                "product_type": row.PRODUCT_TYPE,
                "product_flag_passive": row.PRODUCT_FLAG_PASSIVE,
                "registration_uid": row.REGISTRATION_UID,
                "country_display_label": row.COUNTRY_DISPLAY_LABEL,
                "flag_passive": row.FLAG_PASSIVE,
                "authorization_status": row.AUTHORIZATION_STATUS,
                "procedure_type": row.PROCEDURE_TYPE,
                "mah_company": row.MAH_COMPANY,
                "registration_name_details": row.REGISTRATION_NAME_DETAILS,
                "application_stage": row.APPLICATION_STAGE,
                "application_type": row.APPLICATION_TYPE,
                "renewal_not_required": row.RENEWAL_NOT_REQUIRED,
                "next_renewal_date": row.NEXT_RENEWAL_DATE
            }
            # logging.info("Adding Registration: %r", registration)
            registrations.append(registration)

            if length > 0:
                if i == length - 1:
                    break
            i += 1
        else:
            if j == offset - 1:
                start = True

        j += 1

    pool.release(conn_ariel)

    return registrations

A: Got there in the end:
yaml config:
/read/products_many/{drug_product_ids}:
    get:
      operationId: products.read_products_many
      tags:
        - Product
      summary: Read multiple drug products for the provided drug_product_ids
      description: Read multiple drug products for the provided drug_product_ids
      parameters:
        - name: drug_product_ids
          in: path
          required: true
          schema:
            type: array
            items:
              type: integer
            minItems: 1
          style: simple
          explode: false
          description: drug_product_ids primary keys of the required products

      responses:
        '200':
          description: Successfully retrieved product
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/product'

Based on:https://swagger.io/docs/specification/serialization/#uri-templates
Then in my method, I see a list coming in as a parameter, so I am converting to string and then creating the SQL using string formatting.
def read_products_many(drug_product_ids):

    conn_ariel = get_connection()
    cursor_ariel = conn_ariel.cursor()

    print(drug_product_ids)          # --> [4670, 4671]
    print(type(drug_product_ids))    #  --> List

    # convert to string for use in IN clause in SQL
    drug_product_ids = [str(x) for x in drug_product_ids]

    print("read_many product, id", drug_product_ids)
    # Create the list of products from our data
    sql = """
        SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
        FROM DIM_DRUG_PRODUCT
        WHERE DRUG_PRODUCT_ID in ({0})
        AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%'
        """.format(",".join(drug_product_ids))

    print("SQL")
    print(sql)
    cursor_ariel.execute(sql)

    product = None
    products = []

    for row in cursor_ariel.fetchall():
        r = reg(cursor_ariel, row, False)

        product = {
            "drug_product_id"           :   r.DRUG_PRODUCT_ID,
            "preferred_trade_name"      :   r.PREFERRED_TRADE_NAME,
            "product_line"              :   r.PRODUCT_LINE,
            "product_type"              :   r.PRODUCT_TYPE,
            "flag_passive"              :   r.FLAG_PASSIVE,
            "product_number"            : r.PRODUCT_NUMBER

        }
        products.append(product)

    pool.release(conn_ariel)
    return products

SQL being returned when I enter this URL:
localhost:5000/api/read/products_many/4671,4670

is correct as:
SELECT DRUG_PRODUCT_ID, PREFERRED_TRADE_NAME, PRODUCT_LINE, PRODUCT_TYPE, FLAG_PASSIVE , PRODUCT_NUMBER
        FROM DIM_DRUG_PRODUCT
        WHERE DRUG_PRODUCT_ID in (4671,4670)
        AND PREFERRED_TRADE_NAME NOT LIKE '%DO NOT USE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%DELETE%'
        AND UPPER(PREFERRED_TRADE_NAME) NOT LIKE '%TEST%'


Q: Mounted Volumes for IBM Bluemix CF Apps IBM Containers on Bluemix has the support for mounting volumes and use across containers. Is there any way we can have a similar shared volumes kind w.r.t Bluemix CF Apps?

A: Cloud Foundry applications on IBM Bluemix can use Bluemix's Object Storage service for shared storage between applications.
Cloud Foundry does not support sharing volumes across instances and discourages users from writing the the filesystem as storage.
Using Object Storage, you have an API to access and share files between applications.


Q: How do I disable rails form_with update functionality I have the following form to add somebody to a waiting list.
<%= form_with(model: waitinglist, url: '/join', local: true) do |form| %>

    <%= form.text_field :email %>

    <%= form.submit %>

<% end %>

This works fine and it will post and add somebody to the waiting list. However when the page reloads the form goes into some sort of automatic resource mode that where the submit button magically changes to update and then the form submit magically changes to the HTTP Patch method.
I'm trying to understand what is doing this and I can't find anything in the docs.
How do I create a regular form that just posts to an end point but still validates the model? (and removes this update functionality).
edit added controller
class WaitinglistsController < ApplicationController
  before_action :set_waitinglist, only: [:show, :edit, :update, :destroy]

  # GET /waitinglists/new
  def new
    @waitinglist = Waitinglist.new
  end

  # POST /waitinglists
  # POST /waitinglists.json
  def create
    @waitinglist = Waitinglist.new(waitinglist_params)

    if @waitinglist.save
      flash[:notice] = "You have been added to the waiting list"
      render :new
    else
      render :new
    end
  end

  private
  # Use callbacks to share common setup or constraints between actions.
  def set_waitinglist
    @waitinglist = Waitinglist.find(params[:id])
  end

  # Never trust parameters from the scary internet, only allow the white list through.
  def waitinglist_params
    params.require(:waitinglist).permit(:email)
  end
end

A: You are keeping a copy of your persisted waitinglist variable around between page loads. When your new page is rendered for the second time, since the waiting list has already been persisted, it is doing all the magical default Rails behaviours, which include updating labels for the submit button (create vs update), and the form's method (post vs patch).
You will want to create a new waitinglist if you are going to re-render the new page:
  def create
    @waitinglist = Waitinglist.new(waitinglist_params)

    if @waitinglist.save
      @waitinglist = Waitinglist.new #
      flash[:notice] = "You have been added to the waiting list"
      render :new
    else
      render :new
    end
  end

A: I think what u should do is if the waiting list is saved, redirect to new instead of render new. When u redirect to action it will call the action so a new object will be created. When u do render it render the view and I will have your persisted object, that’s why it is trying to update.


Q: Cretate multiple shared secrets in a (selfmade) public/privavte key infrastructure I just try to understand cryptography, please be concern. Its not meant to be secure or professional. I create 3 numbers for each party. a public key, a secret key and a modulus. The first party (A) creates his keys
let pri = 133
let mod = 256
let pub = mod - pri

and shares "mod" and "pub" to other partys (B, C). When B want to encrypt a string he takes A's public key and modulus and do
// B encrypts
let enc = ( input + pubA ) % modA

A on his side is doing
// B decrypts
let dec = ( enc + priA) % modA

to decrypt it. My problem is, i can create multiple keypairs but only 1 associated public key to each secret key because i have to share the modulus of each pair for en/decryption.
Is it possible (in this situation) to create multiple publics numbers for a single private number? And if so, how can i do it?
Thank you (and sorry if this is a poor question)
EDIT Even if its not "good" to create your own cipher i want to do so..
I recognized that i missed the secret exponent d so that phi divides (e * expo)-1.
/* Pseude code */

p = q = primes()
n = p * q
phi = (p-1) * (q-1)

e = 3
d = ? // <-- have to find my own secret exponent!

if( gcd(e, p-1) != gcd(e, q-1) ) exit(0)

expo = 0
for(expo < 100000)
    if( (e * expo)-1 == phi ) ) d = expo

And therefore i could have
public(n,e)
private(n,d)

so i can share (n,e). Is that correct?


Q: WebDeploy with MSdeploy.exe fails to sync GAC Assembly because dll(s) locked by another process I'm having this problem using msdeploy to sync GAC assembly to many Application Servers.
When I run this command
msdeploy -verb:sync -source:gacAssembly="'MyAssembly'" -dest:gacAssembly,computername=DESTINATIONSERVER

I obtain this error:
*Microsoft.Web.Deployment.DeploymentException:
(28/09/2010 16.46.37) An error occurred when the request was processed on the remote computer.
---> Microsoft.Web.Deployment.DeploymentClientServerException: An error was encountered when processing 'INPS.DNA.dll'.
---> Microsoft.Web.Deployment.DeploymentException: The error code was 0x80070020.
---> System.IO.IOException: The process cannot access 'C:\Windows\assembly\GAC_MSIL\MYASSEMBLY\1.0.0.0__a31fe99d2f98435c\MYASSEMBLY.dll' because it is being used by another process.
   at Microsoft.Web.Deployment.Win32Native.RaiseIOExceptionFromErrorCode(Win32ErrorCode errorCode, String maybeFullPath)
   at Microsoft.Web.Deployment.FileStreamEx.CreateInstance(String path, FileMode fileMode, FileAccess fileAccess)
   at Microsoft.Web.Deployment.FilePathProvider.Add(DeploymentObject source, Boolean whatIf)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at Microsoft.Web.Deployment.DeploymentObject.Update(DeploymentObject source,DeploymentSyncContext syncContext)
   at Microsoft.Web.Deployment.DeploymentSyncContext.HandleUpdate(DeploymentObject destObject, DeploymentObject sourceObject)
   at Microsoft.Web.Deployment.DeploymentSyncContext.SyncDirPathChildren(DeploymentObject destRoot, DeploymentObject sourceRoot)
   at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenNoOrder(DeploymentObject dest, DeploymentObject source)
   at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenOrder(DeploymentObject dest, DeploymentObject source)
   at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject
destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, Conten
tRootTable contentRootTable)
   at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentWorkerR
equest workerRequest)
   --- End of inner exception stack trace ---
   at Microsoft.Web.Deployment.StatusThreadHandler.CheckForException()
   at Microsoft.Web.Deployment.AgentClientProvider.RemoteDestSync(DeploymentObje
ct sourceObject, DeploymentSyncContext syncContext)
   at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject
destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, Conten
tRootTable contentRootTable)
   at Microsoft.Web.Deployment.DeploymentObject.SyncTo(DeploymentProviderOptions
 providerOptions, DeploymentBaseOptions baseOptions, DeploymentSyncOptions syncO
ptions)
   at MSDeploy.MSDeploy.ExecuteWorker()
Error count: 1.*
If I execute IISRESET on DESTINATIONSERVER the error doesn't occur!
My question is:
It's possible to unlock DLL without perform an IISRESET command?
I think I can avoid to restart entire Web Server.
Can you help me'
Thanks a lot!
Best regards.

A: What about using the recyleApp provider to stop and start the app pool?
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StopAppPool",computerName=remote-computer
... do your real deployment ...
msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site",recycleMode="StartAppPool",computerName=remote-computer


Q: How to reduce the time of curl call? For some reason my curl call is very slow. Here is the code I used.
            $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTPHEADER,array('Expect:','Accept: application/xml'));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //curl_setopt(curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //curl_setopt($ch, CURLOPT_NOBODY, !($options['return_body']));
        curl_setopt($ch, CURLOPT_SSLVERSION, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
        curl_setopt($ch,CURLOPT_TIMEOUT_MS,0);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
        $result = curl_exec($ch);

        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);

        curl_close($ch);

we have 9000 records to fetch
its taking 56 mins
To check execution time for each record I use curl_getinfo() function;
and each record take ~0.46 seconds!!
I want to reduce this seconds.
any luck it can reduce to 15 mins?

A: Try to set one more cURL option.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

Also try to use curl_multi_exec.

A: Use file_get_contents($url)
example with User Agent
<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>


Q: Realm from JSON in async in background I'd like to work to write Realm from JSON in async in background, but I can't understand why my code isn't work as must.
override func viewDidLoad() {
    super.viewDidLoad()

    myFunc()

}

and myFunc():
func myFunc() {

        let realm = try! Realm()

        // get file JSON from local device and write data from it to RealmDB
        if realm.isEmpty {

            //local file JSON
            let file = Bundle.main.path(forResource: "file", ofType: "json")!
            let url = URL(fileURLWithPath: file)
            let jsonData = NSData(contentsOf: url)!

            //Serialization JSON
            let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: [])

            DispatchQueue.main.async {

            realm.beginWrite()

            //Create data from JSON to our objects
            realm.create(DataRoot.self, value: json, update: true)

            try! realm.commitWrite()

            }
        }
    }

DB is creating, but next step (as I see) is in error:
  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return (transport.filter("id == 1").first?.routes.count)!
    }

So, I'd like to wait full writing DB in background (show progress view, for example) and go next step.

A: You have to check for optional in numberOfRows Method and do it like this
    func myFunc() {
        let queue1 = DispatchQueue(label: "com.appname.queue")
        queue1.async {
            let realm = try! Realm()
            // get file JSON from local device and write data from it to RealmDB
            if realm.isEmpty {

                //local file JSON
                let file = Bundle.main.path(forResource: "file", ofType: "json")!
                let url = URL(fileURLWithPath: file)
                let jsonData = NSData(contentsOf: url)!

                //Serialization JSON
                let json = try! JSONSerialization.jsonObject(with: jsonData as Data, options: [])
                realm.beginWrite()

                //Create data from JSON to our objects
                realm.create(DataRoot.self, value: json, update: true)

                try! realm.commitWrite()

                DispatchQueue.main.async {

                    self.tableview.reloadData()

                }

            }
        }
    }

    override func tableView(_ tableView: UITableView,     numberOfRowsInSection section: Int) -> Int {
        if let routes = transport.filter("id == 1").first?.routes {
            return routes.count
        }
            return 0
    }

A: To generally answer your question: the high level Realm feature you want to be using here is notifications.
You should be architecting your app in such a way that the data you want to use to back a view controller can be represented in a Realm query or notification, so that when the underlying data for a view or controller changes, you can perform the relevant view update actions.
There are some other problems with your code, such as potentially accessing a Realm instance from a different thread than the one on which it was created. I suggest you read more about this in Realm's Threading documentation.


Q: How do I change the Created By for my crossrider plugin? When users install my browser it shows the plugin created by the name listed under my crossrider dev account.  I'd like to change that to my company name but the site won't let me change the name.  How can I change it to show my company name vs my first and last name?  Thanks

A: Email support@crossrider.com from the email address currently associated with the account. In the email, provide:

*

*Current Account Name: the name currently associated with the account

*Extension ID(s): One or more IDs of extensions in the account

*New Account Name: the desired name for the account

[Disclosure: I am a Crossrider employee]


Q: How to get device ID in angular js? I need to find the device ID on which my app is running. I am using angular js and ionic. Is there any way to obtain the device ID?

A: Option 1: Use AngularJS run
// Calling the rootScope to handle the  ondevice ready
angular.module('myApp').run(['$rootScope', function($rootScope) {
  document.addEventListener('deviceready', function() {
      $rootScope.$apply(function() {
          $rootScope.myVariable = "variable value";
          try {
            $rootScope.uuid = device.uuid; //always use device object after deviceready.**
            alert($rootScope.uuid);
            //onapploginx(uuid);
          } catch (e) {
            alert(e);
          }
          // Register the event listener
          document.addEventListener("backbutton", onBackKeyDown, false);
      });
  });
}]);

Option 2: Use JS only
define the onLoad in the body
<body id="main_body" ng-app='myApp' ng-controller='DemoController' onload="onLoad()">

call addEventListener for device ready and then call the function of onDeviceReady
function onLoad() {
  console.log("i am onload");
  document.addEventListener("deviceready", onDeviceReady, false);
}

// device APIs are available
//
function onDeviceReady() {
  try {
    var uuid = device.uuid; //always use device object after deviceready.**
    alert("uuidx:",uuid);
  } catch (e) {
    alert(e);
  }
}


Q: HttpWebResponses: How efficient is MemoryStream.CopyTo vs chunking? I'm running into a problem with downloading large JSON objects from an API. Usually, this documents are small in size, but occasionally they are quite large (100k+). This puts the large object heap into play and there are some performance concerns.
Here is the guts of the downloader method that returns the response bytes.
using (var httpWebResponse = (HttpWebResponse)request.GetResponse())
{
    byte[] responseBytes;
    using (var responseStream = httpWebResponse.GetResponseStream())
    {
        using (var memoryStream = new MemoryStream())
        {
            if (responseStream != null)
            {
               responseStream.CopyTo(memoryStream);
            }
            responseBytes = memoryStream.ToArray();
        }
     }
     return responseBytes;
 }

If the end goal is to get the contents of the webresponse into a byte array, is this the most efficient way to do this? In the past I would just read the stream in chunks. I've been told that this is less efficient than CopyTo for the 90% of the time (when the JSON response is sub-85k), but better for the other 10%.
I cannot seem to find a general consensus on this. Any input would be appreciated.


Q: python-shell problem with sync inside javascript I'm using python-shell to run a Python code that return some messages inside a JavaScript environment, but the messages come out of sync. The first message returns at the right moment, but then all other messages comes out together at the end, not one by one.
When I run the test.py alone the messages come in the right way, which possibly means that is not a problem with my python code. Despite all other messages is logged together, the time when they are executed inside the python code is right, what can be seeing by the time: inside each message.
But what happens in my browser environment is the message <2>FIRST TEST logged first, and then <3>TEST and <4>MORE TEST are logged together after 10 seconds.

This is my python code test.py:
import sys
import time
import threading

def test():
    start = time.time()
    end1 = time.time()
    print("<2>FIRST TEST time: {}".format(end1 - start))

    time.sleep(5)
    end2 = time.time()
    print("<3>TEST time: {}".format(end2 - start))

    time.sleep(5)
    end3 = time.time()
    print("<4>MORE TEST time: {}".format(end3 - start))

x = threading.Thread(target=test)
x.start()
sys.stdout.flush()

This is my JavaScript code execPyShell.ts:
const exec: () => void = () => {
    console.log('Start')
    let pyshell = new PythonShell('./engine/test.py');
    let newLogs: string[] = [];

    pyshell.on('message', function(message: string) {
        console.log(message);
    })

    pyshell.end(function (err: any) {
    if (err){
        throw err;
    };
        console.log('Finished');
    });
}

A: Solved! I forgot that I had to add
sys.stdout.flush()

After every print() called to force it to flush the buffer.


Q: How to create google play menu in xamarin I'm new to Xamarin. How can i design a pop up menu that looks like google play menu in Xamarin ? I.e see the image below :

A: There are several ways to go about making a fly-out menu, which is what I believe you are after. The very basic approach, is to add something similar to the following to your AXML:
<?xml version="1.0" encoding="utf-8"?>
<flyoutmenu.FlyOutContainer xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <include
        layout="@layout/MenuLayout" />
    <include
        layout="@layout/ContentLayout" />
</flyoutmenu.FlyOutContainer>

Source: http://blog.neteril.org/blog/2013/04/19/fly-out-menu-xamarin-android/
Another Source: http://www.appliedcodelog.com/2016/01/navigation-drawer-using-material-design.html
I hope this helps!


Q: AWS Elastic BeanStalk Security Group I am trying to create Worker Environmenton EBS with Sample Application of Node js which should use existing Security group on VPC.
I create this environment inside VPC (Virtual Private Cloud).
When I create this environment, I keep following configuration for VPC.
Security Group which is selected here is already exist.

In the next screen, I also select instance profile and service role which also exist.

While I create Environment with this setting, It does create Environment fine but it always create new Security group instead of using existing security group.

Why it always create new Security group and not use existing one ?
I want to reuse Security group and not create separate for each worker environment.
Appreciate if someone can guide me in right direction.
Thanks in advance.

A: Beanstalk uses the security group you asked for, but on creation it also creates a unique one for that configuration. If you launch your instance it will be in the security group as expected.

A: Instead of stopping it from being created, was able to modify its rules such that I changed to just allow port 22 access only from my private security group.
Namespace: aws:autoscaling:launchconfiguration
OptionName: SSHSourceRestriction
Value: tcp, 22, 22, my-private-security-group

Visit : https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html#SSHSourceRestriction


Q: How can I get an entity from Doctrine Fixture reference? I have added data fixtures in my project that relies on referencing entity objects from each other.
In data fixture one, I have added entity references such as:
            // GroupEntity_Fixtures.php file
    $this->addReference('GROUP_USER', $groupUser);
    $this->addReference('GROUP_ADMIN', $groupAdmin);

Where $groupAdmin and $groupUser are both Group() entities. In my second fixtures file I want to add those entities to my User entity via:
             //UserEntity_Fixtures.php file
             $userActive->addGroup($this->getReference('GROUP_USER'));

$userActive is a User entity with a Many to Many relationship to Group Entity. Unfortunately it seems that I am only passing in a proxy of the entity and not the entity itself which renders the following error:
 [Symfony\Component\Debug\Exception\ContextErrorException]
  Catchable Fatal Error: Argument 1 passed to Blogger\BlogBundle\Entity\User:
  :addGroup() must be an instance of Blogger\BlogBundle\Entity\groups, instan
  ce of Proxies\__CG__\Blogger\BlogBundle\Entity\Group given, called in /home
  /na/Practice/src/Blogger/BlogBundle/DataFixtures/ORM/CreateUserController_S
  ignUpForm_UserEntity_Fixtures.php on line 27 and defined in /home/na/Practi
  ce/src/Blogger/BlogBundle/Entity/User.php line 305

How do I convert the reference from a proxy to the entity it expects?

Code for Group Fixture:
<?php
// DataFixtures/ORM/GroupEntity_Fixtrues.php

namespace Blogger\BlogBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Blogger\BlogBundle\Entity\User;
use Blogger\BlogBundle\Entity\Group;

class GroupEntity_Fixtures extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * {@inheritDoc}
     */
     public function load(ObjectManager $manager)
     {
        $groupUser = new Group();
        $groupUser->setName('GROUP_USER');
        $groupUser->setRole('ROLE_USER');
        $manager->persist($groupUser);

        $groupAdmin = new Group();
        $groupAdmin->setName('GROUP_ADMIN');
        $groupAdmin->setRole('ROLE_USER,ROLE_ADMIN');
        $manager->persist($groupAdmin);

        $manager->flush();

        $this->addReference('GROUP_USER', $groupUser);
        $this->addReference('GROUP_ADMIN', $groupAdmin);
     }

     public function getOrder()
     {
        return 1;
     }
}

Code for User Fixture
<?php
// DataFixtures/ORM/CreateUserController_SignUpForm_UserEntity_Fixtrues.php

namespace Blogger\BlogBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Blogger\BlogBundle\Entity\User;
use Blogger\BlogBundle\Entity\Group;

class CreateUserController_SignUpForm_UserEntity_Fixtures extends AbstractFixture implements OrderedFixtureInterface
{
    /**
     * {@inheritDoc}
     */
     public function load(ObjectManager $manager)
     {
        $groupUser2 = new Group();
        $groupUser2->setName('GROUP_USER');
        $groupUser2->setRole('ROLE_USER');
        $manager->persist($groupUser2);

        // This person represents an active (email verified) user.
        $userActive = new User();
        $userActive->setPassword("passwordActive");
        $userActive->setEmail("testActive@test.com");
        $userActive->setUserName("testActive");
        $userActive->setPassword(crypt($userActive->getPassword(),$userActive->getSalt()));
        $userActive->setEmailToken(md5(uniqid(rand(), true)));
        $userActive->addGroup($groupUser2);
        //$userActive->getGroups()->add($groupRepository->getGroupByName("BASIC_USER"));

        // This person represents an unactive (email not verified) user.
        $userUnactive = new User();
        $userUnactive->setPassword("passwordUnactive");
        $userUnactive->setEmail("testUnactive@test.com");
        $userUnactive->setUserName("testUnactive");
        $userUnactive->setPassword(crypt($userUnactive->getPassword(),$userUnactive->getSalt()));
        $userUnactive->setEmailToken(md5(uniqid(rand(), true)));

        // Persist objects into the database
        $manager->persist($userActive);
        $manager->persist($userUnactive);
        $manager->flush();

     }

     public function getOrder()
     {
        return 2;
     }
}

Code for Group Entity:
/**
 * @ORM\ManyToMany(targetEntity="User", inversedBy="groups")
 */
private $users;

Code for User Entity:
/**
 * @ORM\ManyToMany(targetEntity="Group", mappedBy="users")
 */
protected $groups;

Added Group Methos:
/**
 * Add groups
 *
 * @param \Blogger\BlogBundle\Entity\groups $groups
 * @return User
 */
public function addGroup(\Blogger\BlogBundle\Entity\groups $groups)
{
    $this->groups[] = $groups;

    return $this;
}

A: The addGroup method has the wrong type hint:
It should be:
/**
 * Add groups
 *
 * @param \Blogger\BlogBundle\Entity\Group $groups
 * @return User
 */
public function addGroup(\Blogger\BlogBundle\Entity\Group $groups)
{
    $this->groups[] = $groups;

    return $this;
}

Notice \Blogger\BlogBundle\Entity\Group instead of \Blogger\BlogBundle\Entity\groups.


Q: how to print more than one rows through PL/SQL procedure? How to write a procedure where user will give department number, and the procedure will show the list of those employees who are working in that department.
My procedure:
create or replace procedure p1(
  dno in number,
  name out varchar2 )
is
begin
 select ename
   into name
   from emp
  where deptno=dno;
end;

PLSQL:
declare
   dno emp.deptno%type:=:dept;
   name emp.ename%type;
begin
  p1(dno,name );
  dbms_output.put_line(name);
end;

But this is showing an error:
ORA-01422: exact fetch returns more than requested number of rows

How can I print multiple values through procedure?

A: I haven't tried your code, but you seen to call the procedure p1(dno,name ); and insert name in it.
But name can only be output becuase of the OUT, you need to use IN OUT in your procedure at least.


Q: How do I secure a SQL Server 2005 database? I have a database for a web application that is home to some personal information about my users.
What should I do to make sure the data is secure?
Encrypting the data makes sense, of course... but what about stopping somebody from getting on the machine to begin with?
What do I do about the developers that need access to the data, to make fixes, etc...?
Is there a document or best practice site that I can use as a guide?

A: Depending on the type of data I'm not sure that encryption is necessary providing you secure access to the system and the database itself.  All of our production database servers are behind a firewall.  Only systems that are on the administrative network are allowed access through the firewall and then only on specific, required ports.  Database servers don't host web servers.
Access to the database servers themselves is strictly limited to DBAs and platform support personnel.  They use administrative logins, not their personal login ids.  That way if their personal account is compromised the database servers aren't.
For web servers only web admins and platform support have access (I happen to wear two hats, web developer and web admin, although that is rare in our organization).
Developers have access to shares where they can publish their application, usually coordinated with the web admin for any setup/configuration.  Some senior developers are given administrator access to databases in order to create/modify schemas.
Usually, what happens is you develop using a locally installed database server, upload code to QA servers that have a little looser access policy, but are only accessible from company networks, then have the DBAs copy the database schema and roles to production and publish your app to the production web server.
Web apps are often configured to run under limited credential service accounts which have read/write, but not admin, access to the database.  I typically encrypt any part of my web.config that contains connection information as well.
The general idea is to give enough access to get your job done without too much bother, but limit access to the minimum required.
Oh.  And no "real" data on development or QA servers.
[EDIT] We don't keep SSNs or credit card numbers.  If you do, you'll need to be even more careful.  Most of my apps do access logging, some are required to due to HIPPA, but I find that it is a good practice for just about anything meaningful

A: Well the developers should probably do all their work on a development database that doesn't contain sensitive information to start with.

A: Here in the UK we have legislation known as the Data Protection Act. If you worked for a UK company I would advise you to speak to your company's 'data controller' (being the individual whom the Information Commissioner's Office can pursue legally in instances of non-compliance) and they will be able to furnish you with a definitive answer about what 'secure' means as regards the data in question, probably enshrined in a written company policy.
If you are in the US I'd guess your corporation might have a bunch of highly paid lawyers who will be able to similarly give a definitive answer :)
I'm no legal expert but would suggest that obfuscating data does not make it fit for any purposes other than that for which it was obtained e.g. integration testing by developers using obfuscated 'real life' data is probably a no-no.

A: You need to pratice standard security for a windows server.  A good place to start is to use integrated logins rather that SQL logins.
You will need to study the books on-line.  You can give some users read-only access.  Others can be denied access to sensitive tables.

A: I would use Active Directory to control access to SQL Server or any network resource.  By grouping the users and applying security to the group, it will make it so much easier to make changes in the future.
Here is a guide from Microsoft on SQL Server 2005 Security Best Practices:
http://download.microsoft.com/download/8/5/e/85eea4fa-b3bb-4426-97d0-7f7151b2011c/SQL2005SecBestPract.doc
*Note: it downloads a Word document, so you will need MS Word or the MS Word viewer
This document has a lot of detail so you may want to grab some coffee first :).
However, I agree with the others, active development shouldn't happen against production data.  We currently use a process of cleaning production data before it gets to the QA or Dev environments.
Another option we explored is developing a solution to generate data for Dev and QA.


Q: Can;t install lxml package on windwos 11 "PS D:\Complete-Python-3-Bootcamp-master\12-Advanced Python Modules\puzzle_unzip> pip install lxml
Collecting lxml
  Using cached lxml-4.9.1.tar.gz (3.4 MB)
  Preparing metadata (setup.py) ... done
Installing collected packages: lxml
  DEPRECATION: lxml is being installed using the legacy 'setup.py install' method, because it does not have a 'pyproject.toml' and the 'wheel' package is not installed. pip 23.1 will enforce this behaviour change. A possible replacement is to enable the '--use-pep517' option. Discussion can be found at https://github.com/pypa/pip/issues/8559
  Running setup.py install for lxml ... error
  error: subprocess-exited-with-error

  × Running setup.py install for lxml did not run successfully.
  │ exit code: 1
  ╰─> [96 lines of output]
      Building lxml version 4.9.1.
      Building without Cython.
      Building against pre-built libxml2 andl libxslt libraries
      running install
      C:\Users\lohar\AppData\Local\Programs\Python\Python311\Lib\site-packages\setuptools\command\install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
        warnings.warn(
      running build
      running build_py
      creating build
      creating build\lib.win-amd64-cpython-311
      creating build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\builder.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\cssselect.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\doctestcompare.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\ElementInclude.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\pyclasslookup.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\sax.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\usedoctest.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\_elementpath.py -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\__init__.py -> build\lib.win-amd64-cpython-311\lxml
      creating build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\__init__.py -> build\lib.win-amd64-cpython-311\lxml\includes
      creating build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\builder.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\clean.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\defs.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\diff.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\ElementSoup.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\formfill.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\html5parser.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\soupparser.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\usedoctest.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\_diffcommand.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\_html5builder.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\_setmixin.py -> build\lib.win-amd64-cpython-311\lxml\html
      copying src\lxml\html\__init__.py -> build\lib.win-amd64-cpython-311\lxml\html
      creating build\lib.win-amd64-cpython-311\lxml\isoschematron
      copying src\lxml\isoschematron\__init__.py -> build\lib.win-amd64-cpython-311\lxml\isoschematron
      copying src\lxml\etree.h -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\etree_api.h -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\lxml.etree.h -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\lxml.etree_api.h -> build\lib.win-amd64-cpython-311\lxml
      copying src\lxml\includes\c14n.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\config.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\dtdvalid.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\etreepublic.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\htmlparser.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\relaxng.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\schematron.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\tree.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\uri.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\xinclude.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\xmlerror.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\xmlparser.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\xmlschema.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\xpath.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\xslt.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\__init__.pxd -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\etree_defs.h -> build\lib.win-amd64-cpython-311\lxml\includes
      copying src\lxml\includes\lxml-version.h -> build\lib.win-amd64-cpython-311\lxml\includes
      creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources
      creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\rng
      copying src\lxml\isoschematron\resources\rng\iso-schematron.rng -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\rng
      creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
      copying src\lxml\isoschematron\resources\xsl\RNG2Schtrn.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
      copying src\lxml\isoschematron\resources\xsl\XSD2Schtrn.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl
      creating build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
      copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_abstract_expand.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
      copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_dsdl_include.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
      copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_message.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
      copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_schematron_skeleton_for_xslt1.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
      copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\iso_svrl_for_xslt1.xsl -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
      copying src\lxml\isoschematron\resources\xsl\iso-schematron-xslt1\readme.txt -> build\lib.win-amd64-cpython-311\lxml\isoschematron\resources\xsl\iso-schematron-xslt1
      running build_ext
      building 'lxml.etree' extension
      creating build\temp.win-amd64-cpython-311
      creating build\temp.win-amd64-cpython-311\Release
      creating build\temp.win-amd64-cpython-311\Release\src
      creating build\temp.win-amd64-cpython-311\Release\src\lxml
      "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -DCYTHON_CLINE_IN_TRACEBACK=0 -Isrc -Isrc\lxml\includes -IC:\Users\lohar\AppData\Local\Programs\Python\Python311\include -IC:\Users\lohar\AppData\Local\Programs\Python\Python311\Include "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt" /Tcsrc\lxml\etree.c /Fobuild\temp.win-amd64-cpython-311\Release\src\lxml\etree.obj -w
      cl : Command line warning D9025 : overriding '/W3' with '/w'
      etree.c
      C:\Users\lohar\AppData\Local\Temp\pip-install-v8_cypj7\lxml_b1e7951ab83046e384fffcd4610d3736\src\lxml\includes/etree_defs.h(14): fatal error C1083: Cannot open include file: 'libxml/xmlversion.h': No such file or directory
      Compile failed: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      creating Users
      creating Users\lohar
      creating Users\lohar\AppData
      creating Users\lohar\AppData\Local
      creating Users\lohar\AppData\Local\Temp
      "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\bin\HostX86\x64\cl.exe" /c /nologo /O2 /W3 /GL /DNDEBUG /MD -I/usr/include/libxml2 "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\14.34.31933\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\VS\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.22000.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\um" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\shared" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\winrt" "-IC:\Program Files (x86)\Windows Kits\10\\include\10.0.22000.0\\cppwinrt" /TcC:\Users\lohar\AppData\Local\Temp\xmlXPathInituop21067.c /FoUsers\lohar\AppData\Local\Temp\xmlXPathInituop21067.obj
      xmlXPathInituop21067.c
      C:\Users\lohar\AppData\Local\Temp\xmlXPathInituop21067.c(1): fatal error C1083: Cannot open include file: 'libxml/xpath.h': No such file or directory
      error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.34.31933\\bin\\HostX86\\x64\\cl.exe' failed with exit code 2
      *********************************************************************************
      Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
      *********************************************************************************
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure

× Encountered error while trying to install package.
╰─> lxml

note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
PS D:\Complete-Python-3-Bootcamp-master\12-Advanced Python Modules\puzzle_unzip> "

*

*im trying to install lxml library by pip install lxml.

*i also installed vs build tools 2022 .

*after that i stuck on this error i tryed multiple things but they dont work

*thigs that i tried manually installing packages.

*multiple internet solutions

im expecting a solution to install lxml on W11 machine.and also im using vs code and pycharm python version 3.11 and pip version 22.3.1

A: The Python lxml module is a language-binding / wrapper for two C libraries.
For Windows they provide binary builds that include these libraries. Otherwise it will be pain and suffering getting it installed and running on Windows. Because it's Windows. "Developers, developers, developers".. (As lxml developers put it: "users of that platform usually fail to build lxml themselves")
Normally you should get the binary distribution when doing install through pip but in this case you don't.

*

*Try to pin an older version, maybe binaries are available for it:
pip install lxml==4.9.0

*Try to download the lxml binary distribution by Christoph Gohlke available here.
You can install the wheel file also via pip.
Sources:

*

*Where are the binary builds?

*Source builds on MS Windows


Q: Reliable Ways to Send Large Files to Clients we have a need to regularly provide large files to clients on a daily or weekly basis.  Currently our process is this:

*

*Internal process creates the file and places it in a specific folder

*Our client connects via SFTP and downloads the file

This work well when the files are small.  As they get bigger (50-100 GB in size), we keep getting network interruptions and internal disk space related issues.
What I'd like to see is the following:

*

*Our internal process creates the file.

*This file is copied to an intermediary service (similar to something like FileDropper).

*Our client will download the file from this intermediary service.

I'd like to know if other people had similar issues and what possible solutions are in place.  File Dropper works great for non-business related files but obviously I won't be putting client data on there.  We also have an Office 365 subscription.  I tried to see what I could use with that but I haven't found anything yet that would help solve this.
Any hints, suggestions or feedback is much appreciated!

A: Consider Amazon S3.
I have used it several times in the past and it is very reliable both for processing a lot of files and for processing large files


Q: PowerShell How to use -and in Where-Object I want to filter a command result using two conditions. Here are my commands
 $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property ConfigurationFlags -NotLike '*DISABLED*' | ft Name, InstanceId -AutoSize

and the next filter is
 $list=Get-PnpDevice | Sort-Object -Property Name | Where-Object -Property FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize

both of them works separately but I want to join them using and command. I tried to use -AND as following command but it keeps raising errors

 Get-PnpDevice | Sort-Object -Property Name | Where-Object{
      ( ConfigurationFlags -NotLike '*DISABLED*') -and
      ( FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize

A: Simply use the The $_ automatic variable in your Where-Object to reference the property names:
Get-PnpDevice | Sort-Object -Property Name | Where-Object{
      ( $_.ConfigurationFlags -NotLike '*DISABLED*') -and
      ( $_.FriendlyName -like '*touch screen*' ) }| ft Name, InstanceId -AutoSize

A: You can pipe 'Where' clauses together... it's simpler syntax and easier to read
Get-PnpDevice | Sort-Object -Property Name | Where ConfigurationFlags -NotLike '*DISABLED*' | Where FriendlyName -like '*touch screen*' | ft Name, InstanceId -AutoSize


Q: Pay with paypal and recurring using billing agreement API I just want to understand that how can I redirect user to PayPal account ==> login ==> agreed to payment teand based on selection I can call my Billing Agreement Rest API.
Do I need to setUp My Own UI to process payment ?

A: The most important thing here is that you cannot sign a billing agreement without a billing plan
So the first thing you need to consider is how you could create a plan.
Its very simple just trigger this api: https://developer.paypal.com/docs/api/payments.billing-plans/v1/
Now you have your plan Id
now you can subscribe a user with this plan id
by triggering this API
https://developer.paypal.com/docs/api/payments.billing-agreements/v1/#billing-agreements_create


Q: sending email with delayed job within Rails_admin causes an error I have a custom collection action in Rails Admin as follows:
require 'rails_admin/config/actions'
require 'rails_admin/config/actions/base'
module RailsAdminSendNewsletter
end

module RailsAdmin
  module Config
    module Actions
      class SendNewsletter < RailsAdmin::Config::Actions::Base

      # Is the action on a model scope (Example: /admin/team/export)
       register_instance_option :collection? do
         true
       end

       register_instance_option :link_icon do
          'icon-share'
       end

       register_instance_option :pjax? do
           false
         end

        register_instance_option :controller do
          Proc.new do
              if request.xhr?
                  resources = Resource.where(:for_newsletter => true)
                  subscriber = Subscriber.all.each do |subscriber|
                     NewsletterMailer.delay.newsletter(subscriber, resources)
                  end
                  resources.each do |resource|
                        resource.update_column(:sent_on, Time.now)
                      end
              end
                flash[:success] = "The Newsletter has successfully been sent."
                redirect_to back_or_index
          end
      end

      end
    end
  end
end

produces the following error:
ArgumentError (wrong number of arguments (2 for 1)):
  lib/rails_admin_send_newsletter.rb:30:in `block (3 levels) in <class:SendNewsletter>'
  lib/rails_admin_send_newsletter.rb:29:in `each'
  lib/rails_admin_send_newsletter.rb:29:in `block (2 levels) in <class:SendNewsletter>'

Here is the newsletter mailer:
class NewsletterMailer < ActionMailer::Base
    default from: ' "Agile Designers" <info@agiledesigner.com>'

    def newsletter(subscriber, resources)
        @subscriber = subscriber
        @resources = resources
        @twitter = "https://twitter.com/agiledesigners"
        mail(:to => subscriber.email, :subject => "Agile Designer Newsletter")
    end
end

I don't understand what causes it
Any help appreciated.


Q: iPhone SDK have a different title on the tab bar and the navigation bar I have a simple question (maybe not a simple answer). Currently I have an iPhone app and I tab bar and navigation set up on it. When I set the self.title it puts it in both the tab bar and the navigation bar. I was wondering if there was a way to have a different title on the navigation bar and tab bar?

A: You're setting the title of the whole view, which in turn automatically sets the title of the tabBar and the nav controller. To set the title of them each individually,
You first set the nav bar by accessing the nav item:
[[self navigationItem] setTitle:(NSString *)];

Then you set the tabBar title by accessing the tab bar item and setting its title like so:
[self.tabBarItem setTitle:(NSString *)];

Good Luck!

A: use self.navigationItem.title for the navigation bar.

A: This is a common mistake and happened to me so many times.
To get around this, every ViewController comes with a navigationItem property giving you even further options.
Use following line inside your ViewControllers to set the title:
self.navigationItem.title = @"Your Desired Title";


Q: Event not working on templated dojo widget My widget makes the form but the event that is suposed to happen doesn't. When the button is clicked it is supposed to grab the value in the input box then put it into URL that is being requested then paste that page into the results div.
EDIT NOTE: Found out that if I have the searchNode WITHOUT the dijit Button type the event works but if I apply the dojo-data-type it doesn't.
Widget:
/**
 * Widget for creating a quick search form.
 */
define([
    "dojo/_base/declare",
    "dojo/request",
    "dijit/_WidgetBase",
    "dijit/_OnDijitClickMixin",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dijit/form/Button",
    "dijit/form/TextBox",
    "dojo/text!./templates/quickSearch.html"
],function(declare, request, _WidgetBase, _OnDijitClickMixin, _TemplatedMixin, _WidgetsInTemplateMixin, Button, TextBox, template){
    return declare("js/widget/SASearch", [_WidgetBase, _OnDijitClickMixin, _TemplatedMixin, _WidgetsInTemplateMixin], {
        //  set our template
        templateString: template,

        //  some properties
        baseClass: "searchWidget",

        //  define an onClick handler
        _onClick: function() {
            var query = this.queryNode.value;
            alert(query);
            request("quick/" + query).then(
              function(text) {
                  this.resultsNode.innerHTML = text;
                  alert(text);
              },
              function(error) {}
            );
        }
    });
});

Template:

Search

A: Your event has to be
data-dojo-attach-event="onClick:_onClick"

On the button.
Also for the returns on the request, your going to have to use dojo.hitch to hitch this.
http://jsfiddle.net/theinnkeeper/qum452gm/


Q: Is there any way to automatically generate java classes from Neo4j graph database In my application, we choosen Neo4j as database. We have designed the database with all the required nodes and relationships. We are trying to integrate the in our springboot java program with reactive neo4j repository. Now we are planning to create equivalent entities.
Is there any way to automatically generate java classes from Neo4j graph database which will be equivalent to @Node and @RelationshipProperties used entities as we create manually.

A: No there is no tool for this and this is in general a good thing when it comes to "complex" data in the graph.
Spring Data Neo4j (6) does only fetch the relationships and properties of a node that you define in your model.
If you would map your graph 1:1 you might end up with ones you do not need. They will pollute your code base and create unnecessary long Cypher statements / data transfers.
I would say that there is -in contrast to the usage of RDBMS- a lot of "shared database" usage in the graph world.
The partial match of a domain model in the application to the graph model is no exception here.
Also a tool that blindly converts your data into a model can only make assumptions.
E.g. multiple labels: You can define them in multiple ways depending on your use-case in Spring Data Neo4j.
But which one is the right one for the tool?
This can produce code that is not your desired outcome and you would have to manually refactor it after creation.
Imagine having such a tool in a build chain: You would have to manually fine-tune the resulting model over and over again.


Q: Android onLoadCompleteListener how to implement? I have a custom class called "Sound" with SoundPool, I want to implement the loading complete listener so that my activity can play an intro sound and display the "start" button once loading is complete.
How would I go about implementing the listener and then testing for the complete status from my activity to make sure everything is loaded then go on to do the above.
A small example would be appreciated.
MyActivity creates an instance of my class "Sound" so that it can call various sound methods from it.
Sound mySound = new Sound();

Most of these are not a problem, because by the time they are called, the loading has completed, however, I need for MyActivity to be able to check if loading has completed before calling
mySound.playIntro();

(for example).
Maybe the OnLoadCompleteListener isn't the best solution, I'm still learning, so I'm open to ideas, this is just the way I guessed it should be done.
Thanks

A: It would look somthing like this:
SoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener(){

@override
onLoadComplete(SoundPool soundPool, int sampleId, int status)
{
// show button and play intro sound here
}});

You should read the android guide for developers. And more specificly for this problem: SoundPool
Edit - Corrected a typo, "listner" to "listener"


Q: Compare two arrays in PowerShell I try to compare two arrays, but it won't work.
#System.Data.DataSet -> $Dataset.Tables.Identifier
#System.Xml.XmlElement -> $xmlarray

#$Arraytemp = $xmlarray | Where {$Dataset.Tables.Identifier -NotContains $xmlarray.myid}
$Arraytemp = $xmlarray | Where {$Dataset.Tables.Identifier -NotContains $x_}

Write-Host "Compared Results"
$Arraytemp | ft
Write-Host "XML Results"
$xmlarray | ft
Write-Host "SQL Results"
$Dataset.Tables.Identifier | ft

I read a XML result in an array $xmlarray. It contains the coloumn myid as a unique identifier (and other coloumns).
I read a MS SQL result in an array in $Dataset.Tables.Identifier, it only contains a unique identifier.
The SQL result contains only a part of the XML array. So I want to know, which rows are the difference, because I want to INSERT them in the database.
When I check the result with Write-Host the results looks good. When I compare them, nothing happens.
SQL is System.Data.DataSet.
SQL is System.Xml.XmlElement.
May be the dataformat is not compatible?


Q: less css mixin with parametric A as default for parametric B I'm currently working with LESS CSS and tried to create a mixin that mimics the default css behavior of shorthand parameters.
in css you often declare i.e.
margin: 5px 5px 10px;

and it's read as
margin: 5px 5px 10px 5px;

I tried the same with a border-radius mixin
.border-radius (@topright: 5px, @bottomright: @topright, @bottomleft: @topright, @topleft:  @bottomright) {}

I want it to take the first as default for all, if called with one parameter only. If I call it with 2 parameter it should take the first as default for the third and the second as default for the fourth.
Is there a way to achieve this behavior with LESS alone?

A: The correct way to do this would be to receive just one parameter
.border-radius(@px) {
    -webkit-border-radius: @px;
    -moz-border-radius: @px;
    border-radius: @px;
}

Then you can call it with one parameter:
.border-radius(5px);

or with many. This requires you to either put them in a variable, or escape them:
@myradius: 5px 5px 10px;
.border-radius(@myradius);

or
.border-radius(~"5px 5px 10px");

I read that the Bootstrap project uses the latter version for brevity.


Q: How to directly search string in PDF using any programming language Is it possible to search for a particular string in PDF using any programming language without converting it to a text or doc file. I want to search for a string directly without converting it, I tried to convert it to text and then search for the string but it gave me wrong result.
Thanks!
Kim

A: Docotic.Pdf library can be used for your task. Please see my answer for similar question.
Disclaimer: I work for the company that develops Docotic.Pdf library.

A: 1) Create your own PDF "parser":
http://www.quick-pdf.com/pdf-specification.htm
Probably could be minimal if you just need text data and not any of the formatting.
2) Find a library in your language of choice that can "natively" read .pdfs (tons of them out there).
3) use a pre-built tool (like pdf2text or pdfgrep): https://unix.stackexchange.com/questions/6704/grep-pdf-files

A: If your requirement is to search a for a word and replace it, you can go for Aspose.pdf.Kit

A: Poppler contains tools to extract text from a pdf document. Use it to search on documents.

A: In Java and C#, you can do that with iText, if the pdf file is not locked.
http://itextpdf.com/


Q: Need to collapse a data table by its ID I am fairly new to r, and I am working with a large data set. I made an example of what my problem is below (data set is tab delineated). Basically I want to collapse all data by its ID number so that all of its attributes are contained in 1 cell instead of many cells.
The actual data set I am working with is genomic in nature, with the "ID" being the "gene name" and the "attribute" being the "pathway" that the gene is associated with. My data set is ~5,000,000 rows long.
I have tried messing around with cbind and rbind, but they do not seem to be specific enough for what I need.
My data set currently looks something like this:
ID  Attributes
1   apple
1   banana
1   orange
1   pineapple
2   apple
2   banana
2   orange
3   apple
3   banana
3   pineapple

And I want it to look like this:
ID  Attributes
1   apple,banana,orange,pineapple
2   apple,banana,orange
3   apple,banana,pineapple

If you have another way besides using r, that would work as well.
Thank you for your help

A: a base solution. To split df by ID, then paste the Attributes together. Then rbind the list of results.
do.call(rbind, by(df, df$ID,
    function(x) data.frame(ID=x$ID[1], Attributes=paste(x$Attributes, collapse=","))
))

data:
df <- read.table(text="ID  Attributes
1   apple
1   banana
1   orange
1   pineapple
2   apple
2   banana
2   orange
3   apple
3   banana
3   pineapple", header=TRUE)

A: A tidyverse approach would be to group_by your ID and summarise with paste.
library(dplyr)

df <- read.table(text = "
  ID  Attributes
  1   apple
  1   banana
  1   orange
  1   pineapple
  2   apple
  2   banana
  2   orange
  3   apple
  3   banana
  3   pineapple", header = TRUE, stringsAsFactors = FALSE)

df %>%
  group_by(ID) %>%
  summarise(
    Attributes = paste(Attributes, collapse = ", ")
  )

# # A tibble: 3 x 2
#      ID Attributes
#   <int> <chr>
# 1     1 apple, banana, orange, pineapple
# 2     2 apple, banana, orange
# 3     3 apple, banana, pineapple


Q: Sorting a list in OCaml Here is the code on sorting any given list:
let rec sort lst =
   match lst with
     [] -> []
   | head :: tail -> insert head (sort tail)
 and insert elt lst =
   match lst with
     [] -> [elt]
   | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;

[Source: Code
However, I am getting an Unbound error:
Unbound value tail
# let rec sort lst =
   match lst with
     [] -> []
   | head :: tail -> insert head (sort tail)
 and insert elt lst =
   match lst with
     [] -> [elt]
   | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;
Characters 28-29:
     | head :: tail -> if elt <= head then elt :: lst else head :: insert elt tail;;
     ^
Error: Syntax error

Can anyone please help me understand the issue here?? I did not find head or tail to be predefined anywhere nor in the code

A: Your code seems correct, and compiles for me:
    Objective Caml version 3.11.1

# let rec sort lst = ...

val sort : 'a list -> 'a list = <fun>
val insert : 'a -> 'a list -> 'a list = <fun>

# sort [ 1 ; 3 ; 9 ; 2 ; 5 ; 4; 4; 8 ; 4 ] ;;
- : int list = [1; 2; 3; 4; 4; 4; 5; 8; 9]

A: Adding to what Pascal said, the list type is defined as:
type 'a list = [] | :: of 'a * 'a list

and that's what you are matching your list lst against.

A: The symbol “|“ is the horizontal line symbol, it is not l character and the -> are the minus symbol and the bigger symbol. I think you copied and pasted the segment of code in the website of Inria. Please check and rewrite the special symbols. I tested it and it works well.

A: Head and tail need not to be defined. They are matched from 'list' you give.


Q: How can I open a html file, after a php file is run? I am a complete beginner in web development in regards to php. Right not I am using:
    <form action="phpfile.php">
    <input type="submit" value="click on me!">
    </form>

To open up my php file, which is a simple echo "hello world!" (for testing purposes) The php file that I would use would be this sendmail file
    <?php
    $to = 'example@gmail.com';
    $subject = 'Mailer Test';
    $message = 'This is a test, Thanks Person';
    $headers = "From: your@email-address.com\r\n";
    ?>

How can, after this is run, a html file would open as soon as the file is done loading? Like a "You have completed the task" page essentially (Also I'm using Xampp which has inbuilt sendmail, so the file does work. Once again temporary before I move onto a webserver)
Thanks!!

A: use this :
header('Location: http://localhost/yourHtmlFile.html');
but make sure your php didn't output anything before it
update
another workaround is to use include ('yourHtmlFile.html');

A: PHP can answer code written in HTML back to the browser using echo:
<?php
//do some code
$name="superuser";
echo "Hi ".$name;
?>


Q: How to reference a lambda from inside it? I am trying to get height of a view in onCreate method but I couldn't find any way to remove OnGlobalLayoutListener.
In Java (working):
containerLayout.getViewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        containerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight();

    }
});

In Kotlin (not accepting "this"):
   containerLayout.viewTreeObserver.addOnGlobalLayoutListener {
            containerLayout.viewTreeObserver.removeOnGlobalLayoutListener(this)
            Toast.makeText(applicationContext, "size is "+ containerLayout.height,Toast.LENGTH_LONG).show()
        }

Is there any reference or example for this problem? Thanks.

A: What's about extension like this?
import android.annotation.SuppressLint
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver

inline fun View.doOnGlobalLayout(crossinline action: (view: View) -> Unit) {
    val vto = viewTreeObserver
    vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
        @SuppressLint("ObsoleteSdkInt")
        @Suppress("DEPRECATION")
        override fun onGlobalLayout() {
            action(this@doOnGlobalLayout)
            when {
                vto.isAlive -> {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        vto.removeOnGlobalLayoutListener(this)
                    } else {
                        vto.removeGlobalOnLayoutListener(this)
                    }
                }
                else -> {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        viewTreeObserver.removeOnGlobalLayoutListener(this)
                    } else {
                        viewTreeObserver.removeGlobalOnLayoutListener(this)
                    }
                }
            }
        }
    })
}

Finally, you can call OnGlobalLayoutListener from View directly
val view: View = ...
view.doOnGlobalLayout {
  val width = view?.measuredWidth
  val height = view?.measuredHeight
}

A: Simple / clear approach (no generics or anonymous objects):
You could create the listener in advance, then add / use / remove as needed:
private var layoutChangedListener: ViewTreeObserver.OnGlobalLayoutListener? = null

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    // create the listener
    layoutChangedListener = ViewTreeObserver.OnGlobalLayoutListener {

        // do something here

        // remove the listener from your view
        myContainerView.viewTreeObserver.removeOnGlobalLayoutListener(layoutChangedListener)
        layoutChangedListener = null
    }

    // add the listener to your view
    myContainerView.viewTreeObserver.addOnGlobalLayoutListener(layoutChangedListener)
}

use case:
I had to be able to remove the listener, in order to adjust the layout inside the listener itself - not removing the listener may result in a deadlock

A: Referencing a lambda from inside it is not supported.
As a workaround, you might use anonymous object instead of lambda SAM-converted to Java functional interface OnGlobalLayoutListener:
containerLayout.viewTreeObserver.addOnGlobalLayoutListener(object: OnGlobalLayoutListener {
    override fun onGlobalLayout() {
        // your code here. `this` should work
    }
})

A: Another solution is to implement and use self-reference:
class SelfReference<T>(val initializer: SelfReference<T>.() -> T) {
    val self: T by lazy {
        inner ?: throw IllegalStateException()
    }

    private val inner = initializer()
}

fun <T> selfReference(initializer: SelfReference<T>.() -> T): T {
    return SelfReference(initializer).self
}

Then the usage would be
containerLayout.viewTreeObserver.addOnGlobalLayoutListener(selfReference {
    OnGlobalLayoutListener {
        containerLayout.viewTreeObserver.removeOnGlobalLayoutListener(self)
        // ...
    }
}

Instead of this, self property is used.


Q: Argument to KnockoutJS function is returning the viewModel when not defined Still continuing to understand KO here. I have an argument to one of the KO methods,it works when I pass it an explicit value but when I call the function with no args it does not give
<button data-bind="click:LaterCall">click</button>

function InvoiceViewModel() {

    //Data
    var self = this;
    self.LaterCall = function (arg) {
        console.log(arg); // why is this not undefined????
    };

}
var viewModel = new InvoiceViewModel();
ko.applyBindings(viewModel);

http://jsfiddle.net/sajjansarkar/9TMv2/2/

A: Knockout's click binding (and event binding, which click is a subset of) pass the current data as the first argument and the event as the second argument to any handlers.
So, arg would be equal to your viewModel in your case.

A: The parameter arg will reference the parent and as you can see in your example the actual viewmodel is the parent. Putting an argument there is mainly used when you have nested controllers and want to reference the parent dynamically as stated in the second example here, http://knockoutjs.com/documentation/click-binding.html

        <button data-bind="click: $parent.removePlace">Remove</button>

I would also recommend you not to use self as a parameter name in javascript, instead go for that
var that = this;


Q: get all rows from orignal Dataframe which is having number or alpha number in particular column? I have Dataframe Like this in df_init
          column1
       0  hi all, i am fine
       1  How are you ? 123 a45
       2  123444234324!!!  (This is also string)
       3  sdsfds sdfsdf 233423
       5  adsfd xcvbb cbcvbcvcbc

I want to get all those values from this dataframe which is having a number or alpha number
I am expecting like this in df_final
          column1
       0  How are you ? 123 a45
       1  123444234324!!!  (This is also string)
       2  sdsfds sdfsdf 233423

A: Use str.contains with \d for match number and filter by boolean indexing:
df = df[df.column1.str.contains('\d')]
print (df)
                                  column1
1                   How are you ? 123 a45
2  123444234324!!!  (This is also string)
3                    sdsfds sdfsdf 233423

EDIT:
print (df)
                  column1
0   hi all, i am fine d78
1   How are you ? 123 a45
2         123444234324!!!
3    sdsfds sdfsdf 233423
4  adsfd xcvbb cbcvbcvcbc
5                 234324@
6                 123! vc

df = df[df.column1.str.contains(r'^\d+[<!\-[.*?\]>@]+$')]
print (df)
           column1
2  123444234324!!!
5          234324@


Q: Short echo repurposed in newer versions of PHP? I have heard from several people that <?= has been re-purposed / replaced in newer versions of PHP, but am unable to find supporting documentation to this change, or to what version(s) it effects. Has short echo been replaced or re-purposed and is there supporting documentation to it?

A: The current documentation does not reflect any change of behaviour of shorthand echo (<?=) since version 5.4.0, in which only the necessary configuration to enable it was changed.

*

*http://php.net/manual/en/function.echo.php


Q: Pandas: Adding column with calculations from other columns I have a csv with measurements:
YY-MO-DD HH-MI-SS_SSS    |        x          |          y
2015-12-07 20:51:06:608  |        2          |          4
2015-12-07 20:51:07:609  |        3          |          4

and I want to add another column with the square root of the sum of x^2+y^2,
z=sqrt(x^2+y^2)
like this:
 YY-MO-DD HH-MI-SS_SSS       |        x          |          y     |     z
    2015-12-07 20:51:06:608  |        2          |          4     |   4.472
    2015-12-07 20:51:07:609  |        3          |          4     |    5

Any ideas?
Thank you !

A: Use np.sqrt on the result of the squares:
In [10]:
df['z'] = np.sqrt(df['x']**2 + df['y']**2)
df

Out[10]:
   x  y         z
0  2  4  4.472136
1  3  4  5.000000

You can also sum row-wise the result of np.square and call np.sqrt:
In [13]:
df['z'] = np.sqrt(np.square(df[['x','y']]).sum(axis=1))
df

Out[13]:
   x  y         z
0  2  4  4.472136
1  3  4  5.000000