text:
Q: Hide quantity fields in cart for specific products in Woocommerce 3 I Would like to hide the quantity field from one specific product category in cart page.
The "Sold Individually" doesn't help me because I have a plugin that must be disabled to work.
Is it possible? Any track will be appreciated.

A: The following code will hide the product quantity field on cart page:
1) for a specific product category (that you will define in this code):
add_filter( 'woocommerce_quantity_input_args', 'hide_quantity_input_field', 20, 2 );
function hide_quantity_input_field( $args, $product ) {
    // Here set your product categories in the array (can be either an ID, a slug, a name or an array)
    $categories = array('t-shirts','shoes');

    // Handling product variation
    $the_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // Only on cart page for a specific product category
    if( is_cart() && has_term( $categories, 'product_cat', $the_id ) ){
        $input_value = $args['input_value'];
        $args['min_value'] = $args['max_value'] = $input_value;
    }
    return $args;
}

Code goes in function.php file of the active child theme (or active theme). Tested and works.
It will also handle product variations added to cart.
2) for specific product IDs (that you will define in this code):
add_filter( 'woocommerce_quantity_input_args', 'hide_quantity_input_field', 20, 2 );
function hide_quantity_input_field( $args, $product ) {
    // Here set your product IDs in the array
    $product_ids = array(37,40,70);

    // Handling product variation
    $the_id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id();

    // Only on cart page for a specific product category
    if( is_cart() && in_array( $the_id, $product_ids ) ){
        $input_value = $args['input_value'];
        $args['min_value'] = $args['max_value'] = $input_value;
    }
    return $args;
}

Code goes in function.php file of the active child theme (or active theme). Tested and works.
It will also handle product variations added to cart.


text:
Q: ASP.NET Core 2.1 - Run attribute's code without reflection I've defined the following attribute:
class MyAttribute: RouteAttribute, IActionModelConvention, IActionHttpMethodProvider
{
    public IEnumerable<string> HttpMethods { get; }

    public MyAttribute(string template) : base(UpdateTemplate(template))
    {
        HttpMethods = new[] { HttpMethod.Post.Method };
    }

    public void Apply(ActionModel action)
    {
        Foo();
    }
}

The idea is to run Foo() without the need to use reflection and manually look for methods with the provided attribute.
Now, MVC will run Apply(action) only after the web application got its first request. I'm looking for a solution which will cause a method to run inside the attribute context without the need to find it by reflection and run a Foo().
Foo() does not have to be necessarily inside the attribute.

Any solution that allows me to have the instance of the attribute and on the startup of my application will be greeted.

Edit: For clarification, what I am trying to achieve is to use MVC's internal mechanism that searches for classes which implement certain interfaces and runs a certain function they implement. For an example here I used IActionModelConvention to run Foo() when using said mechanism. The problem here is that Foo() will run only after the routing mechanism is fired which only happens after a request was sent to the application. I'm looking for something to run my code as the application starts and to have my attribute's instance so I can pass Foo(this.someAttributeField) to it

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to receive UDP packets continuously I want to receive UDP packets continuously from the port. I'm using recvfrom() to receive packets. How to put delay after receiving a single packet. I want to receive more than 50 packets. For that I need help. Thanks in advance....

A: The network stack captures all packets addressed to the socketaddress on the line for you and puts it in a queue. Just use recvfrom to read the queued data. If you want you application to wait for the next receive event you can use the select function.


text:
Q: Component (similar to trackbar) to enter a range of values I need a component for entering ranges. I was thinking along the lines of a trackbar with two markers. Are there "native Delphi" components that are meant for this purpose or that can simulate it easily?

A: I got a few minutes over and wrote this:
unit RangeSelector;

interface

uses
  SysUtils, Windows, Messages, Graphics, Classes, Controls, UxTheme, Dialogs;

type
  TRangeSelectorState = (rssNormal, rssDisabled, rssThumb1Hover, rssThumb1Down, rssThumb2Hover, rssThumb2Down, rssBlockHover, rssBlockDown);

  TRangeSelector = class(TCustomControl)
  private
    { Private declarations }
    FBuffer: TBitmap;
    FMin,
    FMax,
    FSelStart,
    FSelEnd: real;
    FTrackPos,
    FSelPos,
    FThumbPos1,
    FThumbPos2: TRect;
    FState: TRangeSelectorState;
    FDown: boolean;
    FPrevX,
    FPrevY: integer;
    FOnChange: TNotifyEvent;
    FDblClicked: Boolean;
    FThumbSize: TSize;
    procedure SwapBuffers;
    procedure SetMin(Min: real);
    procedure SetMax(Max: real);
    procedure SetSelStart(SelStart: real);
    procedure SetSelEnd(SelEnd: real);
    function GetSelLength: real;
    procedure UpdateMetrics;
    procedure SetState(State: TRangeSelectorState);
    function DeduceState(const X, Y: integer; const Down: boolean): TRangeSelectorState;
    function BarWidth: integer; inline;
    function LogicalToScreen(const LogicalPos: real): real;
    procedure UpdateThumbMetrics;
  protected
    { Protected declarations }
    procedure Paint; override;
    procedure WndProc(var Message: TMessage); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override;
    procedure MouseLeave(Sender: TObject);
    procedure DblClick; override;
  public
    { Public declarations }
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    { Published declarations }
    property Anchors;
    property Min: real read FMin write SetMin;
    property Max: real read FMax write SetMax;
    property SelStart: real read FSelStart write SetSelStart;
    property SelEnd: real read FSelEnd write SetSelEnd;
    property SelLength: real read GetSelLength;
    property Enabled;
    property Visible;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  end;

procedure Register;

implementation

uses Math;

procedure Register;
begin
  RegisterComponents('Rejbrand 2009', [TRangeSelector]);
end;

function IsIntInInterval(x, xmin, xmax: integer): boolean; inline;
begin
  IsIntInInterval := (xmin <= x) and (x <= xmax);
end;

function PointInRect(const X, Y: integer; const Rect: TRect): boolean; inline;
begin
  PointInRect := IsIntInInterval(X, Rect.Left, Rect.Right) and
                 IsIntInInterval(Y, Rect.Top, Rect.Bottom);
end;

function IsRealInInterval(x, xmin, xmax: extended): boolean; inline;
begin
  IsRealInInterval := (xmin <= x) and (x <= xmax);
end;

{ TRangeSelector }

function TRangeSelector.BarWidth: integer;
begin
  result := Width - 2*FThumbSize.cx;
end;

constructor TRangeSelector.Create(AOwner: TComponent);
begin
  inherited;
  FBuffer := TBitmap.Create;
  FMin := 0;
  FMax := 100;
  FSelStart := 20;
  FSelEnd := 80;
  FDown := false;
  FPrevX := -1;
  FPrevY := -1;
  FDblClicked := false;
end;

procedure TRangeSelector.UpdateThumbMetrics;
var
  theme: HTHEME;
const
  DEFAULT_THUMB_SIZE: TSize = (cx: 12; cy: 20);
begin
  FThumbSize := DEFAULT_THUMB_SIZE;
  if UxTheme.UseThemes then
  begin
    theme := OpenThemeData(Handle, 'TRACKBAR');
    if theme <> 0 then
      try
        GetThemePartSize(theme, FBuffer.Handle, TKP_THUMBTOP, TUTS_NORMAL, nil, TS_DRAW, FThumbSize);
      finally
        CloseThemeData(theme);
      end;
  end;
end;

destructor TRangeSelector.Destroy;
begin
  FBuffer.Free;
  inherited;
end;

function TRangeSelector.GetSelLength: real;
begin
  result := FSelEnd - FSelStart;
end;

function TRangeSelector.LogicalToScreen(const LogicalPos: real): real;
begin
  result := FThumbSize.cx + BarWidth * (LogicalPos - FMin) / (FMax - FMin)
end;

procedure TRangeSelector.DblClick;
var
  str: string;
begin
  FDblClicked := true;
  case FState of
    rssThumb1Hover, rssThumb1Down:
      begin
        str := FloatToStr(FSelStart);
        if InputQuery('Initial value', 'Enter new initial value:', str) then
          SetSelStart(StrToFloat(str));
      end;
    rssThumb2Hover, rssThumb2Down:
      begin
        str := FloatToStr(FSelEnd);
        if InputQuery('Final value', 'Enter new final value:', str) then
          SetSelEnd(StrToFloat(str));
      end;
  end;
end;

function TRangeSelector.DeduceState(const X, Y: integer; const Down: boolean): TRangeSelectorState;
begin
  result := rssNormal;

  if not Enabled then
    Exit(rssDisabled);

  if PointInRect(X, Y, FThumbPos1) then
    if Down then
      result := rssThumb1Down
    else
      result := rssThumb1Hover

  else if PointInRect(X, Y, FThumbPos2) then
    if Down then
      result := rssThumb2Down
    else
      result := rssThumb2Hover

  else if PointInRect(X, Y, FSelPos) then
    if Down then
      result := rssBlockDown
    else
      result := rssBlockHover;

end;

procedure TRangeSelector.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;
  if FDblClicked then
  begin
    FDblClicked := false;
    Exit;
  end;
  FDown := Button = mbLeft;
  SetState(DeduceState(X, Y, FDown));
end;

procedure TRangeSelector.MouseLeave(Sender: TObject);
begin
  if Enabled then
    SetState(rssNormal)
  else
    SetState(rssDisabled);
end;

procedure TRangeSelector.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if FState = rssThumb1Down then
    SetSelStart(FSelStart + (X - FPrevX) * (FMax - FMin) / BarWidth)
  else if FState = rssThumb2Down then
    SetSelEnd(FSelEnd + (X - FPrevX) * (FMax - FMin) / BarWidth)
  else if FState = rssBlockDown then
  begin
    if IsRealInInterval(FSelStart + (X - FPrevX) * (FMax - FMin) / BarWidth, FMin, FMax) and
       IsRealInInterval(FSelEnd + (X - FPrevX) * (FMax - FMin) / BarWidth, FMin, FMax) then
    begin
      SetSelStart(FSelStart + (X - FPrevX) * (FMax - FMin) / BarWidth);
      SetSelEnd(FSelEnd + (X - FPrevX) * (FMax - FMin) / BarWidth);
    end;
  end
  else
    SetState(DeduceState(X, Y, FDown));

  FPrevX := X;
  FPrevY := Y;
end;

procedure TRangeSelector.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
begin
  inherited;
  FDown := false;
  SetState(DeduceState(X, Y, FDown));
end;

procedure TRangeSelector.Paint;
var
  theme: HTHEME;
begin
  inherited;

  FBuffer.Canvas.Brush.Color := Color;
  FBuffer.Canvas.FillRect(ClientRect);

  if UxTheme.UseThemes then
  begin

    theme := OpenThemeData(Handle, 'TRACKBAR');
    if theme <> 0 then
      try

        DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_TRACK, TRS_NORMAL, FTrackPos, nil);

        case FState of
          rssDisabled:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMB, TUS_DISABLED, FSelPos, nil);
          rssBlockHover:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMB, TUS_HOT, FSelPos, nil);
          rssBlockDown:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMB, TUS_PRESSED, FSelPos, nil);
        else
          DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMB, TUS_NORMAL, FSelPos, nil);
        end;

        case FState of
          rssDisabled:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBBOTTOM, TUBS_DISABLED, FThumbPos1, nil);
          rssThumb1Hover:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBBOTTOM, TUBS_HOT, FThumbPos1, nil);
          rssThumb1Down:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBBOTTOM, TUBS_PRESSED, FThumbPos1, nil);
        else
          DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBBOTTOM, TUBS_NORMAL, FThumbPos1, nil);
        end;

        case FState of
          rssDisabled:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBTOP, TUTS_DISABLED, FThumbPos2, nil);
          rssThumb2Hover:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBTOP, TUTS_HOT, FThumbPos2, nil);
          rssThumb2Down:
            DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBTOP, TUTS_PRESSED, FThumbPos2, nil);
        else
          DrawThemeBackground(theme, FBuffer.Canvas.Handle, TKP_THUMBTOP, TUTS_NORMAL, FThumbPos2, nil);
        end;

      finally
        CloseThemeData(theme);
      end;

  end

  else

  begin

    DrawEdge(FBuffer.Canvas.Handle, FTrackPos, EDGE_SUNKEN, BF_RECT);

    FBuffer.Canvas.Brush.Color := clHighlight;
    FBuffer.Canvas.FillRect(FSelPos);

    case FState of
      rssDisabled:
        DrawEdge(FBuffer.Canvas.Handle, FSelPos, EDGE_BUMP, BF_RECT or BF_MONO);
      rssBlockHover:
        DrawEdge(FBuffer.Canvas.Handle, FSelPos, EDGE_RAISED, BF_RECT);
      rssBlockDown:
        DrawEdge(FBuffer.Canvas.Handle, FSelPos, EDGE_SUNKEN, BF_RECT);
    else
      DrawEdge(FBuffer.Canvas.Handle, FSelPos, EDGE_ETCHED, BF_RECT);
    end;

    case FState of
      rssDisabled:
        DrawEdge(FBuffer.Canvas.Handle, FThumbPos1, EDGE_BUMP, BF_RECT or BF_MONO);
      rssThumb1Hover:
        DrawEdge(FBuffer.Canvas.Handle, FThumbPos1, EDGE_RAISED, BF_RECT);
      rssThumb1Down:
        DrawEdge(FBuffer.Canvas.Handle, FThumbPos1, EDGE_SUNKEN, BF_RECT);
    else
      DrawEdge(FBuffer.Canvas.Handle, FThumbPos1, EDGE_ETCHED, BF_RECT);
    end;

    case FState of
      rssDisabled:
        DrawEdge(FBuffer.Canvas.Handle, FThumbPos2, EDGE_BUMP, BF_RECT or BF_MONO);
      rssThumb2Hover:
        DrawEdge(FBuffer.Canvas.Handle, FThumbPos2, EDGE_RAISED, BF_RECT);
      rssThumb2Down:
        DrawEdge(FBuffer.Canvas.Handle, FThumbPos2, EDGE_SUNKEN, BF_RECT);
    else
      DrawEdge(FBuffer.Canvas.Handle, FThumbPos2, EDGE_ETCHED, BF_RECT);
    end;

  end;

  SwapBuffers;
end;

procedure TRangeSelector.UpdateMetrics;
begin
  UpdateThumbMetrics;
  FBuffer.SetSize(Width, Height);
  FTrackPos := Rect(FThumbSize.cx, FThumbSize.cy + 2, Width - FThumbSize.cx, Height - FThumbSize.cy - 2);
  FSelPos := Rect(round(LogicalToScreen(FSelStart)),
                  FTrackPos.Top,
                  round(LogicalToScreen(FSelEnd)),
                  FTrackPos.Bottom);
  with FThumbPos1 do
  begin
    Top := 0;
    Left := round(LogicalToScreen(FSelStart) - FThumbSize.cx / 2);
    Right := Left + FThumbSize.cx;
    Bottom := Top + FThumbSize.cy;
  end;
  with FThumbPos2 do
  begin
    Top := Self.Height - FThumbSize.cy;
    Left := round(LogicalToScreen(FSelEnd) - FThumbSize.cx / 2);
    Right := Left + FThumbSize.cx;
    Bottom := Top + FThumbSize.cy;
  end;
end;

procedure TRangeSelector.WndProc(var Message: TMessage);
begin
  inherited;
  case Message.Msg of
    WM_SIZE:
      UpdateMetrics;
  end;
end;

procedure TRangeSelector.SetMax(Max: real);
begin
  if FMax <> Max then
  begin
    FMax := Max;
    UpdateMetrics;
    Paint;
  end;
end;

procedure TRangeSelector.SetMin(Min: real);
begin
  if FMin <> Min then
  begin
    FMin := Min;
    UpdateMetrics;
    Paint;
  end;
end;

procedure TRangeSelector.SetSelEnd(SelEnd: real);
begin
  if (FSelEnd <> SelEnd) and IsRealInInterval(SelEnd, FMin, FMax) then
  begin
    FSelEnd := SelEnd;
    if FSelStart > FSelEnd then
      FSelStart := FSelEnd;
    UpdateMetrics;
    Paint;
    if Assigned(FOnChange) then
      FOnChange(Self);
  end;
end;

procedure TRangeSelector.SetSelStart(SelStart: real);
begin
  if (FSelStart <> SelStart) and IsRealInInterval(SelStart, FMin, FMax) then
  begin
    FSelStart := SelStart;
    if FSelStart > FSelEnd then
      FSelEnd := FSelStart;
    UpdateMetrics;
    Paint;
    if Assigned(FOnChange) then
      FOnChange(Self);
  end;
end;

procedure TRangeSelector.SetState(State: TRangeSelectorState);
begin
  if State <> FState then
  begin
    FState := State;
    Paint;
  end;
end;

procedure TRangeSelector.SwapBuffers;
begin
  BitBlt(Canvas.Handle,
         0,
         0,
         Width,
         Height,
         FBuffer.Canvas.Handle,
         0,
         0,
         SRCCOPY);
end;

end.

There are still a few things to improve, such as 1) add keyboard interface, 2) make the display of the markers optional and add more appearance settings, 4) snap to integer grid, and 3) add the ability to enter a value by numbers Try double-clicking a thumb!.
The control works both with and without visual themes enabled and is completely double-buffered.

A: In addition to Andreas' nice answer and component, hereby another slider component that is capable of:

*

*displaying a range,

*displaying a filtered range within that range,

*dragging the grips and the green bar,

*double clicking a grip for keyboard entry,

*tabbing through the grips for keyboard entry,

*displaying different data types,

*restricting values to a step size.

(Source: NLDelphi.com)

A: I don't know of anything like this, although there probably is such a thing.  I'd be concerned about the usability issues of moving one of the markers on top of the other.  When I ask for ranges in my app I just ask the user to type the numbers in.

A: TTrackBar has SelStart, SelEnd and ShowSelRange. However they don't seem to have much use - they are nearly invisible if themed and AFAICT the user can't move the Sel* markers.

A: I suggest a pair of spin edits. The user can click up/down if they want to but most people will just want to enter their values:


text:
Q: Trigger Xamarin.Forms Picker Can i Trigger a Picker programatically?
I would like a button beside the picker that indicates that the picker is a clickable "dropdown". But how could I open the picker when the button is clicked?

A: You can name the picker (e.g. myPicker) and call its Focus event. Do make sure that you're on the main thread at the time you're calling myPicker.Focus()

A: As @Hutjepower and this xamarin forums post mentions, the following code should work:
Device.BeginInvokeOnMainThread(() =>
{
    if (yourPicker.IsFocused)
        yourPicker.Unfocus();

    yourPicker.Focus();
});

However I have found that it does not currently work on Windows 8.1 and UWP apps, at least in the latest 2.3.4-pre1 version of Xamarin.Forms. I haven't tested it on any phone/tablet devices yet though. Hopefully this bug will get fixed up in a later release. I have created a bug report for this problem.

A: Unfortunately not; the inner workings of the picker are almost entirely in the renderers and are not exposed via an API.


text:
Q: Pandas memoization I have lengthy computations which I repeat many times. Therefore, I would like to use memoization (packages such as jug and joblib), in concert with Pandas. The problem is whether the package would memoize well Pandas DataFrames as method arguments.
Has anyone tried it? Is there any other recommended package/way to do this?

A: Author of jug here: jug works fine. I just tried the following and it works:
from jug import TaskGenerator
import pandas as pd
import numpy as np

@TaskGenerator
def gendata():
    return pd.DataFrame(np.arange(343440).reshape((10,-1)))

@TaskGenerator
def compute(x):
    return x.mean()

y = compute(gendata())

It is not as efficient as it could be as it just uses pickle internally for the DataFrame (although it compresses it on the fly, so it is not horrible in terms of memory use; just slower than it could be).
I would be open to a change which saves these as a special case as jug currently does for numpy arrays: https://github.com/luispedro/jug/blob/master/jug/backends/file_store.py#L102

A: I use this basic memoization decorator, memoized. http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
DataFrames are hashable, so it should work fine. Here's an example.
In [2]: func = lambda df: df.apply(np.fft.fft)

In [3]: memoized_func = memoized(func)

In [4]: df = DataFrame(np.random.randn(1000, 1000))

In [5]: %timeit func(df)
10 loops, best of 3: 124 ms per loop

In [9]: %timeit memoized_func(df)
1000000 loops, best of 3: 1.46 us per loop

Looks good to me.


text:
Q: Create new list in nested list C# Anyone know how to add new list into another list, the new list cannot be predefined.
For example, after get user input, I will do the following
List<List<string>> ListA = new List<List<string>>();

foreach (List<string> subList in ListA)
{
     foreach (var value in subList)
     {
          if(value != INPUT)
          {
                // ListA needs to creates a new list with value INPUT
          }
     }
}

A: Since you cannot modify collection that you're currently enumerating use eg. ToArray():
foreach (List<string> subList in ListA.ToArray())
{
    foreach (var value in subList)
    {
           if(value != INPUT)
           (
              ListA.Add(new List<string>() { INPUT });
           }
    }
}

A: You could use linq to do this:
include the namespace:
using System.Linq;

And try this:
var result = ListA.Select(x => x.Where(k => k != INPUT).ToList()).ToList();

A: List<List<string>> ListA = new List<List<string>>();
List<List<string>> ListsToAdd = new List<List<string>>();

foreach (List<string> subList in ListA)
{
    foreach (var value in subList)
    {
           if(value != INPUT)
           (
              List<string> list = new List<string>();
              list.Add(INPUT);
              ListsToAdd.Add(list);
           }
    }
}
ListA.AddRange(ListsToAdd);


text:
Q: Print leaves queue but does not physically print I am printing from Windows Server 2003 (32-bit) through a TCP/IP printer which is hosted on Windows 8.1 (64-bit). The remote network is connected to use with VPN.
The problem is that the print leaves the 2003 printer and arrives at the Windows 8.1 print queue. It then leaves the print queue as though it has printed successfully but no physical print arrives on the printer.
The printer is a HP Laserjet P2055dn. This setup worked previously before my customer replaced their Windows 7 PC with a new Windows 8.1 PC. I tried the original HP universal print drivers and when they did not work I have since downloaded the latest printer drivers which say that they support windows 8.1 but I still have the same problem.
Can anyone think of anything else to try? or do you think it could be a problem with printing from the 32-bit OS to the 64-bit OS. Where the drivers used on 32-bit OS are not being read properly on the print device.
I do not have the ability to add additional drivers in the printer properties page as it is greyed out.


text:
Q: Where is my tablet's memory card mounted on laptop? I connected my Asus fonepad7 tablet to my laptop via usb. My laptop automatically detects it & opens. But I'm unable to find where the memory card of my tablet mounted on laptop. Just see below, when I put cursor on the tablet device, it shows "mtp://[usb:002,003]/"

As I'm unable to find the mount point, I can't use command line for accessing the tablet. Also, commands "mount" & "df" doesn't reflect anything regarding the tablet.
I'm working on Ubuntu 13.04

EDIT#1

This edit is with ref. to the answer posted by edvinas.me
I got the mount point as "/run/user/ravbholua/gvfs".
But the issue is that all the files & folders are named as numerals. Please see below:
ravbholua@ravbholua-Aspire-5315:/run/user/ravbholua/gvfs/mtp:host=%5Busb%3A002%2C008%5D$ ls
65537
ravbholua@ravbholua-Aspire-5315:/run/user/ravbholua/gvfs/mtp:host=%5Busb%3A002%2C008%5D$ cd *
ravbholua@ravbholua-Aspire-5315:/run/user/ravbholua/gvfs/mtp:host=%5Busb%3A002%2C008%5D/65537$ ls
1   100  105   11  1301  1420  1533  1597  2    223  226  3   4    422  426  5  85  9
10  104  1072  12  1310  1496  1547  1806  212  224  232  30  421  424  430  6  86  900
ravbholua@ravbholua-Aspire-5315:/run/user/ravbholua/gvfs/mtp:host=%5Busb%3A002%2C008%5D/65537$ cp 30 ~
cp: cannot open '30' for reading: Operation not supported

The name of the files & folders as shown in GUI is by names but here it is numerals.
Also I'm unable to copy any file. Please look at the above code.

A: Your tablet is mounted via gvfs instead of usual tools. You should check ~/.gvfs or /run/user/<login>/gvfs directories.


text:
Q: Run HttpClient GetAsync in different threads I have a scenario where I have x amount of queries and I want to run each query in a different thread.
My problem is the Http GetAsync method only works when it returns a Task, I tried to return a void but it did not work. But to create multiple threads I need to return a void.
public static async Task threadAsync(string query)
{
    var watch = System.Diagnostics.Stopwatch.StartNew();
    try
    {
        watch.Restart();

        HttpResponseMessage response = await client.GetAsync(query);
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        watch.Stop();

        string logData += $"Execution Time: {watch.ElapsedMilliseconds} ms, ";

        watch.Reset();
        var data = JObject.Parse(responseBody);
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ", e.Message);
    }
}

I have multiple methods in Threads class with different queries. I tried using GetAwaiter().GetResult(), but that also did not work. How can I use run each query in a different thread?
public class Threads
{
    public static void thread1Create()
    {
        string query = "SOMEQUERY";
        threadAsync(query).GetAwaiter().GetResult()
    }
};

A:
want to run each query in a different thread.

Why?
You really need to learn how windows works internally and what completion ports are. Async methods run on NO thread - they just get called into a thread back when they are done. This is based on the windows network model actually - NOT HAVING THREADS WHILE IT WORKS.

My problem is the Http GetAsync method only works when it returns a Task, I
tried to return a void

Given that GET Returns something in the task, that would be utterly useless.
Your problem is this:

HttpResponseMessage response = await client.GetAsync(query);

There is no requirement to AWAIT immediately. Start all the async get operations, then start awaiting them.
Really learn basics - you USE async, but you THINK in threads still and thus you do not understand what the async model really gives you. The result is a cargo cult like programming totally nullifying the advantages of async, and now asking how to then regain them via threads.


text:
Q: Are the strata of Nakajima quiver varieties simply-connected?  Do they have odd cohomology? Nakajima defined a while back a nice family of varieties, called "quiver varieties" (sometimes with "Nakajima" appended to the front to avoid confusion with other varieties defined in terms of quivers).  These are most concisely defined as the moduli of certain representations of certain preprojective algebras.
I'll be interested in the affine (in the sense of "affine variety" not "affine Lie algebra") version of these, which is the moduli space of semi-simple representations of a certain preprojective algebra.  This variety is singular, but can be divided into smooth strata which correspond to fixing the size of the automorphism group of the representation (i.e. one stratum for simple representations, one for sums of pairs of non-isomorphic simples, etc.).  I would like to know a bit about the geometry of these strata.  One basic (and important for me) question is

Are these strata simply connected or equivariantly simply connected for the action of a group?

Actually, I know that they are not simply connected from some very simple examples (such as the nilcone of $\mathfrak{sl}_2$), but in those examples there is an action of a group such that there are no equivariant local systems (if you're willing to think of the quotient as a stack, the quotient is simply connected), so they are "equivariantly simply connected."
Similarly, I'm interested in the cohomology of these strata; I'd like its odd part to vanish.  Again, there's no hope of this in the most obvious way.  The only way it could happen is equivariantly.

Does the odd (equivariant) cohomology of these strata vanish for any group action?

let me just note in closing: I would be entirely satisfied if these results were only true in the finite type case; I know a lot of geometric statements for quiver varieties go a little sour once you're outside the finite type case.
If anyone knows these or any other results in the literature about the geometry of these strata, I would be very happy to hear them.

A: As Ben wrote, there are examples of non-simply connected strata.
For a quiver variety corresponding to a fundamental representation, it, a priori, only has a small group action. So it is usually far away from homogeneous.
So I suspect the answer is NO, though I do not know a concrete example.
But, I think the question itself is not right:
It is true that perverse sheaves appearing in the push-forward from `natural resolutions' are IC sheaves associated with constant sheaves. But it is not because stratum are simply-connected, or equivariantly simply connected. It is from a very different reason:
This reason cannot be seen if one treat an individual quiver variety separately. One can see it only when one consider various quiver varieties simultaneously, and relate them to a representation. It is basically because there is a component consisting of a single point, and other components are `connected' to it in some sense.
(Each component corresponds only to a weight space, and considering several components simultaneously, one get the structure of a representation. The single point corresponds to the highest weight vector.)
In summary, quiver varieties are not homogeneous in a conventional sense, but have substitutive property (I do not know how to call it) when one treat several components simultaneously.

A: Not really an answer, but I had a similar problem a while ago (I wanted to know the cohomology ring of certain non-free quotients). My supervisor told me to look at Bredon homology, but I found something different to work on. Might be worth a try!


text:
Q: custom username validation in wcf I have a wcf service and client,and would like to provide additional protection with checking of username and password. I have following validatir class
public class UserCredentialsValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (!string.Equals(userName, Config.Login, StringComparison.InvariantCultureIgnoreCase)
                && !String.Equals(password, Config.Password))
            {
                throw new FaultException("Invalid user credentials. Access denied.");
            }
        }
    }

and following server configuration
<behaviors>
      <serviceBehaviors>
        <behavior name="serviceBehavior">
          <serviceDebug includeExceptionDetailInFaults="true"/>   <serviceCredentials>
                    <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="FileStorage.Core.ServiceModel.UserCredentialsValidator, FileStorage.Core"/>
                </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="FileStorage.Core.ServiceModel.FileStorageService" behaviorConfiguration="serviceBehavior">
        <endpoint address="" contract="FileStorage.IFileStorage" binding="wsHttpBinding" bindingConfiguration="bindingConfig"/>
      </service>
    </services>
    <bindings>
      <wsHttpBinding>
        <binding name="bindingConfig" maxBufferPoolSize="104857600" maxReceivedMessageSize="104857600" openTimeout="00:10:00"
                 closeTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00">
          <readerQuotas maxDepth="32" maxStringContentLength="104857600" maxArrayLength="104857600"
                        maxBytesPerRead="104857600" maxNameTableCharCount="1024"/> <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>

Problem is that CustomValidatir never execute Validate method, e.g. validation logic doesn't execute
What can cause this? Thanks in advance

A: Try changing your 'security' section to read this...
<security mode="TransportWithMessageCredential">
    <transport clientCredentialType="Basic" proxyCredentialType="Basic" />
    <message clientCredentialType="UserName"/>
</security>

A: The security mode="TransportWithMessageCredential" is ok. Not sure why we need transport clientCredentialType="Basic" proxyCredentialType="Basic"...
I am using transport clientCredentialType="Certificate" protectionLevel="EncryptAndSign" in my windows service hosted WCF..working fine..It seems the trick actually lies in choosing the correct security mode.


text:
Q: SQL if column is empty, add an empty column I want to be able to check if we have a column and if not, then we just want to add an empty column,
    IF Users.[parties] = '' OR NULL
        BEGIN
            SELECT [parties]
            FROM Users
            UNION
            SELECT 'Empty'
        END

The Users.[parties], we check to see if we have a column but if we don't, it will result in a crash, in the case for this event I thought it would be best just to add an empty column with the name of Empty but I can't get the code to work above.
If we do have columns, the results will be something like...
ColumnsName    ColumnAge
data             33
data             22

But when there isn't a column, it crashes and ideally I would like it to just have an empty column like this,
EmptyColumn

A: The code below checks whether a column exists in the table, in our case the name of the column is columnName and the name of the table is tableName.
IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
    BEGIN
        -- Column exists
       SELECT [parties] FROM Users
    END
ELSE
    BEGIN
        -- Column does not exists
        SELECT 'Empty'[parties]
    END

A: I think you just want
IF EXISTS(
           SELECT 1
           FROM Sys.Columns
           WHERE Name = N'parties'
                 AND
                 Object_ID = Object_ID(N'SchemaName.Users')
         )
BEGIN
  SELECT parties
  FROM Users;
END
ELSE
BEGIN
  SELECT 'EmptyColumn' EmptyColumn -- or NULL EmptyColumn
  FROM Users;
END

A: I'll try with this: (I'm not sure it works)
select case when ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) =0 --count rows
          then 'empty'  -- if 0 output empty
          else parties end as parties --else ouputs the result
from your_table

This is a more 'standard' approach
CREATE VIEW user_filled as
SELECT [parties]
FROM Users
UNION
SELECT 'EMPTY'

and when you query it (if needed -> on count(*))
select count(*)
from user_filled
where parties <> 'EMPTY'

on join
select *
from user_filled join other_table
      on (user_filled <> 'EMPTY and userfilled.key= other_table.key)

NOTE: put the clause into the ON so it's filtered out BEFORE the join is made


text:
Q: A function in $H^\infty(\Delta^2)$ Can you give an example of a function $f\in H^\infty(\Delta^2)$ with $f^{-1}\in L^\infty(T^2)$ but not inner? Here $H^\infty(\Delta^2)$ is the space of all bounded analytic functions defined on bi-disc $\Delta^2$ and $T^2$ is torus.

A: I'm not sure I understand your question. I assume that $f^{-1} = 1/f$? (The standard interpretation as the inverse of $f$ doesn't make sense.) Also, I assume that by inner you mean that the boundary value has modulus (suitably interpreted) has modulus $1$ almost everywhere.
If that is the case, almost any bounded zero-free holomorphic function will do. Take for example $f(z,w) = z-2$.


text:
Q: Trace of non-commutable matrices Let $M_1$ and $M_2$ be two symmetric $d\times d$ matrices. What is the relationship between
$tr(M_1M_2M_1M_2)$ and $tr(M_1^2 M_2^2 )$?
P.S. I tried a few examples and found
$$
tr(M_1M_2M_1M_2) \le tr(M_1^2 M_2^2 )
$$
seems always true. Is there a theorem?

A: Your conjecture is a special case of the following result which essentially follows from the Lieb-Thirring inequality.
Let $A$ and $B$ be Hermitian matrices. Then, for every positive integer $p$ we have
\begin{equation*}
 |\text{tr}(AB)^{2p}| \le \text{tr}A^{2p}B^{2p}
\end{equation*}

A: Not to take anything away from Suvrit's answer, but this is actually much simpler. First, we can assume $M_1$ is diagonal. Call it $diag(x_1, \dotsc, x_i).$
Then the difference between the LHS and the RHS is
$$\sum_{i> j} a_{ij}^2 (x_i - x_j)^2,$$
where the $a_{ij}$ are the entries of $M_2.$


text:
Q: How to connect SQL server database with JPA project - Wildfly server - Java EE Well, this question may be a duplicate or something. But I am desperate. I am learning Java EE and I cant even set up all the configurations properly.
My situation:
I have a Wildfly 8.1- Jboss server, up and ready.
I have deployed datasource (SQL server) Its working.
It has this JNDI:
java:/TimeTrackerDS
And this driver: sqlserver
Driver Class: com.microsoft.sqlserver.jdbc.SQLServerDriver
All this seems to be okay. Now I am deploying my new Application.
And I just dont know how to use this staff to connect to database.
The application is also deployed. How to connect these 2 things (db and app)
I have found a lot of solutions. Write properties to persistance.xml But I cant get anything to work. Because I don't understand it. Maybe if someone from you guys, show it to me on my particular example. I would understand what I am doing wrong.
(The server, app and sql server are all at same machine )(localhost)

A: I found the solution.
I have a mistake in my entity java class. So it didnt compile properly.
Propper persistence.xml for someone who may need it :
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

<persistence-unit name="TimeTracker">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>

    <jta-data-source>java:/TimeTrackerDS</jta-data-source>
    <class>model.Task</class>
    <properties>
        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.jdbc.batch_size" value="20" />
        <property name="hibernate.format_sql" value="true"/>
    </properties>

</persistence-unit>


text:
Q: Creating closed Range in Swift 3 not working Can anyone tell me why the code below works in Swift 2, but somehow breaks in Swift 3?
let range: Range = 0...2

However it can simply be fixed by doing this
let range: Range = 0..<3

Anyone knows what is the reason behind this?

A: Operators ... and ..< used to produce the same type, Range, in Swift 2.x. Now they produce different types (migration guide):

*

*Range

*CountableRange

*ClosedRange

*CountableClosedRange
Changing the type in the first assignment to ClosedRange should fix the problem. Better yet, let Swift infer the type for you:
let range = 0...2


text:
Q: mimic a table using css I'm trying to display a grid of items, with each item having a photo on the left and a description on the right, something like this:
----------------------------
| photo | item description |
----------------------------

I want to display these items in a 3x3 grid on the page. I have the grid part worked out, what I'm having trouble with is alignment of the photo and description. When the height of the description exceeds the height of the photo, I don't want the text to wrap under the photo.  I essentially want to maintain two separate columns.
I have tried this:
.item{
  padding-left: 60px; // size of photo + 5px margin
  background-position: 5px 0px;
}

  Here is the item description

That has worked very well. the markup is clean and I don't have to mess around with absolute/relative, however, now I can't add a border to the image.  Can anyone suggest a workaround or alternative?

A: IMHO that is not clean. Those are obviously content relevant images, so they shouldn't be background images.
It usually very simple with floating, but there are several other ways.
CSS:
.item img {
  float: left;
}

.item p {
  margin-left: 60px; // size of photo + 5px margin
}

HTML:

Here is the item description

A: Have a look here. You just need to apply min-height on your div.

A: Why don't you want to use a table?  This seems to me to be tabular data (admittedly with the image being a data element), so wouldn't a table would be the obvious choice?

A: you could use list-elements like so

Description

Image

Description

Image

Description

Image

Description

Image

Description

Image

Description

Image

Description

Image

Description

Image

Description

Image

and the CSS
ul {width: 960px; font-family: Arial; font-size: 12px; float: left;}
ul li {width: 80px; height: 180px; padding: 10px; background: #444444; list-style: none; float: left; color: #cccccc; }
ul li.image {width: 180px; height: 180px; padding: 10px; background: #cccccc; margin: 0 20px 20px 0; color: #444444; }


text:
Q: The practice of deep clone failed I tried to make a deep clone via overridong the clone method, but the result is not how a deep clone behaves(blanks and oldBlanks should print differently).
It is supposed to print:
192, []
1_2, [1]

It actually prints:
192, []
192, []

An MCVE is presented.
import java.util.ArrayList;

public class Program {

static class Blank implements Cloneable {

    @Override
    protected Blank clone()  {

        Blank b = new Blank(this);

        return b;

    }

    public Blank(String str) {
        origin = str;
        uradix = str.length();

        String strn = str.replaceAll("_","0");
        existed = Integer.parseInt(strn);

        for (int i = 0; i < uradix; i++) {

            int radix = uradix - i;

            if (str.charAt(i) == '_'){
                not_existed.add(radix-1);
            }

        }

    }

    public Blank(Blank b){
        this.origin = b.origin;
        this.uradix = b.uradix;
        this.existed = b.existed;

        for (Integer i :
                b.not_existed) {
            int k = i;
            this.not_existed.add(k);
        }
    }

    String origin;
    int uradix;
    int existed;
    ArrayList<Integer> not_existed = new ArrayList<>();//remain sequence: ->, i.e. left to right
}

static Blank[] copy(Blank[] ts){

    for (Blank t :
            ts) {
        t = t.clone();
    }

    return ts;
}

public static void main(String[] args) {

    Blank[] blanks = {new Blank("1_2"),new Blank("_2"),new Blank("_2_")};
    Blank[] oldBlanks = copy(blanks);

    StringBuilder sb = new StringBuilder(blanks[0].origin);

    System.out.println("before the change");
    System.out.println(blanks[0].origin+", "+blanks[0].not_existed);
    System.out.println(oldBlanks[0].origin+", "+oldBlanks[0].not_existed);

    int index = 1;
    sb.replace(index,index+1,"9");
    blanks[0] = new Blank(sb.toString());

    System.out.println("after the change");
    System.out.println(blanks[0].origin+", "+blanks[0].not_existed);
    System.out.println(oldBlanks[0].origin+", "+oldBlanks[0].not_existed);
}

}
p.s. My tutor said that a static class used in such a pattern is weird, but that should not be the problem because the problem reproduces even if I modify the class Blank outside non-static.

A: It's not your clone method that causes the problem, bBut rather the way you implemented your copy.
You return the original Blank[] reference and then adapt it.
If you do this:
static Blank[] copy(Blank[] ts){
    Blank[] ts_copy = new Blank[ts.length];
    for (int i=0; i<ts.length; i++) {
        ts_copy[i] = ts[i].clone();
    }
    return ts_copy;
}

Then I get an output like this:

before the change
  1_2, [1]
  1_2, [1]
  after the change
  192, []
  1_2, [1]


text:
Q: knife cookbook site downland with all dependencies I'm just starting out with chef, and I'm following http://gettingstartedwithchef.com. One thing it suggests is using knife cookbook site download $COOKBOOK_NAME to get community cookbooks. However sometimes they come with dependencies, and I then have to wait untill Vagrant tells me there's a problem and then manually download and install the packages one by one.
Is there anyway to get knife to download all the dependencies that a cookbook needs? It would speed things up.
I noticed knife cookbook site install, but that wants to do a pile of git stuff, which I don't want to do. I want to download the cookbook (which also means dependencies), I don't want to be making commits.
Is this possible?

A: Use Berkshelf or Librarian to manage your cookbooks.  It is MUCH easier than doing it with knife, and handles dependencies for you.


text:
Q: Send an IOS image across an api I have an image that I am trying to send to a rails app via my IOS app.
Step 1:
This grabs the image from the UIView
@IBOutlet var notifier: UILabel!
@IBOutlet var image: UIImage
@IBAction func Build(sender: AnyObject) {
    let image_data = UIImagePNGRepresentation(image.image!)
    self.service.createNewImage(notifier: notifier, image: image_data!)
}

Step 2:
This is the service
func createNewImage(notifier: UILabel, image: NSData) {
    let dataDictionary = ["image_data": image]
    self.post("image/build", data: dataDictionary).responseJSON { (response) -> Void in
            if(response.description[response.description.startIndex] as Character == "S") {
                notifier.text = "This should be success"
            } else {
                notifier.text  = "failure"
            }
      }
}

This code currently causes the error:  *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteMutableData)'
How do I package an image to send across an API?
Notes:
I believe the issue is coming from this line specifically:
    self.post("image/build", data: dataDictionary).responseJSON { (response) -> Void in

post is defined as:
func post(path: String) -> Request {

    return self.post(path, data: NSDictionary())
}

func post(path: String, data: NSDictionary) -> Request {
   let  url = self.url_from_path(path)
    return self.client.request(.POST, url, parameters: data as? [String : AnyObject] , encoding: ParameterEncoding.JSON,
        headers: self.getHeaders())
}

func patch(path: String, data: NSDictionary) -> Request {
    let  url = self.url_from_path(path)
    return self.client.request(.PATCH, url, parameters: data as? [String : AnyObject] , encoding: ParameterEncoding.JSON,
        headers: self.getHeaders())
}

A: This works:
    let strBase64:String = image.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
    let dataDictionary = ["image_data": strBase64]

You just convert the NSData which cannot be put into a JSON into a base64 string which can be put into a JSON


text:
Q: Align div element to bottom of container I am trying to bottom align one of three divs inside a container, but I'm having some issues.
As you will see, if I try and use absolute positioning on the bottom-aligned div the height becomes a problem.
I can set a specific height, but the content within the cta-item divs could vary from very small to very large.
I'm trying to create a solution for all use cases.
I know I can use jQuery to get the height of the largest cta-item div and adjust accordingly, but I'm trying to avoid using jQuery/JS for this whenever possible.
I created a fiddle here with what I currently have.
Thank you in advance!

.dynamic-cta-ctr {
  display: flex;
}
.dynamic-cta-ctr .cta-item {
  flex: 1;
  text-align: center;
  padding: 0 30px;
  position: relative;
  border-right: 1px solid #555;
}
.dynamic-cta-ctr .cta-item:last-child {
  border-right: none;
}
.dynamic-cta-ctr .cta-item .bottom-aligned {
  /* position: absolute;
  bottom: 0; */
}

Some content

Some content that sort of hangs around

Bottom aligned content

You can have your cake and eat it too!

Some content that sort of hangs around

Bottom aligned content

More people will come if you say we have punch and pie

Some content that sort of hangs around

Bottom aligned content

A: Add this to your code:
.cta-item {
   display: flex;
   flex-direction: column;
}

.bottom-aligned {
    margin-top: auto;
}

revised fiddle
More details here: Methods for Aligning Flex Items


text:
Q: Querying a database with any subset of a list of conditions I have a MySQL database with a number of columns (say column0 .. column19).
I want to select all rows of the database which satisfy a condition of the form:
column0 < value0 AND column1 < value1 AND ... AND column19 < value19.

The catch is that I want to select rows which satisfy ANY 15 conditions out of the above.
I know I can do multiple queries will all possible combinations of 15 conditions, but I'm looking for a solution with only 1 query.
Is it possible with MySQL? Is there another database architecture which allows such queries?
Thanks

A: You could use the below, but don't expect it'll perform particularly well!
WHERE (CASE WHEN column0 < value0 THEN 1 ELSE 0 END +
      CASE WHEN column1 < value1 THEN 1 ELSE 0 END +
      ... +
      CASE WHEN column19 < value19 THEN 1 ELSE 0 END) >= 15

A: Will's answer can also be written as:
WHERE (  SUM( column0 < value0 )
       + SUM( column1 < value1 )
       ... +
       + SUM( column19 < value19 )
      ) >= 15

The above will work only in MYSQL, not other databases. So, I suppose it's better to use the standard CASE WHEN than this.

Another way to handle such a query would be like this (id is the primary key of the table):
SELECT *
FROM yourTable
    JOIN
      ( SELECT id
        FROM yourTable
        WHERE column0 < value0
      UNION ALL
        SELECT id
        FROM yourTable
        WHERE column1 < value1
      UNION ALL
        ...
      UNION ALL
        SELECT id
        FROM yourTable
        WHERE column19 < value19

      GROUP BY id
      HAVING COUNT(*) >=15
      ) AS chk
    ON chk.id = yourTable.id

If there are 20 indexes (one on every column0, column1, ..., column19), it might, might be quicker.


text:
Q: Using JOIN to display data in a table Thanks for reading my question
i am trying to make *clients_id* from the table repair_jobs appear as the name from the table contacts
but i am having no luck
i have got 2 sql query's is this wrong?
the 1st
$query = "select * from repair_jobs";

this helps me display the information i need regarding the fields from repair_jobs and works
this is the 2nd
$query = "SELECT repair_jobs.client_id, contacts.name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.name";

under that i have this to try to display the name of the client
echo "{$client_id}	";

but it is only displaying the number and not the data (clients name) that i need
am i missing something?

Additional information
The client_id (repair_jobs) is a number and is the same as id (contacts) but wanting to display the name (contacts)
CLIENTS
Id – name – surname – phone – address

REPAIRS
Id – clients_id (same as id in clients) – unit – date – price

current code
<?php
//include database connection
include 'db_connect.php';

//query all records from the database
$query = "select * from repair_jobs";

//execute the query
$result = $mysqli->query( $query );

//get number of rows returned
$num_results = $result->num_rows;

//this will link us to our add.php to create new record
if( $num_results > 0){ //it means there's already a database record

    //start table
    //creating our table heading
    echo "
";
    echo "

";
        echo "Job #	";
        echo "Name Of Unit	";
        echo "Client	";
        echo "Estimated Value	";
    echo "

";

    //loop to show each records
    while( $row = $result->fetch_assoc() ){
            //extract row
            //this will make $row['firstname'] to
            //just $firstname only
            extract($row);

            //creating new table row per record
            echo "
";
                echo "# {$id}	";
                echo "{$rmake} {$rmodel}	";

$query = "SELECT rj.client_id, c.name AS client_name FROM repair_jobs rj INNER JOIN contacts c ON rj.client_id=c.id";
echo "{$client_name}	";

echo '£';
$lhours = $labour;
$repaircosts = $ourcosts;
$labourpay = $labourcharge;
$sum_total = $repaircosts +($lhours * $labourpay);

print ($sum_total);
echo '	';
echo "	";
echo "";
    }

    echo "

";//end table

}else{
    //if database table is empty
    echo "No records found.";
}

//disconnect from database
$result->free();
$mysqli->close();

?>

A: Change your 1st query to you join query, as there is no reason to do a 2nd query in the middle of your code. (also you never executed that query anyway).
//query all records from the database
$query = "SELECT repair_jobs.*, contacts.name as client_name
FROM repair_jobs
INNER JOIN contacts
ON repair_jobs.client_id=contacts.id";

Then in your table keep the $client_name
echo "{$client_name}	";

A: <?php
include 'db_connect.php';
$query = "SELECT rj.Id AS job_number, rj.unit, rj.make, rj.model, c.name AS client_name, rj.price FROM repair_jobs rj INNER JOIN contacts c ON rj.clients_id = c.id ORDER BY c.date";
$result = $mysqli->query( $query );
$num_results = $result->num_rows;
if( $num_results > 0){ //it means there's already a database record
    echo "
";
    echo "

";
    echo "Job #	";
    echo "Name Of Unit	";
    echo "Client	";
    echo "Estimated Value	";
    echo "

";
    while( $row = $result->fetch_assoc() ){
        extract($row);
        echo "
";
        echo "#{$job_number}	";
        echo "{$make} {$model}	";
        echo "{$client_name}	";
        echo "£";
        $lhours = $labour;
        $repaircosts = $ourcosts;
        $labourpay = $labourcharge;
        $sum_total = $repaircosts +($lhours * $labourpay);
        echo $sum_total;
        echo '	';
        echo "	";
        echo "
";
    }
    echo "

";
} else {
    echo "No records found.";
}
$result->free();
$mysqli->close();
?>


text:
Q: Laravel Form helper not show data after validation error i'm having problem with forms helper in laravel 5.3.
I have a foreach that shows my data in a form.
Everythins work fine, until i submit a form and validation fails.
Therefore, when validation fails, the input text in my form not show the previus data, but only the data which were submitted.
Here the code:
@foreach($cars as $car)
    {!! Form::model($car, ['route' => ['cars.update', $car->id], 'method' => 'PUT']) !!}

            {{ Form::label('name', $car->name) }}
            {{ Form::text('name', $car->name, ['class' => 'editbox-normal']) }}

            {{ Form::label('phone', 'Phone') }}
            {{ Form::text('phone', null, ['class' => 'editbox-normal']) }}

            {{ Form::label('license_plate', 'License plate') }}
            {{ Form::text('license_plate', null, ['class' => 'editbox-normal']) }}

            {{ Form::label('total_km', 'KM') }}
            {{ Form::text('total_km', null, ['class' => 'editbox-normal']) }}

            {{ Form::submit('Submit', ['class' => 'btn btn-edit']) }}

    {!! Form::close() !!}
@endforeach

If i submit one of those forms and validation fails, for example name is required and name input is empty, laravel flash $error, but every input of each form displays the data of the submitted form. In this example, every name input will be empty, and phone, license_plate and total_km will have the same value.
Instead, if i use pure html code for the input, everythinks work fine.
In addition, if you notice, the fist label has the value set to $car->name, the same of the text input, but in the label it is shows correctly, in the input not.
Anyone knows why?
Thanks in advance.

A: This is actually intended behaviour. This way, when you e.g. forget to enter your name, the rest of the data you entered isn't lost.
In your use case, however, this leads to unintended results (because you have multiple forms on the same page). I would advise splitting the forms up to different pages :)


text:
Q: Failing to install MySQL-python I am tying to install MySQL-python in a python 2.7 virtual environment but I am getting the following error:
Installing collected packages: MySQL-python
Running setup.py install for MySQL-python ... error
ERROR: Command errored out with exit status 1:
 command: /home/jhylands/py2/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-FUMQGL/install-record.txt --single-version-externally-managed --compile --install-headers /home/jhylands/py2/include/site/python2.7/MySQL-python
     cwd: /tmp/pip-install-scNGlE/MySQL-python/
Complete output (30 lines):
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb
creating build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants
running build_ext
building '_mysql' extension
creating build/temp.linux-x86_64-2.7
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-1x6jhf/python2.7-2.7.18~rc1=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o
_mysql.c:44:10: fatal error: my_config.h: No such file or directory
   44 | #include "my_config.h"
      |          ^~~~~~~~~~~~~
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
----------------------------------------
ERROR: Command errored out with exit status 1: /home/jhylands/py2/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-scNGlE/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-FUMQGL/install-record.txt --single-version-externally-managed --compile --install-headers /home/jhylands/py2/include/site/python2.7/MySQL-python Check the logs for full command output.

I have already tried installing the solutions suggested in this post
 and this post

A: So I managed to solve the issue with the following command:
sudo wget https://raw.githubusercontent.com/paulfitz/mysql-connector-c/master/include/my_config.h -P /usr/include/mysql/

Which I found from a comment on this answer.

A: According to the MySQL 8 docs:
https://dev.mysql.com/doc/relnotes/mysql/8.0/en/news-8-0-2.html

These changes were made with respect to client program development:
Client programs should only need to #include the <mysql.h> header file. In particular, <my_config.h> should not be needed, and is no longer installed.

So, it's likely that new installations of libmysqlclient-dev exclude my_config.h for that reason.
However, that also suggests a very simple answer -- when a program tries to include my_config.h, give them mysql.h instead:
sudo apt install libmysqlclient-dev
sudo ln -s /usr/include/mysql/mysql.h /usr/include/mysql/my_config.h

I was able to pip install MySQL-python==1.2.5 successfully on Ubuntu 20.04 LTS with that softlink added.


text:
Q: What is actually a Determinant? The way I've been introduced to determinants is that if there is a system of  two linear equations then we can represent the coefficients of the variables and the constants in the form of a matrix.
Now if we plot the matrices on the coordinate system then we will get a parallelogram and if we calculate the area of the parallelogram then we will get the determinant of the given matrix.
For eg if A is the matrix then its determinant will be:
$ad-cb$.
i.e. |A|= $ad-cb$.
if A=$\begin{bmatrix}a & b\\c & d\end{bmatrix}$
Now the questions I want to ask:
1)What is a determinant actually what does it tells us about a system of equations?
2)The area found by the formula $ad-cb$, how is it telling us a determinant? Basically how the area of parallelogram telling the value of determinant?
3)In my book its given that: system of equations has a unique solution or not is determined by the number of ab-cd.What does this mean?

A: A determinant is basically a measure of volume (or area) together with the $\pm$ sign making it more strictly speaking an oriented volume.
So if you imagine your given basis and the linear transformation operating on them, then your determinant measures how the volume spanned by those basis vectors changes. The volume will be scaled by the determinant of the transformation. The $\pm$ sign corresponds to whether that volume will be 'flipped', loosely speaking.
But what happens if the determinant is zero? Then that means your volume must now be zero.
What does that mean for your system of equations? If you visualise your transformation as mapping vectors into some other vectors, then what you'll soon be able to imagine is that if your volume after the transformation has to be zero, so you're basically dropping down to a lower-dimensional space, then there's no way you can still have exactly one vector which transforms into whatever vector is on the right hand side of your equation $Ax=b.$ Otherwise you'd have a nonzero volume.
So if a determinant is zero, that means your system of equations couldn't possibly have a unique solution.

A: (1) A system of two linear equations in two variables can be written (in the standard way) as a matrix system $A \vec x = \vec b$, where $A$ is a $2\times 2$ matrix. Let's say its entries are
$$A = \begin{pmatrix} a & b \\ c & d \end{pmatrix}.$$
The determinant of $A$ is the value $ad-bc$. It's (mostly) only important whether this value is zero or nonzero. If $\det(A) = 0$, the system of equations does not have a unique solution (meaning it has either no or more than one solution), no matter what $\vec b$ is; it may not have a solution at all, depending on $\vec b$. If $\det(A) \ne 0$, the system has a unique solution, no matter what $\vec b$ is. You can prove this quite easily in the case of $2\times 2$ matrices.
(2) The determinant is the value $ad-bc$. It happens to also give you the (signed) area of the parallelogram you're thinking of. That is a property of the determinant, but it would be a horrible definition of the determinant. It's hardly an obvious consequence of the definition of the determinant, either (unless you really only care about $2\times 2$ matrices, in which case, see @J.G.'s answer). But that's not to say you shouldn't keep in mind that it has this property.
(3) See the end of (1).

A: I'm not sure how questions 1), 2) differ, but I think you want a proof that the determinant is an area.
Note first that $A$ sends the usual basis elements to vectors given by $A$'s columns. If a parallelogram has edges equal to these vectors, which we'll call $\vec{A}_1,\,\vec{A}_2$, and the angle between these is $\theta$, the parallelogram's area is $|\vec{A}_1||\vec{A}_2|\sin\theta$. With the abbreviation $v^2:=\vec{v}\cdot\vec{v}$, the squared area is $$A_1^2A_2^2\sin^2\theta=A_1^2A_2^2-A_1^2A_2^2\cos^2\theta=A_1^2A_2^2-(\vec{A}_1\cdot\vec{A}_2)^2.$$This turns out to be $$(a^2+c^2)(b^2+d^2)-(ab+cd)^2=(ad-bc)^2,$$ i.e. the area is $\pm(ad-bc)$.
It can also be proven - but it's more complicated to do so - that in general if $A\in\Bbb R^{n\times n}$ then $\det A$ is, up to a sign, the measure of the parallelotope whose edges are $A$'s columns.
As for 3), $A\vec{x}=\vec{b}$ has a unique solution iff $\det A\ne 0$. By contrast, if $\det A=0$ then $A\vec{x}=\vec{b}$ has either no solutions or infinitely many of them, depending on the choice of $\vec{b}$.


text:
Q: Send data to php on window close Can you tell me why this doesn't work..?? also tried with window.unload but it also didn't worked
   window.onbeforeunload = function(){
                 $.ajax({
             url:'logout.php',
             type:'POST',
             data:{user:$("#user").val()},
             success: function(response){

                   alert(response);
                 }

             })

}

A: Well, you can set async: false on your AJAX call to make the browser wait for the request to finish before doing anything else, but note that this will 'hang' the browser for the duration of the request.
async: false,

A: Make the ajax call synchronous. As the call is asynchronous, before you get anything back the window is closed.


text:
Q: Cart Price Rules - discount on certain number of products i am new in Magento, i want to to add discount on certain number of products.
I mean, i have products on my store, every product has SKU.
I want to make discount 50% for purchasing 12 products on my site.
So the number 12 should be in the cart, no matter if it's 12 pieces of one product, or several products with a total of 12 pieces.

A: Log in to Magento Admin and GoTo Marketing > Cart Price Rules and create a new rule by clicking Add New Rule
Now you can set the condition
See below screenshots
https://prnt.sc/1vpk1b3
Set the discount Percentage
See below screenshots
https://prnt.sc/1vpk6ki


text:
Q: OSX copy DVD data while resetting permissions I have a DVD of .dwg files I need to copy from a DVD to my mac. The files are organised in a folder structure on the DVD as well.
The problem seems to be that while I can cope some files across the folders have permissions as read only. As the copy process isn't complete the files do not have permission to be written to these read only folders. ~70% transfer is achieved.
Resetting permissions and copying manually would take a days.
Is there a way, perhaps in terminal, I can force the dvd to copy all data? Or, a way to copy with new read/write permissions allowing for the DVD to copy completely.
Any help greatly appreciated!!


text:
Q: Calculate the sum of values within an array of objects I am trying to find the total sum for each item sold inside an array, like so:
The array looks like this:
 [
  {
    'Some Title Item', '22', 'Apple'
  },
  {
    'Another Item', '12', 'Android'
  },
  {
    'Third Item', '15', 'Android'
  },
  {
    'Another Item', '6', 'Apple'
  },...
]

I already have a variable were I store all the titles/labels, and now need to find the sum of total items sold for each of those.

A: Your input and output must be arrays.
Use array.reduce for achieve your desired result.

const data = [
  [
    'Some Title Item', '22', 'Apple'
  ],
  [
    'Another Item', '12', 'Android'
  ],
  [
    'Third Item', '15', 'Android'
  ],
  [
    'Another Item', '6', 'Apple'
  ]
];
let output = [];
output = data.reduce((acc, curr) => {
  const node = acc.find((node) => node[0] === curr[0]);
  if (node) {
    node[1] += Number(curr[1]);
  } else {
    acc.push([curr[0], Number(curr[1])]);
  }
  return acc;
}, []);
console.log(output);


text:
Q: Generating a ECDSA Private key in bouncy castle returns a PUBLIC key I am attempting to use bouncy castle to generate ECDSA keys. The code seems to work fine from the Java perspective; but, when I dump the file and try to validate the data, OpenSSL does not like the format of the data.
After some research, I figured that bouncy castle is encoding the private key as public key.
Here is my Java code:
public class Test {
    public static void main(String[] args) {
        Security.addProvider(new BouncyCastleProvider());
        System.out.println("Starting...");
        String name = "prime256v1";
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
            kpg.initialize(new ECGenParameterSpec(name));
            KeyPair keyPair = kpg.generateKeyPair();
            FileOutputStream writer = new FileOutputStream("private.key");
            writer.write(keyPair.getPrivate().getEncoded());
            writer.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

The file private.key is generated in valid DER format; however, when I run the following command to see the ASN.1 structure of the key:
$ openssl asn1parse -inform DER -in /my/path/private.key
    0:d=0  hl=3 l= 147 cons: SEQUENCE
    3:d=1  hl=2 l=   1 prim: INTEGER           :00
    6:d=1  hl=2 l=  19 cons: SEQUENCE
    8:d=2  hl=2 l=   7 prim: OBJECT            :id-ecPublicKey
   17:d=2  hl=2 l=   8 prim: OBJECT            :prime256v1
   27:d=1  hl=2 l= 121 prim: OCTET STRING      [HEX DUMP]: <hex data>

For comparison, if I run the following commands to generate a ECDSA key using OpenSSL, I get  the following ASN.1 structure:
 $ openssl ecparam -name prime256v1 -genkey -noout -outform DER -out private.key
 $ openssl asn1parse -inform DER -in private.key
     0:d=0  hl=2 l= 119 cons: SEQUENCE
     2:d=1  hl=2 l=   1 prim: INTEGER           :01
     5:d=1  hl=2 l=  32 prim: OCTET STRING      [HEX DUMP]: <hex data>
    39:d=1  hl=2 l=  10 cons: cont [ 0 ]
    41:d=2  hl=2 l=   8 prim: OBJECT            :prime256v1
    51:d=1  hl=2 l=  68 cons: cont [ 1 ]
    53:d=2  hl=2 l=  66 prim: BIT STRING

So, I guess my questions are

*

*Is there anything I am missing?

*Or is this a known bug?

*Is there anyway to get around it?

A: Java outputs key in the encoded format. You should try:
private String getPrivateKeyAsHex(PrivateKey privateKey) {

    ECPrivateKey ecPrivateKey = (ECPrivateKey) privateKey;
    byte[] privateKeyBytes = new byte[PRIVATE_KEY_LENGTH];
    writeToStream(privateKeyBytes, 0, ecPrivateKey.getS(), PRIVATE_KEY_LENGTH);

    String hex = Hex.toHexString(privateKeyBytes);

    logger.debug("Private key bytes: " + Arrays.toString(privateKeyBytes));
    logger.debug("Private key hex: " + hex);

    return hex;
}

private String getPublicKeyAsHex(PublicKey publicKey) {

    ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
    ECPoint ecPoint = ecPublicKey.getW();

    byte[] publicKeyBytes = new byte[PUBLIC_KEY_LENGTH];
    writeToStream(publicKeyBytes, 0, ecPoint.getAffineX(), PRIVATE_KEY_LENGTH);
    writeToStream(publicKeyBytes, PRIVATE_KEY_LENGTH, ecPoint.getAffineY(), PRIVATE_KEY_LENGTH);

    String hex = Hex.toHexString(publicKeyBytes);

    logger.debug("Public key bytes: " + Arrays.toString(publicKeyBytes));
    logger.debug("Public key hex: " + hex);

    return hex;
}

private void writeToStream(byte[] stream, int start, BigInteger value, int size) {
    byte[] data = value.toByteArray();
    int length = Math.min(size, data.length);
    int writeStart = start + size - length;
    int readStart = data.length - length;
    System.arraycopy(data, readStart, stream, writeStart, length);
}


text:
Q: What are your tips for finding a replacement battery for mac book pro? The battery on my mac book pro (late 2008) running OS X Yosemite needs to be replaced. The battery only holds half capacity. What are your tips for finding a good battery. What battery do you recommend?

A: Practically all third party batteries for mac are s**t, go to Apple and buy an apple battery. Expensive but worth the money. I am speaking from a hard way of learning...
LS


text:
Q: Redis command in NodeJS hangs indefinitely I'm trying to insert some data into a redis cache  using the Redis NPM library but even tho' it says it's connected, every single command after connects hangs indefinitely and I don't understand what is the problem since there is no errors being printed in the console.
// Connect to Redis Elasticache
const redisClient = redis.createClient({
    socket: {
        host: configuration.REDIS_HOST,
        port: configuration.REDIS_PORT,
    },
});
redisClient.on('connect', function() {
    console.log('Connected!'); //Gets Printed
});

redisClient.on('error', err => {
    console.log(err);
});
redisClient.on("ready", (err) => {
    console.log("ready"); //Gets Printed
});

await redisClient.connect();
console.log(redisClient.isOpen); //returns true

await redisClient.RPUSH("data", "some data");

console.log("Pushed Message"); // never executes

Have tried multiple commands such as get,set and none of them works, all of them hangs.


text:
Q: Front end help needed Not sure if this is appropriate for SO, if not I will take down but I am in need of help doing some of my front-end. Basically I have a div and a child div that handles all my data that I need. that child div has a width, and it works well until you hit a certain point (if you minimize screen width you'll see what I am saying). How can I make it so the div holding the items is always centered? Also, I am asking in the sense of this being responsive.
Part 2) how can I make it so the button is always in the middle, but JUST to the right (because I plan on having a previous button)?
I am using twitter bootstrap if that helps with this! (I have tried a lot of things and have not had any success, I tried utilizing the 'pull-right' and 'pull-left' classes with no prevail, I have tried using the span classes they offer with no luck as well.)
 Live demo
code:

Our Products

                <form method="post">

                        <button class="btn btn-success" type="submit" name="next"> Next </button>

                            @{
                                x = getPageNum * 6;
                            }

                                @for (int i = x; i < @itemsPerPage; i++)
                                {

                                                @Html.DisplayFor(m => m[i].title)

                                                @Html.DisplayFor(m => m[i].price)

                                }

                </form>

A: From what I see is that the Div containing the elements is centered in the middle, your problem is that the elements themselves are not centered inside that Div. What you can do is give the container That is holding both the pictures and the buttons Text-align: center;
.container {
    text-align: center;
}

that will center both the pictures and the button. Then give the button a little margin to move it to the right a little.
button {
    margin-left: 150px;
}


text:
Q: CV.imwrite is returning a black square My simple resizing code is returning a black square in the desired size. This is obviously some rookie error but I can't work out for the life of me what it is.
Has nothing to do with compression as I have tried with a blank image and the same result occurs.
    img = cv2.imread('imageToSave.jpg')
    # percent of original size
    width = 28
    height = 28
    dim = (width, height)
    res = cv2.resize(img, dim)
    cv2.imwrite('imageToSave.jpg',res)

Ideally the result would be a rescaled version of the 'imageToSave file

A: I may be too down to earth but did you try to display your picture after the reading and after your resize instead of saving it locally?
These two step will locate the issue, and you'll fix it quick i think :)


text:
Q: Ubuntu server hardisk read-only Detected IO errors while flushing file data on sdc-8 I am having a server running  Ubuntu 16.04 with some data writing on external hardisk. Suddenly the server stops working on Nov 6 and when I restart the server it start working without problem, I got the following error from log file Detected IO errors while flushing file data on sdc-8. I have seen that the last writ on disk has happens on Nov 6 12:44:01  and I have attached the log at that time.
Can anyone help me to find what could be happens at that time.  So I can apply the fix on my server to prevent such a situation.
Nov  6 12:27:09 user kernel: [10350005.519121] scsi_io_completion: 11 callbacks suppressed
Nov  6 12:27:09 user kernel: [10350005.519132] sd 2:0:0:0: [sdc] tag#10 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519141] sd 2:0:0:0: [sdc] tag#10 CDB: Write(16) 8a 00 00 00 00 00 1d fc f3 28 00 00 01 28 00 00
Nov  6 12:27:09 user kernel: [10350005.519144] print_req_error: 11 callbacks suppressed
Nov  6 12:27:09 user kernel: [10350005.519147] print_req_error: I/O error, dev sdc, sector 503116584
Nov  6 12:27:09 user kernel: [10350005.519156] EXT4-fs warning: 4 callbacks suppressed
Nov  6 12:27:09 user kernel: [10350005.519162] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 85219810 (offset 0 size 151552 starting block 62889610)
Nov  6 12:27:09 user kernel: [10350005.519165] buffer_io_error: 741 callbacks suppressed
Nov  6 12:27:09 user kernel: [10350005.519167] Buffer I/O error on device sdc, logical block 62889573
Nov  6 12:27:09 user kernel: [10350005.519174] Buffer I/O error on device sdc, logical block 62889574
Nov  6 12:27:09 user kernel: [10350005.519179] Buffer I/O error on device sdc, logical block 62889575
Nov  6 12:27:09 user kernel: [10350005.519183] Buffer I/O error on device sdc, logical block 62889576
Nov  6 12:27:09 user kernel: [10350005.519188] Buffer I/O error on device sdc, logical block 62889577
Nov  6 12:27:09 user kernel: [10350005.519192] Buffer I/O error on device sdc, logical block 62889578
Nov  6 12:27:09 user kernel: [10350005.519197] Buffer I/O error on device sdc, logical block 62889579
Nov  6 12:27:09 user kernel: [10350005.519201] Buffer I/O error on device sdc, logical block 62889580
Nov  6 12:27:09 user kernel: [10350005.519206] Buffer I/O error on device sdc, logical block 62889581
Nov  6 12:27:09 user kernel: [10350005.519210] Buffer I/O error on device sdc, logical block 62889582
Nov  6 12:27:09 user kernel: [10350005.519258] sd 2:0:0:0: [sdc] tag#9 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519263] sd 2:0:0:0: [sdc] tag#9 CDB: Write(16) 8a 00 00 00 00 00 1d fc f0 98 00 00 01 30 00 00
Nov  6 12:27:09 user kernel: [10350005.519266] print_req_error: I/O error, dev sdc, sector 503115928
Nov  6 12:27:09 user kernel: [10350005.519274] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 86550053 (offset 0 size 155648 starting block 62889529)
Nov  6 12:27:09 user kernel: [10350005.519322] sd 2:0:0:0: [sdc] tag#8 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519327] sd 2:0:0:0: [sdc] tag#8 CDB: Write(16) 8a 00 00 00 00 00 1d fc 1c a0 00 00 01 30 00 00
Nov  6 12:27:09 user kernel: [10350005.519330] print_req_error: I/O error, dev sdc, sector 503061664
Nov  6 12:27:09 user kernel: [10350005.519337] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 85219807 (offset 0 size 155648 starting block 62882746)
Nov  6 12:27:09 user kernel: [10350005.519384] sd 2:0:0:0: [sdc] tag#7 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519389] sd 2:0:0:0: [sdc] tag#7 CDB: Write(16) 8a 00 00 00 00 01 21 80 00 38 00 00 00 08 00 00
Nov  6 12:27:09 user kernel: [10350005.519391] print_req_error: I/O error, dev sdc, sector 4857004088
Nov  6 12:27:09 user kernel: [10350005.519397] Buffer I/O error on dev sdc, logical block 607125511, lost async page write
Nov  6 12:27:09 user kernel: [10350005.519422] sd 2:0:0:0: [sdc] tag#6 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519427] sd 2:0:0:0: [sdc] tag#6 CDB: Write(16) 8a 00 00 00 00 01 21 44 4b c0 00 00 00 18 00 00
Nov  6 12:27:09 user kernel: [10350005.519429] print_req_error: I/O error, dev sdc, sector 4853091264
Nov  6 12:27:09 user kernel: [10350005.519437] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 151685307 (offset 0 size 0 starting block 606636409)
Nov  6 12:27:09 user kernel: [10350005.519444] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 151688454 (offset 0 size 4096 starting block 606636410)
Nov  6 12:27:09 user kernel: [10350005.519451] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 151688455 (offset 0 size 4096 starting block 606636411)
Nov  6 12:27:09 user kernel: [10350005.519464] sd 2:0:0:0: [sdc] tag#5 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519468] sd 2:0:0:0: [sdc] tag#5 CDB: Write(16) 8a 00 00 00 00 01 21 44 4b 68 00 00 00 08 00 00
Nov  6 12:27:09 user kernel: [10350005.519471] print_req_error: I/O error, dev sdc, sector 4853091176
Nov  6 12:27:09 user kernel: [10350005.519477] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 151688477 (offset 0 size 4096 starting block 606636398)
Nov  6 12:27:09 user kernel: [10350005.519494] sd 2:0:0:0: [sdc] tag#4 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519498] sd 2:0:0:0: [sdc] tag#4 CDB: Write(16) 8a 00 00 00 00 01 21 44 40 c8 00 00 00 78 00 00
Nov  6 12:27:09 user kernel: [10350005.519500] print_req_error: I/O error, dev sdc, sector 4853088456
Nov  6 12:27:09 user kernel: [10350005.519507] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 151688476 (offset 0 size 4096 starting block 606636058)
Nov  6 12:27:09 user kernel: [10350005.519520] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 151688479 (offset 0 size 4096 starting block 606636059)
Nov  6 12:27:09 user kernel: [10350005.519532] EXT4-fs warning (device sdc): ext4_end_bio:323: I/O error 10 writing to inode 151688481 (offset 0 size 4096 starting block 606636060)
Nov  6 12:27:09 user kernel: [10350005.519581] sd 2:0:0:0: [sdc] tag#3 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519586] sd 2:0:0:0: [sdc] tag#3 CDB: Write(16) 8a 00 00 00 00 01 21 41 87 38 00 00 00 08 00 00
Nov  6 12:27:09 user kernel: [10350005.519588] print_req_error: I/O error, dev sdc, sector 4852909880
Nov  6 12:27:09 user kernel: [10350005.519593] Buffer I/O error on dev sdc, logical block 606613735, lost async page write
Nov  6 12:27:09 user kernel: [10350005.519609] sd 2:0:0:0: [sdc] tag#2 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519614] sd 2:0:0:0: [sdc] tag#2 CDB: Write(16) 8a 00 00 00 00 01 21 41 56 60 00 00 00 08 00 00
Nov  6 12:27:09 user kernel: [10350005.519616] print_req_error: I/O error, dev sdc, sector 4852897376
Nov  6 12:27:09 user kernel: [10350005.519620] Buffer I/O error on dev sdc, logical block 606612172, lost async page write
Nov  6 12:27:09 user kernel: [10350005.519637] sd 2:0:0:0: [sdc] tag#1 FAILED Result: hostbyte=DID_OK driverbyte=DRIVER_TIMEOUT
Nov  6 12:27:09 user kernel: [10350005.519641] sd 2:0:0:0: [sdc] tag#1 CDB: Write(16) 8a 00 00 00 00 01 21 41 56 40 00 00 00 10 00 00
Nov  6 12:27:09 user kernel: [10350005.519643] print_req_error: I/O error, dev sdc, sector 4852897344
Nov  6 12:27:09 user kernel: [10350005.519648] Buffer I/O error on dev sdc, logical block 606612168, lost async page write
Nov  6 12:27:09 user kernel: [10350005.519653] Buffer I/O error on dev sdc, logical block 606612169, lost async page write
Nov  6 12:27:09 user kernel: [10350005.519664] Buffer I/O error on dev sdc, logical block 606603630, lost async page write
Nov  6 12:27:09 user kernel: [10350005.520026] JBD2: Detected IO errors while flushing file data on sdc-8
Nov  6 12:44:41 user kernel: [10351057.165709] Aborting journal on device sdc-8.
Nov  6 12:44:41 user kernel: [10351057.269153] EXT4-fs error (device sdc): ext4_journal_check_start:61: Detected aborted journal
Nov  6 12:44:41 user kernel: [10351057.269160] EXT4-fs (sdc): Remounting filesystem read-only
Nov  6 12:44:41 user kernel: [10351057.277460] EXT4-fs error (device sdc): ext4_journal_check_start:61: Detected aborted journal
Nov  6 12:44:41 user kernel: [10351057.285798] EXT4-fs error (device sdc): ext4_journal_check_start:61: Detected aborted journal
Nov  6 12:44:41 user kernel: [10351057.344165] EXT4-fs error (device sdc): ext4_journal_check_start:61: Detected aborted journal
Nov  6 12:44:41 user kernel: [10351057.352474] EXT4-fs error (device sdc): ext4_journal_check_start:61: Detected aborted journal
Nov  6 12:44:41 user kernel: [10351057.352483] EXT4-fs (sdc): ext4_writepages: jbd2_start: 1024 pages, ino 86550607; err -30

A: This is likely a hardware problem with your disk.  The kernel is sending data to the disk, but the disk has timed out in sending a reply.  It may happen to work after restarting the system or the disk, but the problem will probably reoccur again and again until the disk dies.
You should copy the data to a new disk using dd if that's possible and then discard the old disk.  You can try querying the disk with smartctl as outlined in this document about running SMART self-tests to see if it reports any problems.


text:
Q: New to database design (Postgres) seeking advice I am new to designing databases. I come from a front end background. I am looking to design a database that stores performance metrics of wind turbines. I was given an excel file. The list of metrics is nearly 200 and you can see the first few in this image.

I can't think of the best way to represent this data in a database. My first thought was to import this table as is into a database table and add a turbine-id column to it. my second through was to create a table for each metric and add a turbine-id column to each of those tables. What do you guys think. What is the best way for me to store the data that would set me up with a performant database. Thank you for your help and input

A: One way to do it would be something like this:
TURBINE
  ID_TURBINE         INTEGER PK
  LATITUDE           DECIMAL
  LONGITUDE          DECIMAL

METRIC
  ID_METRIC          INTEGER PK
  METRIC_NAME        VARCHAR UNIQUE
  VALUE_TYPE         VARCHAR
    Allowed values = ('BOOLEAN', 'PERCENTAGE', 'INTEGER', 'DOUBLE', 'STRING')

TURBINE_METRIC
  ID_TURBINE_METRIC        INTEGER PK
  ID_TURBINE               INTEGER
     FOREIGN KEY TO TURBINE
  METRIC_NAME              VARCHAR
     FOREIGN KEY TO METRIC
  BOOLEAN_VALUE            BOOLEAN
  PERCENTAGE_VALUE         DOUBLE
  INTEGER_VALUE            INTEGER
  DOUBLE_VALUE             DOUBLE
  STRING_VALUE             VARCHAR

Flesh this out however you need it to be. I have no idea how long your VARCHAR fields should be, etc, but this allows you flexibility in terms of which metrics you store for each turbine. I suppose you could make the LATITUDE and LONGITUDE metrics as well - I just added them to the TURBINE table to show that there may be fixed info which is best stored as part of the TURBINE table.

A: You want one table to represent turbines (things true of the turbine, like its location) and one or more of turbine metrics that arrive over time.  If different groups of metrics arrive at different intervals, put them in different tables.
One goal I would have would be to minimize the number of nullable columns.  Ideally, every column is defined NOT NULL, and invalid inputs are set aside for review. What is and is not nullable is controlled by promises made by the system supplying the metrics.
That's how it's done: every table has one or more keys that uniquely identify a row, and all non-key columns are information about the entity defined by the row.
It might seem tempting and "more flexible" to use one table of name-value pairs, so you never have to worry about new properties if the feed changes.  That would be a mistake, though (a classic one, which is why I mention it).  It's actually not more flexible, because changes upstream will require changes downstream, no matter what.  Plus, if the upstream changes in ways that aren't detected by the DBMS, they can subtly corrupt your data and results.
By defining as tight a set of rules about the data as possible in SQL, you guard against missing, malformed, and erroneous inputs.  Any verification done by the DBMS is verification that the application can skip, and that no application will be caught by.
For example, you're given min/max values for wind speed and so on.  These promises can form constraints in the database.  If you get negative wind speed, something is wrong.  It might be a sensor problem or (more likely) a data alignment error because a new column was introduced or the input was incorrectly parsed.  Rather than put the wind direction mistakenly in the wind speed column, the DBMS rejects the input, and someone can look into what went wrong.
Don't forget to have fun.  You have an opportunity to create a new database in a growing industry, and learn about database technology and theory at the same time.  Doesn't happen every day!


text:
Q: sort array starts with specific word or letter in angular2 I have a JSON response and I want to order by it which starts with specific words or letter.
I need it to sort  ItenaryFor which starts with "ItenaryFor": "Sightseen"
please check below JSON response from API.
here is my JSON:
{
    "resultCode": 1,
    "resultData": {
        "Itinary": [
            {
                "ItenaryFor": "Transfer",
                "Icon": "motel",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": "Phi Phi Island, Phuket City Tour",
                "BackgroundImg": ""
            },
            {
                "ItenaryFor": "Sightseen",
                "Icon": "holiday",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": "Phi Phi Island, Phuket City Tour",
                "BackgroundImg": ""
            },
            {
                "ItenaryFor": "Sightseen",
                "Icon": "holiday",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": "Phi Phi Island, Phuket City Tour",
                "BackgroundImg": ""
            },
            {
                "ItenaryFor": "Hotel",
                "Icon": "motel",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": "Phi Phi Island, Phuket City Tour",
                "BackgroundImg": ""
            },
            {
                "ItenaryFor": "Hotel",
                "Icon": "motel",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": "Phi Phi Island, Phuket City Tour",
                "BackgroundImg": ""
            },
            {
                "ItenaryFor": "Hotel",
                "Icon": "motel",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": null,
                "BackgroundImg": null
            },
            {
                "ItenaryFor": "Sightseen",
                "Icon": "holiday",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": "Coral Island",
                "BackgroundImg": ""
            },
            {
                "ItenaryFor": "Hotel",
                "Icon": "motel",
                "Comment": null,
                "Iscustomsave": true,
                "TourDelight": "Coral Island",
                "BackgroundImg": null
            }
        ]
    }
}

Please give me suggestions.

A: you can use Array.sort to achieve this. see docs.
refer below example:

var arr = [{
    "ItenaryFor": "Transfer",
    "Icon": "motel",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": "Phi Phi Island, Phuket City Tour",
    "BackgroundImg": ""
  },
  {
    "ItenaryFor": "Sightseen",
    "Icon": "holiday",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": "Phi Phi Island, Phuket City Tour",
    "BackgroundImg": ""
  },
  {
    "ItenaryFor": "Sightseen",
    "Icon": "holiday",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": "Phi Phi Island, Phuket City Tour",
    "BackgroundImg": ""
  },
  {
    "ItenaryFor": "Hotel",
    "Icon": "motel",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": "Phi Phi Island, Phuket City Tour",
    "BackgroundImg": ""
  },
  {
    "ItenaryFor": "Hotel",
    "Icon": "motel",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": "Phi Phi Island, Phuket City Tour",
    "BackgroundImg": ""
  },
  {
    "ItenaryFor": "Hotel",
    "Icon": "motel",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": null,
    "BackgroundImg": null
  },
  {
    "ItenaryFor": "Sightseen",
    "Icon": "holiday",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": "Coral Island",
    "BackgroundImg": ""
  },
  {
    "ItenaryFor": "Hotel",
    "Icon": "motel",
    "Comment": null,
    "Iscustomsave": true,
    "TourDelight": "Coral Island",
    "BackgroundImg": null
  }
];

arr.sort(function(a,b) {
  if(a.ItenaryFor.indexOf('Sightseen') === 0) {
    return -1;
  } else {
    return 1;
  }
});

console.log(arr);

Plunker demo about implementing it as a Pipe.

A: It's not a good idea to use a pipe for sorting. See the link here: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe
Rather, add code in your component to perform your sort.
Here is an example. This one filters, but you could change it to sort instead.
import { Component, OnInit } from '@angular/core';

import { IProduct } from './product';
import { ProductService } from './product.service';

@Component({
    templateUrl: './product-list.component.html'
})
export class ProductListComponent implements OnInit {

    _listFilter: string;
    get listFilter(): string {
        return this._listFilter;
    }
    set listFilter(value: string) {
        this._listFilter = value;
        this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
    }

    filteredProducts: IProduct[];
    products: IProduct[] = [];

    constructor(private _productService: ProductService) {

    }

    performFilter(filterBy: string): IProduct[] {
        filterBy = filterBy.toLocaleLowerCase();
        return this.products.filter((product: IProduct) =>
              product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
    }

    ngOnInit(): void {
        this._productService.getProducts()
                .subscribe(products => {
                    this.products = products;
                    this.filteredProducts = this.products;
                },
                    error => this.errorMessage = <any>error);
    }
}


text:
Q: Organize date format with PHP there is any way to organize a date echoed from a datepicker from the last page?
Like this:
I recieve in this format: 2013, 06, 24
And i want this format: 24/06/2013
This is possible?

A: You could do it like this...
$date = "2013, 06, 24";
$date = str_replace(", ","-",$date);

$date = date('d/m/Y', strtotime($date));

But you never mention which language you wanna do it in?
You have both php and javascript as tags, so how are we supposed to know how exactly you wanna do it.

A: If you're referring to getting it in that format from the client side, then When you create your datepicker you can do this:
$( ".selector" ).datepicker({ dateFormat: "dd/mm/yy" });

source: jQuery datepicker documentation
if you want to do it server-side in php after you've received the string, you can do:
$datefields = explode(', ', $dateString);
echo $datefields[2] . '/' . $datefields[1] . '/' . $datefields[0];

I used explode() instead of split() because split() is deprecated and we don't need the full power of preg_split() here either.
source: php explode() documentation

A: you could do this using the date-functions that php/js offers or you could go for regular expressions which would be if you are sure you receive a valid format and just want to reformat it:
/(\d{4}), (\d{2}), (\d{2})/ and replace with $3/$2/$1. Would be done in php using preg_replace("/(\d{4}), (\d{2}), (\d{2})/", '$3/$2/$1', "2013, 06, 24");

A: If it's always the format 'yyyy, mm, dd' you can use:
var mydate = '2013, 06, 24'
               .replace(/\s+/g,'')
               .split(',')
               .reverse()
               .join('/'); //=> '24/06/2013'


text:
Q: Weird Indexer Issue Magento 1.9.1.0 all patches.
We have a weird indexing issue. We have all indexers set to "Update on Save"
But we still keep getting "Reindex Required", mostly index product stock status.

*

*I thought that if you have "Update on Save" it reindexes right away, and you would never see "Reindex Required"?

*The second weird thing is when I go into the index_process_event table, the event that has a status of "new" is a very old one, like 2 years old? What is happening here? It almost seems like something is changing old rows in index_process_event to "new"?
My index_event table has 26456 rows and my index_process_event has 2322
I think this is related, we also keep having products disappear from categories. It just happens randomly. One to three products will not show up a couple times a day, when we are busy. So then we reindex or save the product and it comes back.
Do you think truncating the index_process tables would fix this?

A: Based on the exceptions you need to fix those duplicate entries first, usually you can just remove the offending row directly in the DB, take a backup first, though.
So it could be the indexes are failing each time they run so they are always incomplete.
The best way to correlate that failure to the indexer is to run it via CLI if you can. If you have SSH access go to your Magento web root and run something like this -

php shell/indexer.php --reindexall

Then wait for the indexer to run, if one of the exceptions is the problem it will be output during the appropriate index.
It could be a locks issue in var/locks, too, but often they are locked because of some other failure.