text:
Q: android: recycler view adapter I am new to recycler view widget , i want to get my data from my api url and list the data into my recycler view , i have these classes : recyclerAdapter , recyclerView , MainActivity , row .
the data is loaded from api succesfully but the does not set the json string received from the api in the recycler view , and the recycler view is shown white and empty . any body can find the problem in my code ?
MainActivity.java code is :
public class MainActivity extends AppCompatActivity {
    final String member_id = "2";
    final String get_cash_url = "http://famila1.ir/khabgah/get_khabgah_cash.php?member_id=" + member_id;

    private RecyclerView rc;
    private RecyclerView.Adapter adapter;
    private List<recyclerView> cashList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rc = findViewById(R.id.rc);
        rc.setHasFixedSize(true);
        rc.setLayoutManager(new LinearLayoutManager(this));
        cashList = new ArrayList<>();
        loadUrlData();

    }

    private void loadUrlData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                get_cash_url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println(response);
                progressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    JSONArray array = jsonObject.getJSONArray("bedehkariHa");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jo = array.getJSONObject(i);
                        recyclerView temp = new recyclerView(jo.getString("hazine"), jo.getString("tarikh"), jo.getString("tozihat"), jo.getString("member_id"), "kir");
                        cashList.add(temp);
                    }
                    adapter = new recyclerAdapter(cashList, getApplicationContext());
                    rc.setAdapter(adapter);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
                , new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                progressDialog.setMessage("somthing was wrong during runnig app...");
                progressDialog.show();
                System.out.println("error: "+error);
            }
        }
        );
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }
}

recyclerView.java code is :
public class recyclerView {
private String hazine,tarikh,tozihat,madarkharj,harSahm;
public recyclerView(String hazine,String tarikh,String tozihat,String madarkharj,String harSahm ) {
    this.hazine = hazine;
    this.harSahm = harSahm;
    this.madarkharj = madarkharj;
    this.tarikh = tarikh;
    this.tozihat = tozihat;
}
public String getHazine(){return hazine;}
public String getTarikh(){return tarikh;}
public String getTozihat(){return tozihat;}
public String getMadarkharj(){return madarkharj;}
public String getHarSahm(){return harSahm;}

}
public class recyclerAdapter extends RecyclerView.Adapter<recyclerAdapter.ViewHolder>{

public static final String KEY_NAME = "name";
public static final String KEY_LASTNAME = "lastname";
public static final String KEY_IMAGE = "image";
public static final String KEY_HAZINE = "hazine";
public static final String KEY_TARIKH = "date";
public static final String KEY_MADARKHARJ = "member_id";

private List<recyclerView> cashlist;
private Context context;

Recycler adapter class is this :
public recyclerAdapter(List<recyclerView> cashlist, Context context){
    this.cashlist = cashlist;
    this.context = context;

}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.row,viewGroup,false);

    return new recyclerAdapter.ViewHolder(v);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {
    final recyclerView recyclerviews = cashlist.get(position);
    viewHolder.hazine.setText(recyclerviews.getHazine());
    viewHolder.harSahm.setText(recyclerviews.getHarSahm());
    viewHolder.tarikh.setText(recyclerviews.getTarikh());
    viewHolder.tozihat.setText(recyclerviews.getTozihat());

    viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(context, "TEST is Toasted", Toast.LENGTH_SHORT).show();
        }
    });

}

@Override
public int getItemCount() {
    return cashlist.size();
}

// Inside this class, we'll have another class for the ViewHolder thus
public class ViewHolder extends RecyclerView.ViewHolder{

    TextView hazine,harSahm,tozihat,tarikh;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);
        hazine = (TextView) itemView.findViewById(R.id.mablaq_hazine);
        harSahm = (TextView) itemView.findViewById(R.id.bedehkariha_dong);
        tarikh = (TextView) itemView.findViewById(R.id.tarikh_hazine);
        tozihat = (TextView) itemView.findViewById(R.id.babate_hazine);
    }
}

}
and this is row.xml :
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent" android:background="@android:color/white" >

    <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" android:padding="5dp"
                android:background="@android:color/holo_blue_bright" android:layout_marginBottom="5dp"
        >
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:padding="3dp"
                    android:background="@android:color/holo_blue_dark">
                <TextView
                        android:text="سهم شما:"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/tarikh_hazine2"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"
                />
                <TextView
                        android:text="قالب پرداخت"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/bedehkariha_dong"
                        android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"/>
                <TextView
                        android:text="مبلغ کل: "
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/mablaq_hazine2"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"/>
                <TextView
                        android:text="مبلغ کل"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/mablaq_hazine" android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"/>
            </LinearLayout>
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:padding="3dp"
                    android:background="@android:color/holo_blue_dark">
                <TextView
                        android:text="تاریخ:"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/tarikh_hazine22"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"
                />
                <TextView
                        android:text="تاریخ"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/tarikh_hazine" android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"
                        android:inputType="textMultiLine"
                />
            </LinearLayout>
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:padding="3dp"
                    android:background="@android:color/holo_blue_dark">
                <TextView
                        android:text="توضیحات: "
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/babate_hazine2"
                        android:textSize="18sp" android:textColor="@android:color/holo_red_dark"
                        android:textStyle="bold"
                />
                <TextView
                        android:text="هزینه بابت......"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content" android:id="@+id/babate_hazine" android:layout_weight="1"
                        android:textSize="18sp" android:textColor="@android:color/black"
                        android:inputType="textMultiLine"
                        android:gravity="right"/>
            </LinearLayout>
            <LinearLayout
                    android:orientation="horizontal"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" android:layout_marginTop="2dp">
                <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" android:layout_weight="1" android:padding="2dp">
                    <TextView
                            android:text="پرداخت از: "
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none"
                            android:background="@android:color/white" android:gravity="center"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz1" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FF75AD06" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz2" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_green_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz3" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FF75AD06" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz4" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_green_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz5" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#75ad06" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/pardakhtaz6" android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_green_dark" android:padding="2dp"
                    />
                </LinearLayout>
                <LinearLayout
                        android:orientation="vertical"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent" android:layout_weight="1" android:padding="2dp">
                    <TextView
                            android:text="هزینه شریکی با:"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none"
                            android:background="@android:color/white" android:gravity="center"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba1"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FFF10D0D" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba2"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_red_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba3"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FFF10D0D" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba4"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_red_dark" android:padding="2dp"
                    />
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba5"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="#FFF10D0D" android:padding="2dp"/>
                    <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content" android:id="@+id/moshtarak_ba6"
                            android:layout_weight="1"
                            android:textSize="18sp" android:textColor="@android:color/black"
                            android:fadingEdge="none" android:gravity="right"
                            android:background="@android:color/holo_red_dark" android:padding="2dp"
                    />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

A: Parsing Problem first I got.Change
 JSONArray array = jsonObject.getJSONArray("bedehkariHa");

To:
 JSONArray array = jsonObject.getJSONArray("bedehkari_ha");

Then check

A: According to the result from JSON, the key bedehkariHa does not exist and that may cause Parsing Error, a JSONException. So instead of this:
 JSONArray array = jsonObject.getJSONArray("bedehkariHa");

use this to get the JSONArray associated with bedehkari_ha:
 JSONArray array = jsonObject.getJSONArray("bedehkari_ha");

A: I'd firstly look at your general approach.
You seem to be instantiating a Volley request...I bet this isn't the only one in your app?
Make a "NetworkService" singleton that holds application Context and call that as a service layer...rather than calling a new Volley instance for each class you need it!
Here is one I wrote for my apps...I have omitted a lot of the methods and left you with a GetRequest method. You could add the URLEncoding of parameters in the service.
You can call this by simply in an activity/fragment:
 HashMap<String,String> urlParams = new HashMap<>();
        urlParams.put("param1","value1");

        VolleyRequestService.getInstance(this).getJSONObject(urlParams, true, new GetJSONObjectRequestable() {
            @Override
            public void onSuccessfulAPIResponse(JSONObject response) {

            }

            @Override
            public void onFailedAPIResponse(VolleyRequestService.ErrorType errorType, String description) {

            }
        },"https://myendpoint.com/endpoint.php");

And the service:
package devdroidjonno.com.tests.Networking;

import android.content.Context;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class VolleyRequestService {
    private static final String DEBUG = "VolleyRequestService";
    private static final String authCode = "87fe987vwefb987eb9w87wv";
    private static VolleyRequestService ourInstance = null;
    private static RequestQueue requestQueue;

    private VolleyRequestService(Context applicationContext) {
        this.requestQueue = Volley.newRequestQueue(applicationContext);
        Log.d(DEBUG, "Init Volley Service " + this.hashCode());
    }

    public static VolleyRequestService getInstance(Context context) {
        if (ourInstance == null) {
            ourInstance = new VolleyRequestService(context.getApplicationContext());
        }
        return ourInstance;
    }

    // A GET request to an endpoint that returns a JSONObject.
    public void getJSONObject(HashMap<String, String> urlParams, final boolean requiresAuthHeader, final GetJSONObjectRequestable callback, String endpointURL) {
        endpointURL += "?";
        for (Map.Entry mapEntry : urlParams.entrySet()) {
            endpointURL += mapEntry.getKey() + "=" + mapEntry.getValue() + "&";
        }
        Log.d(DEBUG, endpointURL);
        requestQueue.add(new JsonObjectRequest(Request.Method.GET, endpointURL, null, response -> {
            Log.d(DEBUG, response.toString());
            try {
                if (response.has("error")) {
                    callback.onFailedAPIResponse(ErrorType.APIERROR, response.getString("error"));
                } else {
                    callback.onSuccessfulAPIResponse(response);
                }
            } catch (Exception e) {
                callback.onFailedAPIResponse(ErrorType.EXCEPTION, e.getLocalizedMessage());
                e.printStackTrace();
            }
        }, error -> callback.onFailedAPIResponse(ErrorType.VOLLEYERROR, error.getMessage())) {
            @Override
            public Map<String, String> getHeaders() {
                HashMap<String, String> headers = new HashMap<>();
                if (requiresAuthHeader) headers.put("Authorization", authCode);
                return headers;
            }
        });
    }

    public enum ErrorType {
        NOERROR, APIERROR, VOLLEYERROR, AUTHERROR, EXCEPTION
    }

}

And finally the callback...
package devdroidjonno.com.tests.Networking;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public interface GetJSONObjectRequestable {
    void onSuccessfulAPIResponse(JSONObject response) throws JSONException, IOException;

    void onFailedAPIResponse(VolleyRequestService.ErrorType errorType, String description);
}


text:
Q: How to create a default project under Delphi XE7? Related to this question: Should "Library path" point to the source files of packages?
Fabricio Araujo suggested that is not necessary to set the 'search path' for each new project by creating a 'Default Project Option'. How can this be done in Delphi XE7?

A: Prompted by your q, and more for amusement than anything else, I decided to try
writing an IDE-plugin that would provide a way to store some preferred project
settings somewhere and allow you to apply them to the current project.
To use, prepare and save a sample .Ini file containing your preferred settings in the format shown below (it's important to get the project option names right, see below for how to do find them out), then compile the unit below into a new package and install it in the IDE.  Its gui will pop up when you subsequently open a project.
The settings in the .Ini are loaded into a ValueList editor and pressing the
[Return] key in one of the values will apply it to the project.
Interestingly, the names the IDE uses for the Project seetings are the same in XE7
as they are in D7.  Iow, the XE7 IDE uses these internally rather than the names
which appear in the .DProj XML file.  You can get a full list of them by clicking the GetOptions button.
As usual when working with the IDE OTA services, the code has to include
a fair amount of "baggage".
Tested in D7 and XE7.
Sample Ini File:
[settings]
OutputDir=Somewhere
UnitOutputDir=Somewhere else
UnitDir=$(DELPHI)
ObjDir=$(DELPHI)
SrcDir=$(DELPHI)
ResDir=$(DELPHI)

Code:
unit ProjectOptionsXE7u;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls, ToolsAPI, Grids, ValEdit, IniFiles;

type
  TProjectOptionsForm = class(TForm)
    Panel1: TPanel;
    Memo1: TMemo;
    ValueListEditor1: TValueListEditor;
    btnGetOptions: TButton;
    procedure btnGetOptionsClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure ValueListEditor1KeyPress(Sender: TObject; var Key: Char);
  private
    function GetCurrentProject: IOTAProject;
    procedure GetOptionsFromIni;
    procedure UpdateOptionValue;
  public
    Services: IOTAServices;
    ProjectGroup : IOTAProjectGroup;
    Project: IOTAProject;
    Options : IOTAProjectOptions;
    ModServices: IOTAModuleServices;
    Module: IOTAModule;
    NotifierIndex: Integer;
    Ini : TMemIniFile;
    IsSetUp : Boolean;
    SetUpCount : Integer;
    procedure GetProjectOptions;
    procedure SetUp;
  end;

var
  ProjectOptionsForm: TProjectOptionsForm;

procedure Register;

implementation

{$R *.dfm}

type
  TIdeNotifier = class(TNotifierObject, IOTANotifier, IOTAIDENotifier)
  protected
    procedure AfterCompile(Succeeded: Boolean);
    procedure BeforeCompile(const Project: IOTAProject; var Cancel: Boolean);
    procedure FileNotification(NotifyCode: TOTAFileNotification;
      const FileName: string; var Cancel: Boolean);
  end;

procedure Register;
begin
  ProjectOptionsForm:= TProjectOptionsForm.Create(Nil);
  ProjectOptionsForm.Services := BorlandIDEServices as IOTAServices;
  ProjectOptionsForm.NotifierIndex := ProjectOptionsForm.Services.AddNotifier(TIdeNotifier.Create);
end;

procedure CloseDown;
begin
  ProjectOptionsForm.Services.RemoveNotifier(ProjectOptionsForm.NotifierIndex);
  ProjectOptionsForm.Close;
  ProjectOptionsForm.Free;
end;

procedure TIdeNotifier.AfterCompile(Succeeded: Boolean);
begin
end;

procedure TIdeNotifier.BeforeCompile(const Project: IOTAProject; var Cancel: Boolean);
begin
end;

procedure TIdeNotifier.FileNotification(NotifyCode: TOTAFileNotification;
  const FileName: string; var Cancel: Boolean);
begin
  if NotifyCode in [ofnProjectDesktopLoad, ofnActiveProjectChanged]  then begin
    ProjectOptionsForm.Show;
//    ProjectOptionsForm.Memo1.Lines.Add('Got notification');
    ProjectOptionsForm.SetUp;
//    ProjectOptionsForm.Memo1.Lines.Add('after GetProjectOptions');
  end;
end;

procedure TProjectOptionsForm.btnGetOptionsClick(Sender: TObject);
var
  KeyName,
  Value,
  S : String;
  V : Variant;
  i : Integer;
begin
  GetProjectOptions;
  ValueListEditor1.Strings.Clear;
  for i := Low(Options.GetOptionNames) to High(Options.GetOptionNames) do begin
    try
      KeyName := Options.GetOptionNames[i].Name;
      if CompareText(KeyName, 'HeapSize') = 0 then
        NoOp;
      V := Options.Values[KeyName];
      if not VarIsEmpty(V) then
        Value := VarToStr(V)
      else
        Value := '';
      ValueListEditor1.InsertRow(KeyName, Value, True);
    except
      //  Reading some CPP-related settings cause exceptions
      S := '***Error   ' + KeyName; // + ': ' + IntToStr(Options.Values[KeyName].Kind);
      Memo1.Lines.Add(S);
    end;
  end;
end;

procedure TProjectOptionsForm.FormDestroy(Sender: TObject);
begin
  Ini.Free;
end;

procedure TProjectOptionsForm.GetOptionsFromIni;
var
  i : Integer;
  KeyName : String;
  TL : TStringList;
begin
  ValueListEditor1.Strings.Clear;
  TL := TStringList.Create;
  try
    Ini.ReadSection('Settings', TL);
    Assert(TL.Count > 0);
    for i := 0 to TL.Count - 1 do begin
      KeyName := TL[i];
      ValueListEditor1.InsertRow(KeyName, Ini.ReadString('Settings', KeyName, ''), True);
    end;
  finally
    TL.Free;
  end;
end;

procedure TProjectOptionsForm.FormCreate(Sender: TObject);
var
  IniFileName : String;
begin
  IniFileName := 'd:\aaad7\ota\ProjectOptions.Ini'; //  <beware of hard-code path
  Ini := TMemIniFile.Create(IniFileName);
  GetOptionsFromIni;
end;

function TProjectOptionsForm.GetCurrentProject: IOTAProject;
var
  i: Integer;
begin
  Result := nil;
  ModServices := BorlandIDEServices as IOTAModuleServices;
  for i := 0 to ModServices.ModuleCount - 1 do
  begin
    Module := ModServices.Modules[i];
    if Supports(Module, IOTAProjectGroup, ProjectGroup) then begin
      Result := ProjectGroup.ActiveProject;
      Options := Result.ProjectOptions;
      Exit;
    end
    else if Supports(Module, IOTAProject, Project) then
    begin // In the case of unbound packages, return the 1st
      if Result = nil then begin
        Result := Project;
        Options := Result.ProjectOptions;
      end;
    end;
  end;
end;

procedure TProjectOptionsForm.GetProjectOptions;
begin
  Assert(Project <> Nil, 'Project');
  Options := Project.ProjectOptions;
end;

procedure TProjectOptionsForm.SetUp;
begin
  Project := GetCurrentProject;
  GetProjectOptions;
  Inc(SetUpCount);
  Caption := 'Setup done ' + IntToStr(SetUpCount);
  IsSetUp := True;
end;

procedure TProjectOptionsForm.UpdateOptionValue;
var
  Rect : TGridRect;
  S : String;
  KeyName,
  Value : String;
  Row,
  Col : Integer;
begin
  if Options = Nil then
    Exit;
  Rect := ValueListEditor1.Selection;
//  S := 'left: %d top: %d right: %d, bottom: %d';
//  S := Format(S, [Rect.Left, Rect.Top, Rect.Right, Rect.Bottom]);
//  Memo1.Lines.Add(S);
  Row := Rect.Bottom;
  Col := Rect.Left - 1;
  KeyName := ValueListEditor1.Cells[Col, Row];
  Value := ValueListEditor1.Values[KeyName];

  Options.SetOptionValue(KeyName, Value);
  Options.ModifiedState := True;

  Module.Save(False, False);
end;

procedure TProjectOptionsForm.ValueListEditor1KeyPress(Sender: TObject; var
    Key: Char);
begin
  if Key = #13 then
    UpdateOptionValue;
end;

initialization

finalization
  CloseDown;
end.

A:
How this can be done in Delphi XE7?

It cannot. This functionality was removed I'm not sure exactly when, but it has not been present for some considerable time.
What you can do is:

*

*Create a new project.

*Change its settings however you please.

*Save this modified project template to some central location.

*Whenever you make a new project, do so by copying this project template.

You can integrate this process into the IDE by saving your modified project template into the Object Repository. Add a project to the repository with Project | Add to Repository.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove commands from SettingsPane - windows 8.1 In search of how to remove the commands from the SettingsPane in Windows 8.1. I don't see it anywhere in the SettingsPane Class documentation in MSDN
Any clues?

A: Add only needed commands.
In the below code , onCommandsRequested will be fired every time when SettingsPane  is opened . You can check conditions before adding commands.
    SettingsPane.GetForCurrentView().CommandsRequested += onCommandsRequested;

Alos, close and reopen the settings pane If you want to change the command when SettingsPane  is open. I dont think there is other ways to achieve the same

A: I found it! :) We can remove commands like this
void OnCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
{
        args.Request.ApplicationCommands.Clear();
        // or
        args.Request.ApplicationCommands.RemoveAt(0);
}


text:
Q: What happens when someone is blacklisted? Just wanted to find out what happens when someone is blacklisted or has a post-ban. Is it only their login that is blacklisted or also their IP address?

A: This is roughly what happens:

See also: What can I do when getting "We are no longer accepting questions/answers from this account"?


text:
Q: Leaflet with multiple polylines elements leads to huge HTML I'm building a leaflet map on R having multiple layers that are controlled by addLayersControl.  Every layer as the same spatial information, so only the data associated to each polylines changes. The idea is to have a basic map, where the user decide which data field is display.  I succeeded at making the map, however I noticed that the size of the html file produced is huge.
In my actual context, making the map with only one layer leads to a ~20mb file.  However, if I add one field it gets to ~40mb and three layer ~60mb.  So it seems to me that the html produced is loading the same shapefile 3 times instead of simply using one shapefile and linking it a data frame of some sort.
Am I stock with this behavior of leaflet or is there a way to file size inflation in my context?  I may not have programmed my leaflet the better way...
I've made a reproducible example to show the problem.  It uses a small shapefile so the size problem is not dramatic, however the point is the same, which is constantly doubling file size.  Also, the example is lengthy, sorry about that, I could'n find a way to simplify it further.
Preparation:
# loading the libraries
library(sf)
library(leaflet)
library(htmlwidgets)

# preparing the shapefile
nc <- st_read(system.file("gpkg/nc.gpkg", package="sf"), quiet = TRUE) %>%
  st_transform(st_crs(4326))

# preparing the colors (not really important)
pal.area <- colorNumeric(palette = "inferno", domain = range(nc$AREA))
pal.perim <- colorNumeric(palette = "inferno", domain = range(nc$PERIMETER))
pal.cnty <- colorNumeric(palette = "inferno", domain = range(nc$CNTY_))
pal.sid74 <- colorNumeric(palette = "inferno", domain = range(nc$SID74))

Making the leaflet, this section is long, however it's simply 4 leaflet maps created one after another by adding one layer at a time.  It's mostly copy-pasted work:
###
one_layer <- leaflet(data = nc) %>%
  addTiles() %>%
  addPolylines(fillColor = ~pal.area(AREA),
               fill = TRUE,
               opacity = 0.8,
               group = "area") %>%
  addLegend("bottomright",
            pal = pal.area, values = ~AREA,
    opacity = 1, group = "area"
  )
###

###
two_layers <- leaflet(data = nc) %>%
  addTiles() %>%
  addPolylines(fillColor = ~pal.area(AREA),
               fill = TRUE,
               opacity = 0.8,
               group = "area") %>%
  addLegend("bottomright",
            pal = pal.area, values = ~AREA,
            opacity = 1, group = "area") %>%
  addPolylines(fillColor = ~pal.perim(PERIMETER),
               fill = TRUE,
               opacity = 0.8,
               group = "perim") %>%
  addLegend("bottomright",
            pal = pal.perim, values = ~PERIMETER,
            opacity = 1, group = "perim"
  ) %>%
  addLayersControl(
    overlayGroups = c("area", "perim"), position = "bottomleft",
    options = layersControlOptions(collapsed = FALSE)
  )
###

###
three_layers <- leaflet(data = nc) %>%
  addTiles() %>%
  addPolylines(fillColor = ~pal.area(AREA),
               fill = TRUE,
               opacity = 0.8,
               group = "area") %>%
  addLegend("bottomright",
            pal = pal.area, values = ~AREA,
            opacity = 1, group = "area") %>%
  addPolylines(fillColor = ~pal.perim(PERIMETER),
               fill = TRUE,
               opacity = 0.8,
               group = "perim") %>%
  addLegend("bottomright",
            pal = pal.perim, values = ~PERIMETER,
            opacity = 1, group = "perim"
  ) %>%
  addPolylines(fillColor = ~pal.cnty(CNTY_),
               fill = TRUE,
               opacity = 0.8,
               group = "cnty") %>%
  addLegend("bottomright",
            pal = pal.cnty, values = ~CNTY_,
            opacity = 1, group = "cnty"
  ) %>%
  addLayersControl(
    overlayGroups = c("area", "perim", "cnty"), position = "bottomleft",
    options = layersControlOptions(collapsed = FALSE)
  ) %>%
  hideGroup(c("perim","cnty"))
###

###
four_layers <- leaflet(data = nc) %>%
  addTiles() %>%
  addPolylines(fillColor = ~pal.area(AREA),
               fill = TRUE,
               opacity = 0.8,
               group = "area") %>%
  addLegend("bottomright",
            pal = pal.area, values = ~AREA,
            opacity = 1, group = "area") %>%
  addPolylines(fillColor = ~pal.perim(PERIMETER),
               fill = TRUE,
               opacity = 0.8,
               group = "perim") %>%
  addLegend("bottomright",
            pal = pal.perim, values = ~PERIMETER,
            opacity = 1, group = "perim"
  ) %>%
  addPolylines(fillColor = ~pal.cnty(CNTY_),
               fill = TRUE,
               opacity = 0.8,
               group = "cnty") %>%
  addLegend("bottomright",
            pal = pal.cnty, values = ~CNTY_,
            opacity = 1, group = "cnty"
  ) %>%
  addPolylines(fillColor = ~pal.sid74(SID74),
               fill = TRUE,
               opacity = 0.8,
               group = "sid74") %>%
  addLegend("bottomright",
            pal = pal.sid74, values = ~SID74,
            opacity = 1, group = "sid74"
  ) %>%
  addLayersControl(
    overlayGroups = c("area", "perim", "cnty", "sid74"), position = "bottomleft",
    options = layersControlOptions(collapsed = FALSE)
  ) %>%
  hideGroup(c("perim","cnty", "sid74"))
###

Then, you get 4 objects (maps)  we can compare their size directly in R:
object.size(one_layer)
301864 bytes
object.size(two_layers)
531144 bytes
object.size(three_layers)
681872 bytes
object.size(four_layers)
828616 bytes

The size increase is constant and way higher that what we would expect if the only the data was added instead of all the spatial info.  As a comparison, the initial shape which has 15 fields is of size:
object.size(nc)
135360 bytes

If we save the maps to HTML, the problem is even more visible:
saveWidget(one_layer, paste0(getwd(),"/temp_data/temp/one_layer.html"), selfcontained = F)
saveWidget(two_layers, paste0(getwd(),"/temp_data/temp/two_layers.html"), selfcontained = F)
saveWidget(three_layers, paste0(getwd(),"/temp_data/temp/three_layers.html"), selfcontained = F)
saveWidget(four_layers, paste0(getwd(),"/temp_data/temp/four_layers.html"), selfcontained = F)

file.info(list.files("temp_data/temp", pattern = ".html$", full.names = T))$size[c(2,4,3,1)] %>%
  setNames(c("One Layer", "Two Layers", "Three Layers", "Four Layers")) %>%
  barplot(ylab="size in Bytes")

It's clearly doubling in size.
So, to summarize, is there a way to get leaflet to not reproduced the spatial information when adding multiple fields of data to the same map?


text:
Q: Implicit would allows for eliding "s" of third person conjugation? I'm on a pinch here:

Then when a request comes, the server can compare the version number
  present in the digest with the current version of the site, and only
  push assets that have changed between the two versions.

I think that I should write "push" instead of "pushes", because of the can auxiliar that I used before. Am I right? What is the precise rule in this case?

A:
The server can [do stuff], and only push assets [blah].

or

The server can [do stuff], and only pushes assets [blah].

Both are fine as, in the first, "only push" implies "can only push" or "will only push".
If you want to avoid ambiguity you can add the "can" or "will" into your sentence but I had no problem reading it as it is.


text:
Q: Justification for new theories of Particle Physics and General Relativity In reference to arxiv:1212.4893v3 and arxiv:1206.5078v2 papers of Ma and Wang, they have proposed new theories in particle physics, the weakton model where quarks and leptons are formed using these weaktons; modified Einstein's field equations taking care of Dark matter and Energy.
Are these really major breakthroughs as they apparently seem to be, with proper experimental evidences of their accuracy ? Or are they yet to be verified ? What does the Physics community think of these ? I am curious.

A: I am an experimental physicists, and the model in the first paper has not reached the level of experimental predictions, for LHC results. In fact except for the link you give the search at the CERN document server gives nothing, and the word "weakton" does not yield discussions or appraisals. So the experimental physics community is overlooking this, even though some people at the LHC look at composite models., look at paragraph 4.1.
From what I see of the submission history it has not been peer reviewed to appear in a standard journal although it is a year since it is in the archive.
Lets see if a theoretical physicist has a response to this question for the particle paper.
Edit after comment
Now for the new gravitational theory paper, I found an article popularizing it,

"Most importantly, this new energy and the new field equations offer a unified theory for both dark energy and dark matter, which until now have been considered as two totally different beasts sharing only 'dark' in name," he said. "Both dark matter and dark energy can now be represented by the sum of the new scalar potential energy density and the coupling energy between the energy-momentum tensor and the scalar potential field."
The negative part of this sum represents the dark matter, which produces attraction, and the positive part represents the dark energy, which drives the acceleration of expanding galaxies, he said.
"In a nutshell, we believe that new gravity theory will change our view on energy, gravitational interactions, and the structure and formation of our universe," Wang(an author) said.
Kevin Zumbrun, chair of the Department of Mathematics at IU Bloomington, said the new unified theory looked sound in principle.
"It is speculative at the cosmological level, since one must match with experiment, but the math is solid," he said. "It's a new and elegant angle on things, and if this does match experiment, it is a huge discovery. Quite exciting!"
Wang (an author) said the new field equations also lead to a modified Newtonian gravitational force formula, which shows that dark matter plays a more important role in a galactic scale at about 1,000 to 100,000 light years, but is less important in the larger scale, where dark energy will be significant (more than 10 million light years).
"This unified theory is consistent with general characterizations of dark energy and dark matter, and further tests of the theory up to measured precisions of cosmic observations are certainly crucial for an eventual validation of the theory," Wang added.


text:
Q: using PPP without TCP/IP I'm using a PPP to communicate with a device. So far what I have been doing is instantiating PPP on my machine (Fedora 29) and on the device (Yocto Linux). Then I open a TCP/UDP socket and communicate with the device. My serial link (which is why I use PPP) has low baud rate, 4800 to be exact. I cannot change it, it is a project requirement. I've been doing some reading about PPP and as far as I understand I can't just instantiate it and use it raw. I'm have to use TCP/IP/UDP. Am I correct? In other words once I have a PPP connection the only way to use is to open a socket (UDP or TCP) and talk to the device through it. I can't just create my application level packet and tell PPP to send it, I have to go through TCP/IP layer (transport layer).

A: PPP can run protocols other than IP; the most common is of course IPv6. But numerous others have been (and maybe still are) run over PPP. Wikipedia even has a list of protocols that run over PPP, though I'm not sure how many work on Linux.
Also — the reason you run PPP over a serial link is because you want to run a higher-level protocol like IP. If you want to avoid that overhead, just use the serial link directly. Serial links don't require PPP; you can send raw binary data over RS232 using whatever application-specific protocol you'd like.


text:
Q: How to fix Valueerror in python, scaling in machine learning? I am learning machine learning. while learning the KMN algorithm scaling of data was required. when I applied it, it gave me value error.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv(r'C:\Users\admin\Documents\milemarkers.csv')
df.head()
->
OBJECTID    REF_PT_ID   HWY     REF_PT_NUM  ROUTE_ID_RIMS
0   10060   52.000  14  52.000000   192
1   10061   54.167  29  54.167000   14
2   10062   122.000     94  122.000000  15
3   10063   0.000   48  0.000000    229
4   10064   196.014     29  196.014008  14

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(df)
scaled_features = scaler.transform(df)
df_feat = pd.DataFrame(scaled_features,columns = df.columns[:-1])

ValueError: Shape of passed values is (9738, 5), indices imply (9738, 4)

A: isnt it just bcs of you ignoring the last column? it's obvious by using [:-1] you just make it (9738,4)
the correct form would be
df_feat = pd.DataFrame(scaled_features,columns = df.columns)

A: I don't think you were supposed to scale the OBJECTID column
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()

Select the features and scale them
features = df.iloc[:,1:]
scaler.fit(features)
scaled_features = scaler.transform(features)
df_scaled = pd.DataFrame(data=scaled_features,columns=df.columns[1:])

>>> scaler.mean_
array([84.8362   , 42.8      , 84.8362016, 92.8      ])
>>> scaler.scale_    #std
array([67.76082634, 27.78056875, 67.76082897, 96.81198273])

Add the columns from the original dataframe that weren't scaled.
missing = df.columns.difference(df_scaled.columns)
df_scaled[missing] = df[missing]
df_scaled = df_scaled.reindex(columns=df.columns)    #re-order the columns

>>> df_scaled
   OBJECTID  REF_PT_ID       HWY  REF_PT_NUM  ROUTE_ID_RIMS
0     10060  -0.484590 -1.036696   -0.484590       1.024667
1     10061  -0.452610 -0.496750   -0.452610      -0.813949
2     10062   0.548456  1.843015    0.548455      -0.803620
3     10063  -1.251995  0.187181   -1.251995       1.406851
4     10064   1.640739 -0.496750    1.640739      -0.813949

DATA
data = '''{"OBJECTID":{"0":10060,"1":10061,"2":10062,"3":10063,"4":10064},
           "REF_PT_ID":{"0":52.0,"1":54.167,"2":122.0,"3":0.0,"4":196.014},
           "HWY":{"0":14,"1":29,"2":94,"3":48,"4":29},
           "REF_PT_NUM":{"0":52.0,"1":54.167,"2":122.0,"3":0.0,"4":196.014008},
           "ROUTE_ID_RIMS":{"0":192,"1":14,"2":15,"3":229,"4":14}}'''
df = pd.read_json(data)


text:
Q: Moving incremental project folders to Git as commits I have an archaic source code management system at the moment that I'd like to move to Git. I have multiple copies of the same project folder; each time I complete a release/new feature I copy the latest folder, increment the name and start working on that. It's bad, but I've been the only developer so it works. I'd like to move the project over to Git with each folder being an individual commit, but have no idea where to start. Any help would be appreciated!

A: Here is the only way I can think to do this - it may take a bit of time...
First, initialize a git directory. You do this by (assuming unix/mac os) changing to the desired directory (cd <dir_path>) and running git init from the terminal. Here is a reference.
Next copy all the contents of the version #1 folder to the git directory. Once you have done this run git .add from the terminal (this should stage everything in the git directory for a commit). Now you are ready to commit your code: git commit -m 'ver 1.0 commit message'.
Next delete all the contents (except the .git folder!) from your git directory and then copy in all the contents of the version #2 folder. Then run your add and commit commands again. Repeat until you are on your current version.
Once you have done this I recommend setting up some sort of remote repository to push your project to. GitHub and BitBucket are both really good!
Hope this helps.


text:
Q: Separation of Interstitial load from UI thread I created a simple android game and decided to put interstitial ads. My code(I'm using MoPub ad SDK, implementation is similar to admob):
private void loadMoPubInterstitial () {

    moPubInterstitialView.load();
}

and I call this from main activity's onCreate() method. The Interstitials are showing but it causes heavy load to UI thread. Console shows warning that some 350 frames are dropped and that the application is doing too many work on main thread. The game is really lagging in devices. When I commented the line
moPubInterstitialView.load();

the warning is removed and the game is running smoothly on device. So I decided to move the interstitial loading process to another thread. This was my code:
   private void loadMoPubInterstitial () {

    new Thread(new Runnable() {
        public void run() {
            moPubInterstitialView.load();
        }
    }).start();
}

But this time, the interstitials are not showing. The check to decide whether the interstitials are ready or not:
moPubInterstitialView.isReady()

returns false always.
What could be the reason?

A: I am not sure, but i think you are checking the moPubInterstitialView before thread is finish doing the load work, just try to check the  moPubInterstitialView.isReady() once your thread is finished doing all the tasks.. I tried the below sample and it work for me.
boolean flag= false;
                temptest ="before change" ;
              Thread thread= new Thread(new Runnable() {
                   @Override
                   public void run() {
                       temptest=" text changed";
                        flag= true;
                   }
               });

                thread.start();

                if(flag)
                {
                    System.out.println(temptest);

                }


text:
Q: What method within view is notified when view is displayed on ui I'm trying to create a custom surfaceview where every time the view is on the screen the view will start playing a video on its own. I was wondering what method within View is notified when a view is displayed on the UI and seen by the user. I'm using a viewpager so the SurfaceCreated doesn't work because views are created before they are displayed on the screen.

A: How to start a video automatically in a view pager when it comes on the screen
This was the underlying problem. The OP, wisely, wanted to try and isolate the point where it, in a sense "comes on to the screen". Problem is that this can mean many things:
When I first heard the question, I thought a good case would be onAttachedToWindow - see the docs. For people reading this question based on its original title, this is what you want.
The view is inflated and created in the Activity's onCreate in most cases (e.g. if you've used setContentView).
The OP had had no luck with surfaceCreated callbacks either. So we considered in the comments above whether the OP would be interested in the three draw stages layout, measure and draw. There are two stages to actually "putting a view on the screen" in android - the measuring, and the layout pass- see here.
Problem would be that it turned out that the OP was animating his view onto the screen, so the question became how do you tell when a view "arrives" on the screen after animation.
The important point is: you actually wanted to detect a stage much much later in the drawing process, which is understandable! Animation works by many calls to invalidate which in turn require many draws for that view's Canvas - so the stage at which you want to play the video is by no means when the view is first displayed in the UI.
Solution for this particular scenario.
Use animation listeners on your ViewAnimator instances (e.g. ViewPager). To not have to bother with them in teh activity, I would roll your own view, and then use the Adapter type patterns Android is so fond of to manage constantly changing data:
a very hastily written implementation would be:
public class VideoStartingViewFliper extends ViewFlipper {
private final Animation fromRight;
private final Animation toLeft;
private final Animation fromLeft;
private final Animation toRight;
private VideoViewAdapter mAdapter;

public VideoStartingViewFliper(final Context context, final AttributeSet attrs) {
    super(context, attrs);
    fromRight = new YourChoiceOfAnimation();
    fromRight.setAnimationListener(videoStartingAnimationListener);

    toLeft = new YourChoiceOfAnimation();
    toLeft.setAnimationListener(videoStartingAnimationListener);

    fromLeft = new YourChoiceOfAnimation();
    fromLeft.setAnimationListener(videoStartingAnimationListener);

    toRight = new YourChoiceOfAnimation();
    toRight.setAnimationListener(videoStartingAnimationListener);
}

static interface VideoViewAdapter {

    public String getVideoPath(int childId);

}

public void setVideoViewAdapter(final VideoViewAdapter adapter) {
    mAdapter = adapter;
}

// or even call this showNextVideo and don't override!
@Override
public void showNext() {
    setInAnimation(fromRight);
    setOutAnimation(toLeft);
    super.showNext();
}

@Override
public void showPrevious() {
    setInAnimation(fromLeft);
    setOutAnimation(toRight);
    super.showPrevious();

}

private final AnimationListener videoStartingAnimationListener = new AnimationListener() {

    @Override
    public void onAnimationStart(final Animation animation) {
        final VideoView video = ((VideoView) getCurrentView());
        video.stopPlayback();
    }

    @Override
    public void onAnimationRepeat(final Animation animation) {

    }

    @Override
    public void onAnimationEnd(final Animation animation) {
        final VideoView video = ((VideoView) getCurrentView());
        // check null here!
        video.setVideoPath(mAdapter.getVideoPath(getCurrentView().getId()));
        video.start();
    }
};
}

Hope this helps.


text:
Q: C# hmac hashing function converting to PHP I am working on a rest call to an asp.net web service and was provided sample code in C#. I am having trouble converting the following function
 public static string ComputeHash(string hashedPassword, string message)
        {
            var key = Encoding.UTF8.GetBytes(hashedPassword.ToUpper());
            string hashString;

            using (var hmac = new HMACSHA256(key))
            {
                var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
                hashString = Convert.ToBase64String(hash);
            }

            return hashString;
        }

So far this is the draft php equivalent, is there anything specific I should be taking into account when converting between the two? Ignore any formatting am just trying to keep variable names the same for now for sanity. I can't seem to get these to come out to be the same.
function ComputeHash($hashedPassword, $message)
{
$key = utf8_encode(strtoupper($hashedPassword));
$hashString=hash_hmac('sha256',utf8_encode($message),$key,True);
$hashString = base64_encode($hashString);
return $hashString;
        }

EDIT
Thanks to comments below I am able to get both functions doing the same.
Now the issue I have is around the input message
In C# this comes out like this
"GET\n03 August 2022 14:57:27.569500\n/api/member\nuserName=tom.woodforde@redox-software.co.uk";
If I feed the same into the function below the output is different.
This is how the function is built in C# to generate the message

private const String _newLineChar = "\n";
 private static String CreateMessage(String method, String dateUTC, String apiModule, String data)
        {
            return method + _newLineChar + dateUTC + _newLineChar + apiModule + _newLineChar + data;
        }

In PHP this is my equivalent
function CreateMessage($method, $dateUTC, $apiModule, $data){
            $newLineChar = "\\n";
            $message= $method.$newLineChar.$dateUTC.$newLineChar.$apiModule.$newLineChar.$data;
            return $message;
        }

I can feed in the exact same string but get a different result from the encryption and I am assuming it must be because of \n


text:
Q: How do you find the first element of a path? I just downloaded Python 3.4 and I'm wondering how you would go about finding the first directory of a relative path?  I.e. given the path a/b/c/d I would like to print a.
The closest I've gotten is:
from pathlib import Path
print(list(Path('a/b/c/d').parents)[-2])

or
p = Path('a/b/c/d')
print(p.parents[len(p.parents) - 2])

in both cases the -2 part is a bit magical.  I've read the docs and the PEP, and haven't found any better way.. did I miss something obvious?

A: Path.parts is what you need.
p = Path("a/b/c/d")
print(p.parts[0])

A: Use parts attribute:
>>> from pathlib import Path
>>> Path('a/b/c/d').parts
('a', 'b', 'c', 'd')
>>> Path('a/b/c/d').parts[0]
'a'

A: From the documentation, parents gives you an immutable sequence providing access to the logical ancestors of the path; the last element of that sequence would be the logical root, and the second to last element would then be the first directory in the path, which is what you're looking for. That is why you need to use the p.parents[len(p.parents)-2] shortcut ('-2' is for the 'second to last' element of a list).
Note that parents always gives you full formed paths. If you only want the directory name you might want to use p.parts instead. In that case the first element is the logical root, so you'd want p.parts[1].


text:
Q: Php curl with proxy response 502 I am getting 502 as response from a specific site while scrapping, it works with other sites and without proxy works too, can anyone help ?
function doo ( $proxyip, $port, $auth, $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING       => "",
        CURLOPT_USERAGENT      => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36", // tell yourself i am this
        CURLOPT_AUTOREFERER    => true,
        CURLOPT_CONNECTTIMEOUT => 120,
        CURLOPT_TIMEOUT        => 120,
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_PROXY          => $proxyip,
        CURLOPT_PROXYPORT      => $port,
        CURLOPT_PROXYUSERPWD   => $auth,
        CURLOPT_HTTPPROXYTUNNEL => 1,
        CURLOPT_PROXYTYPE => 'HTTP'
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header = $content;
    return $header;
}

Exact Error:
Failure when receiving data from the peer: Received HTTP code 502 from proxy after CONNECT


text:
Q: shuffle memory pool to be free : SPARK with Java i want to join two list (NoHeaderIndexed and NoFirstIndexed) by the key likue this :
    final  Broadcast<JavaPairRDD<Long, Tuple2<String, String>>> c = ctx.broadcast(noHeaderIndexed);
    JavaPairRDD<Tuple2<Tuple2<String, String>, Long>, Tuple2<Tuple2<String, String>, Long>> rs = noFirstIndexed.mapToPair(new PairFunction<Tuple2<Long, Tuple2<String, String>>, Tuple2<Tuple2<String, String>, Long>, Tuple2<Tuple2<String, String>, Long>>() {
        @Override
        public Tuple2<Tuple2<Tuple2<String, String>, Long>, Tuple2<Tuple2<String, String>, Long>> call(Tuple2<Long, Tuple2<String, String>> longTuple2Tuple2) throws Exception {
            String s1 = "";
            if (c.value().lookup(longTuple2Tuple2._1).get(0)._1 != null)
                s1 = c.value().lookup(longTuple2Tuple2._1).get(0)._1;

            String s2 = "";
            if (c.value().lookup(longTuple2Tuple2._1).get(0)._2 != null)
                s2 = c.value().lookup(longTuple2Tuple2._1).get(0)._2;
            return new Tuple2<Tuple2<Tuple2<String, String>, Long>, Tuple2<Tuple2<String, String>, Long>>(new Tuple2<Tuple2<String, String>, Long>(new Tuple2<String, String>(longTuple2Tuple2._2._1,longTuple2Tuple2._2._2),longTuple2Tuple2._1),new Tuple2<Tuple2<String, String>, Long>(new Tuple2<String, String>(s1,s2),longTuple2Tuple2._1 ) );
        }
    });

    //writeResult(rs, "rs.txt");
    rs.coalesce(1,true).saveAsTextFile(path+ "rs");

But when i try to execute it, it display this :
INFO ShuffleMemoryManager: Thread 61 waiting for at least 1/2N of shuffle memory pool to be free

And it doesn't terminate the execution. Could you please explain to me the problem and how can i fix it.
Thank you in advance.

A: Here in this command
rs.coalesce(1,true).saveAsTextFile(path+ "rs");
you are making only one partition so that all data will come to one node. you need increase the number of partitions
Try this depends on your data size
rs.coalesce(10,true).saveAsTextFile(path+ "rs");


text:
Q: How to avoid AC in cheap DC charger I bought a cheap DC charger a couple of days back and I have been using it to charge my headphones and other small electronics.
I recently noticed that there is small amount of AC, less than 1V, coming from the DC charger. It shoots up to more than 1V AC when the switch is off. I tested my other branded chargers, and they all had less than .5V AC in them when I measured using my multimeter.
I am not an expert in electronics and it doesn't make any sense to me why the DC charger has AC in its output.

*

*Does anyone know why this happens?

*Is this bad for devices/ batteries?

*Is there any circuit we can use to remove this AC from DC chargers?

A: *

*It happens because of the cheapest circuit possible, too little bypassing, sometimes too much stress for the components (some parts may be operating around limits), pretty much if you just try to sketch a charging circuit, you get a cheap charger. All those thermal compensation stuff and noise filtering is extra cost and extra brainwork.

*Yes, it's bad for devices. Overshoots in particular, but constant significant noise will reduce lifetime of the circuits that are charged with this device. In fact, you never know what will be harmed an what won't.

*Removing AC from DC is one of the main purpose of capacitors. You put a capacitor between power line and ground:
First of all, determine noise frequency (estimate). Decade is enough, you only need to understand if it's 100Hz or 1kHz or 10kHz or whatever it is. You could then choose the correct bypass cap which will be best for filtering out the undesired frequencies.
Look at this chart:

Of course, it's only estimate, but it's a good starting point.
You want to have minimum resistance at your noise's frequency, which will mean, that the noise will go through the capacitor to the ground, while the rest of the frequencies stay untouched (not literally, you see the graph, but you get my point). Nothing stops you from using 2-3 caps of very different values (very small one like 1nF, 1uF and some 68uF electrolytic against low frequency noise, this is just an example, but you can give it a try, such a set covers wide spectrum of frequencies to filter out). Of course, since you can measure the noise, I assume you have scope, so you can always just try stuff and see what happens and how much it helps. To put it simple, proper bypassing should make it a lot better.
You can go with cheap disk ceramic caps. Even those ebay sets will do, and they should be just fine at 5V, don't know if they don't explode with 12V+, but 5V no problem.
Another small addition: a 5.1V zener from power line to ground (reversed, anode(+) on the ground side) will ensure you don't have dangerous overshoots, it will clip any voltage above 5.1, but if you bypass it well, you won't really need it (again, the scope should tell you)


text:
Q: Fabric executing command on remote server doesn't work I want use fabric in python, to execute command on remote server.
I wrote these:
from fabric.api import *
from fabric.tasks import execute
def do_some_thing():
    run("ls -lh")
if __name__ == '__main__':
    execute(do_some_thing,hosts=['root@10.18.103.102'])

but, it doesn't work and make me login..
It's the output:
➜  ~  python test.py
[root@10.18.103.102] Executing task 'do_some_thing'
[root@10.18.103.102] run: ls -lh
[root@10.18.103.102] out: root@svn:~#
[root@10.18.103.102] out: root@svn:~#

A: Make use of the env variable -
from fabric.api import *
from fabric.contrib.files import *

def myserver():
    env.hosts = ['10.18.103.102']
    env.user = 'root'
    # if you have key based authentication, uncomment and point to private key
    # env.key_filename = '~/.ssh/id_rsa'
    # if you have password based authentication
    env.password = 'ThEpAsAwOrd'

def ls():
    run('ls -al')

Now save these in a file call fabfile.py and execute (on the same directory) -
$ fab myserver ls

Fabric will execute both the functions one after another. So when it executes ls() it'll have the server details in env.


text:
Q: Trouble Making A simple AI I am currently trying to make a tic-tac-toe game where the pc randomly choses a number from an array  and, according to the number, it chooses a button and changes it's text property. How would I make it not choose a button that already has a text property? Here is my code:
   Dim AIChoice As Integer
   AIChoice = AIChoic.Next(0, AI.Length - 1)

   If AI.GetValue(AIChoice) = 1 And Button1.Text = "" Then
       Button1.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 2 And Button2.Text = "" Then
       Button2.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 3 And Button3.Text = "" Then
       Button3.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 4 And Button4.Text = "" Then
       Button4.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 5 And Button5.Text = "" Then
       Button5.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 6 And Button6.Text = "" Then
       Button6.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 7 And Button7.Text = "" Then
       Button7.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 8 And Button8.Text = "" Then
       Button8.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)
   ElseIf AI.GetValue(AIChoice) = 9 And Button9.Text = "" Then
       Button9.Text = "O"
       AIChoice = AIChoic.Next(0, AI.Length)

I Also Have an array earlier with the numbers 1-9 on it.

A: This should function identically to the code you posted, except that it will keep picking a random number until it finds a button with an empty string as its Text. Note that it would be better to create the buttons as an array rather create an additional array to refer to them, but this is the simplest fix and I don't think you'll run into any problems that the other way would avoid.
Dim AllButtons() As Button = {Button1, Button2, Button3, Button4, Button5, Button6, Button7, Button8, Button9}
Dim AIChoice As Integer
Do
    AIChoice = AIChoic.Next(0, AI.Length - 1)
Loop Until AllButtons(AI.GetValue(AIChoice) - 1).Text = ""
AllButtons(AI.GetValue(AIChoice) - 1).Text = "O"
AIChoice = AIChoic.Next(0, AI.Length)


text:
Q: How to get the file and upload it using Node.js and Postman I need one help. I am sending file using Postman and I need to upload it inside required folder using Node.js. I am explaining my code below.

server.js:

var express=require('express');
var morgan = require('morgan');
var http=require('http');
var bodyParser= require('body-parser');
var methodOverride = require('method-override');
var mongo = require('mongojs');
var session = require('express-session');
var app=module.exports=express();
var server=http.Server(app);
var port=8889;
var api=require('./api/api.js');
app.use(express.static(__dirname + '/public'));     // set the static files location /public/img will be /img for users
app.use(morgan('dev'));                     // log every request to the console
app.use(bodyParser.urlencoded({ extended: false,limit: '5mb' }))    // parse application/x-www-form-urlencoded
app.use(bodyParser.json({limit: '5mb'}))    // parse application/json
app.use(methodOverride());
app.post('/upload',api.upload);
server.listen(port);
console.log("Server is running on the port"+port);

api.js:

var multer  = require('multer');
var storage =multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './../uploads');
  },
  filename: function (req, file, callback) {
    callback(null, Date.now()+'-'+file.originalname);
  }
});
var upload = multer({ storage: storage});
exports.upload=function(req,res){
}

Actually I am posting the file using postman whose screen shot is given below.

Here my requirement is the file will upload into the required folder i.e-uploads and the uploaded file name will return as response to user. Please help me.

A: You haven't actually used the multer here. You have created upload using multer but you did not use it.
Try the following code:
app.post('/upload', upload.single('file'), function (req, res, next) {
     // req.file is the `file` file
     // req.body will hold the text fields, if there were any
})

where upload will be the var upload = multer({ storage: storage}); variable.


text:
Q: Extensions installed on chrome browser missing when chrome browser instance is opened with Selenium chromeDriver I have a peculiar problem here.
When I open chromeBrowser via chromeDriver the extensions that were previously installed are missing.Also the apps extension is getting deleted from extensions folder(AppData\Local\Google\Chrome\User Data\Default\Extensions).
Now when I open the chrome browser manually, the extension appear on the browser , also the apps folder in extensions folder (AppData\Local\Google\Chrome\User Data\Default\Extensions) no w appears back.
Below is version of chromedriver & browser.
chromedriver version :26.0.1383.0
chromebrowser : 26.0.1410.64

A: You have to install each extension you want to use.  In Selenium2 C# API it looks like this
var options = new ChromeOptions();
options.AddExtension(Path.GetFullPath("local/path/to/extension.crx"));
var driver = new ChromeDriver(options);

and the extension will be in the browser.  Reference for java can be found here. See this question for how to obtain the .crx file for your extension from the chrome store.

A: this answer can be found here https://sites.google.com/a/chromium.org/chromedriver/extensions.
Chrome extensions can be either packed or unpacked.  Packed extensions are a single file with a .crx extension.  Unpacked extensions are a directory containing the extension, including a manifest.json file.
To pack an unpacked extension, use the Pack button in chrome://extensions or use Chrome: "chrome.exe --pack-extension=C:\path\to\unpacked\extension --pack-extension-key=C:\myext.pem".  See the extensions docs for other ways to do this that are more automation friendly.  To unpack a packed extension, just unzip the file (you may need to rename the file from .crx to .zip for your zip utility to recognize it).
Installing extensions via ChromeDriver
Packed (.crx file)
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

Unpacked (directory)
ChromeOptions options = new ChromeOptions();
options.addArguments("load-extension=/path/to/extension");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
ChromeDriver driver = new ChromeDriver(capabilities);

A: If you want to have the extension available during testing you need to start chrome with a profile that defines this extension or give the extension as desired property to the webdriver. Usually, when you start chrome via webdriver the chrome starts with a fresh profile each time.
so if you want to load an extension in the test chrome, do this:
 DesiredCapabilities capabilities = DesiredCapabilities.chrome();
 capabilities.setCapability("chrome.switches",
    Arrays.asList("--load-extension=/path/to/extension/directory"));
 WebDriver driver = new ChromeDriver(capabilities);

More info about the matter can be found here

A: ChromeOptions options = new ChromeOptions();
 options.AddAdditionalCapability("excludeSwitches", new object[] { "disable-default-apps" });
 IWebDriver drv = new ChromeDriver(options);
available from webdriver .net bindings 2.40 onwards.


text:
Q: CSS3 & GIF Loading Circle
Possible Duplicate:
CSS3 Continous Rotate Animation (Just like a loading sundial)

I have this simple GIF loading circle. Is it possible something like this can be coded with just CSS3? Any help is much appreciated.
jsFiddle

A: HTML:

CSS:
@-webkit-keyframes rotate {
    from { -webkit-transform: rotate(0deg) }
    to { -webkit-transform: rotate(360deg) }
}
@-moz-keyframes rotate {
    from { -moz-transform: rotate(0deg) }
    to { -moz-transform: rotate(360deg) }
}
@-o-keyframes rotate {
    from { -o-transform: rotate(0deg) }
    to { -o-transform: rotate(180deg) }
}
@-ms-keyframes rotate {
    from { -ms-transform: rotate(0deg) }
    to { -ms-transform: rotate(360deg) }
}
.arc-hider {
    width: 30px;
    height: 30px;
    border-radius: 60px;
    border: 6px solid #36669F;
    position: absolute;
    left: 45%;
    z-index: 5;
    clip: rect(0px 21px 21px 0px);
    -webkit-animation: rotate 2s linear infinite 0s;-moz-animation: rotate 2s linear infinite 0s;-o-animation: rotate 2s linear infinite 0s;-ms-animation: rotate 2s linear infinite 0s;
    animation: rotate 2s linear infinite 0s;
}

Should do the trick
Live Demo | Source


text:
Q: SSD in external usb 3.0 case not recognized
*

*Mac mini 2009

*Intel SSD 330 60 Gb

*IcyBox IB-AC603a USB 3.0

I can't see the SSD in Desktop nor in Disk Utility. I don't know what to do as it is said to be USB 2.0 friendly in case's documentation.

A: USB 2.0 doesn't provide enough power for the SSD in an enclosure unless you have a case that has a plug where you may add more power (and that's going to be hard to find because USB 3.0 2.5" enclosures normally do not require such extra power and, therefore, will not have the 5v power port).
Or try a powered USB hub between the case and the Mac. That may work.


text:
Q: Alternative software to Freedom and/or Anti-Social? Freedom:
http://macfreedom.com/
Anti-Social:
http://anti-social.cc/
Simply put: Where can I find an alternative software to either-or/both these apps?
Note: Part of the appeal of these apps is allowing the user to explicitly make it extra difficult to re-enable these services. Unplugging the network cable might seem to achieve the same results from an glance, but the added difficulty in re-enabling those services is what makes these apps valuable.

A: Self Control  (Download Link)
From an OMG!Ubuntu! article

Self Control allows you to 'block access to incoming and/or outgoing mail servers and websites' for a specified amount of time.

A: Firstly make sure you only have one web browser (i.e Firefox) and then Install Leechblock addon

A: Anything you do can be undone if the user your trying to target has sudo rights (administrative access). So your first priority is to make sure you secure your machines in such a way as to prevent sudo access.
Once you have this set up correctly, you can move to installing packages that control access via time based rules.

A: there is also a chromium extension named "StayFocused" doing that. nice extension if you're just using chromium.


text:
Q: Need help with Image processing using Python I am a new programmer in Python and I am trying to do some image processing. I want to incorporate a selection feature on an image with the help of the mouse. The image will display and then the user will select a part of the image with the mouse which will get saved as a new image. I have idea about opening, displaying and saving an image but I have no idea if we can select an image in Python using any algorithm. Any help will be appreciated.
Regards.

A: Checkout PIL (Python Imaging Library):
http://www.pythonware.com/products/pil/

A: I am not sure what image library you are using. But to create a subset of an image using PIL look here under the chapter "Cutting, Pasting and Merging Images".

A: If you are trying to do some complex shape selecting instead of rectangle cutting, you may look into OpenCV library,
http://opencv.willowgarage.com/documentation/python/index.html


text:
Q: Using Viewbag data on javascript on views page In my project ı am trying to use a javascript chart with my datas on database,
firstly I have sent my data with viewbag
 public IActionResult Index()
    {
        var student = _context.Student.Select(x => x.Name).ToList();
        ViewBag.student = student;
        var notes = _context.Student.Select(y => y.Note).ToList();
        ViewBag.notes = notes;

        return View();
    }

So in javascript The premade chart has a code like this;
   $('#graph2').graphify({
    start: 'donut',
        obj: {
        id: 'lol',
            legend: false,
            showPoints: true,
            width: 775,
            legendX: 450,
            pieSize: 200,
            shadow: true,
            height: 400,
            animations: true,

        x: [2000, 2001, 2002, 2003, 2004, 2005, 2006],
        points: [17, 33, 64, 22, 87, 45, 38],
        xDist: 90,
            scale: 12,
            yDist: 35,
            grid: false,
            xName: 'Year',
            dataNames: ['Amount'],
            design: {
            lineColor: 'red',
                tooltipFontSize: '20px',
                pointColor: 'red',
                barColor: 'blue',
                areaColor: 'orange'
            }
        }
    });

I want to add my viewbag datas into the  x and point arrays i tried something like this;
@foreach(var item in (List<string>Viewbag.student)
{x.push(item);}

but it did not work at all.

A: You cannot mix Razor and JavaScript like that. You will have to keep in mind that the Razor rendering happens on the server and once it's done, the result will be served as static HTML to the browser which will only then interpret it and run the JavaScript.
So in order to pass information from Razor to JavaScript, you will need to do it in a way that survives the rendering process.
A good way to do this is to serialize your data as JSON and store it in a variable that the JavaScript code can access. You can use the Json.Serialize method from within your Razor view to do that:
<script>
var studentData = @Json.Serialize(ViewBag.Student);
var notesData = @Json.Serialize(ViewBag.Notes);

// now do something with those JavaScript variables…
</script>

The @… part will be executed by the Razor renderer, so the rendered result could look for example like this:
<script>
var studentData = ["student1", "student2", "student3"];
var notesData = [123, 456, 789];

// now do something with those JavaScript variables…
</script>

That result is now valid JavaScript and can be properly executed by the client.

A: First of all you should not be doing it this way either send json object from a controller action and then utilize it in your view. A quick dirty solution is to call js code with @: like:
@foreach(var item in (List<string>ViewBag.student)
{
  @:x.push("@item");
}

As @ tells that this is razor or server side c# code and if we need to loop a server side and in it do something with js we can use @: to tell that it's not c# or sercer side code.


text:
Q: Read settings in another section than values I have following settings file:
{
  "IsEncrypted": false,
  "Values": {
    "UniquePermisionsQueueConnStr": "xx",
    "UniquePermisionsQueueName": "spo-unique-permissions-reporting",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "AzureWebJobsDashboard": "UseDevelopmentStorage=true"
  },
  "CosmosDB": {
    "UniquePermisionsQueueConnStr": "xx"
  }
}

I can read the settings in the values section without any props by using ConfigurationManager.AppSettings["UniquePermisionsQueueName"]; or Environment...
However how do I get the values in the CosmosDB section? I tried ConfigurationManager.AppSettings["CosmosDB:UniquePermisionsQueueName"] but with no luck.

A: Only Values section is injected into Environment variables by Azure Function runtime, hence we got nothing for other section.
We need to read the Json file as usual. Add ExecutionContext context in function method signature and try code below.
var r = new StreamReader(context.FunctionAppDirectory+"/local.settings.json");
var myJson = r.ReadToEnd();
dynamic config =  JsonConvert.DeserializeObject(myJson);
var cosmosDBSettings = config.CosmosDB as JObject;
var uniquePermisionsQueueConnStr = cosmosDBSettings.GetValue("UniquePermisionsQueueConnStr").ToString();

As for deployment to Azure, local.settings.json is for local dev, which is not uploaded to Azure by default. We should remove <CopyToPublishDirectory>Never</CopyToPublishDirectory> in <functionname>.csproj(Right click on project and Edit <functionname>.csproj).


text:
Q: HTML Email Outlook.com lines appearing under column In my email design I have strange lines appearing under my right hand column.  The left hand column seems uneffected.  It appears to be the styling from my <a> (the link).
The links don't appear to be linking either.

A: This is caused by using <a href="#"> or by not using http:// or https://.  I replaced all "#" with "http://www.example.com" to resolve.
This was causing my border from my link to show on my column.  So if you see other link styling on your column, or a <td> that could be why


text:
Q: Pandas: splitting data frame based on the slope of data I have this data frame
x = pd.DataFrame({'entity':[5,7,5,5,5,6,3,2,0,5]})

Update: I want a function If the slope is negetive and the length of the group is more than 2 then it should return True, index of start and end of the group. for this case it should return:  result=True, index=5, index=8
1- I want to split the data frame based on the slope. This example should have 6 groups.
2- how can I check the length of groups?

I tried to get groups by the below code but I don't know how can split the data frame and how can check the length of each part
New update: Thanks Matt W. for his code. finally I found the solution.
df = pd.DataFrame({'entity':[5,7,5,5,5,6,3,2,0,5]})
df['diff'] = df.entity.diff().fillna(0)
df.loc[df['diff'] < 0, 'diff'] = -1

init = [0]
for x in df['diff'] == df['diff'].shift(1):
    if x:
        init.append(init[-1])
    else:
        init.append(init[-1]+1)
def get_slope(df):
    x=np.array(df.iloc[:,0].index)
    y=np.array(df.iloc[:,0])
    X = x - x.mean()
    Y = y - y.mean()
    slope = (X.dot(Y)) / (X.dot(X))
    return slope
df['g'] = init[1:]

df.groupby('g').apply(get_slope)

Result
0    NaN
1    NaN
2    NaN
3    0.0
4    NaN
5   -1.5
6    NaN

A: Take the difference and bfill() the start so that you have the same number in the 0th element. Then turn all negatives the same so we can imitate them being the same "slope". Then I shift it to check to see if the next number is the same and iterate through giving us a list of when it changes, assigning that to g.
df = pd.DataFrame({'entity':[5,7,5,5,5,6,3,2,0,5]})
df['diff'] = df.entity.diff().bfill()
df.loc[df['diff'] < 0, 'diff'] = -1

init = [0]
for x in df['diff'] == df['diff'].shift(1):
    if x:
        init.append(init[-1])
    else:
        init.append(init[-1]+1)
df['g'] = init[1:]
df
   entity  diff  g
0       5   2.0  1
1       7   2.0  1
2       5  -1.0  2
3       5   0.0  3
4       5   0.0  3
5       6   1.0  4
6       3  -1.0  5
7       2  -1.0  5
8       0  -1.0  5
9       5   5.0  6

A: Just wanted to present another solution that doesn't require a for-loop:
df = pd.DataFrame({'entity':[5,7,5,5,5,6,3,2,0,5]})
df['diff'] = df.entity.diff().bfill()
df.loc[diff < 0, 'diff'] = -1
df['g'] = (~(df['diff'] == df['diff'].shift(1))).cumsum()
df


text:
Q: Connecting two numpy array channels I have two numpy arrays, for example:
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [[11,12,13],[14,15,16],[17,18,19]]

Which are channels of the same image. I would like to get the "connected" channels array in a as pythonic way as possible. wanted outcome:
c = [[[1,11],[2,12],[3,13]],
    [[4,14],[5,15],[6,16]],
    [[7,17],[8,18],[9,19]]]

What Iv'e tried:
I created an array of the same size and looped over both the source array to connect them.
for x in range(len(a)):
    for y in range(len(a[x])):
        c[x][y] = [a[x][y],b[x][y]]

What I need: I would love to find a more efficient, modular and pythonic way of implementing this.

A: You can use np.stack on the second axis:
>>> np.stack((a,b),axis=2)
array([[[ 1, 11],
        [ 2, 12],
        [ 3, 13]],

       [[ 4, 14],
        [ 5, 15],
        [ 6, 16]],

       [[ 7, 17],
        [ 8, 18],
        [ 9, 19]]])

Checking that it's the same as your c array:
c = np.array([[[1,11],[2,12],[3,13]],
              [[4,14],[5,15],[6,16]],
              [[7,17],[8,18],[9,19]]])

>>> (c == np.stack((a,b),axis=2)).all()
True

A: This is dstack.  You mention this is an image, and from the docs:

This is a simple way to stack 2D arrays (images) into a single 3D array for processing.

np.dstack((a, b))

array([[[ 1, 11],
        [ 2, 12],
        [ 3, 13]],

       [[ 4, 14],
        [ 5, 15],
        [ 6, 16]],

       [[ 7, 17],
        [ 8, 18],
        [ 9, 19]]])

Minor note, the docs also state that concatenate, and stack should be preferred, as they are more general.


text:
Q: CRM 2011 setting form field value but display stays blank Sometimes (in fact most times) when I try to set a lookup field value, the value is set and readable, but the field itself looks blank on the form.
Why might this be? All the parameters passed to setSimpleLookupValue look correct.
Any ideas as to why this might be happening?
This is the function which does most of the work:
function sgc_hr_getManager() {
  var testContactId = Xrm.Page.getAttribute("sgc_hr_case_initialcontact").getValue();
  if (testContactId != null) {
    // do nothing - the field already has a value
  } else {
    var employeeVal = Xrm.Page.getAttribute("customerid").getValue();
    if( employeeVal != null && employeeVal[0] && employeeVal[0].id != null ) {
      var employeeId = Xrm.Page.getAttribute("customerid").getValue()[0].id;
      employeeId = employeeId.replace('{','').replace('}','');
      SDK.REST.retrieveRecord( employeeId, 'Contact', null, null, function( employee )     {
        var managerId = employee.sgc_hr_ManagerId.Id;
        if( managerId != null ) {
          SDK.REST.retrieveRecord( managerId, 'Contact', null, null, function( manager ) {
              // the following function call correctly sets the value
              // but the control display is usually left blank
              setSimpleLookupValue( 'sgc_hr_case_initialcontact', 'Contact', manager.ContactId, manager.FullName );
          }, function(a) {
              alert('An error occured! Unable to retrieve postholder record ' + managerId );
          });
        }
      }, function(a) {
          alert('An error occured! Unable to retrieve postholder record ' + employeeId );
      })
    } else {
        alert('Cannot get employee details');
    }
  }
}

The setSimpleLookupValue function is the standard one as follows:
function setSimpleLookupValue(LookupId, Type, Id, Name) {
   var lookupReference = [];
   lookupReference[0] = {};
   lookupReference[0].id = Id;
   lookupReference[0].entityType = Type;
   lookupReference[0].name = Name;
   Xrm.Page.getAttribute(LookupId).setValue(lookupReference);
  }

A: Try to add next line before you set the value
Xrm.Page.getAttribute("sgc_hr_case_initialcontact").setSubmitMode("always");


text:
Q: Jacobian determinant question Show that the pair of equations
$$x^2-y^2-u^3+v^2+4=0\;,\;\; 2xy+y^2-2u^2+3v^4+8=0$$
Determine local functions $x(u,v)$ and $y(u,v)$ defined for $(u,v)$ near $u = 2$ and $v = 1$ such that $x(2,1) = 2$ and $y(2,1) = -1$.
Compute $\dfrac{\partial u}{\partial x}$ at $(2,1)$

A: Hint Let $p=u^3-v^4-4,\ q=2u^2-3v^4-8,$ so that your system is
$$x^2-y^2=p, \\ 2xy+y^2=q. \tag{1}$$
If the second equation of $(1)$ is solved for $x$ one has
$$x=\frac{q-y^2}{2y}. \tag{2}$$
Now substitute this into the first equation of $(1)$ and move $p$ to the left side, obtaining an expression which must be zero. This expression has a denominator of $4y^2$ which is irrelevant for solutions, and the negative of its numerator is quadratic in $y^2$, i.e. only contains $y^4,y^2$ [and $p,q$ ] so it determines $y^2$ from $p,q.$ Specifically,
$$3y^4+2(2p+q)y^2-q^2=0. \tag{3}$$
Now here's why this answer is only a hint: at this point you may be able to use the initial conditions that at $(u,v)=(2,1)$ you have $(x,y)=(2,-1).$ I did calculate that at these values of $u,v$ one has $p=3,\ q=-3$ and when plugged in this agrees with $(x,y)=(2,-1).$ When $(3)$ is solved for $y^2$ there will be a sign choice on the $y^2$, and after that on passing to $y$ itself there is another sign choice, for a total of four sign choices in all. To make the solution local satisfying the conditions, the right sign choices need to be made, which determines $y,$ and then $x$ is forced by $(2).$
Given the forms of $p,q$ this approach may give  rather complicated formulas for $x,y$ in terms of $u,v$. There may be a simpler way but I don't see one.


text:
Q: Align left and align right across lines I am new to latex and I want the following format but simple things like \hfill does not help here.
Name:XX                                                          Email: abc@example.com
Work:YY                                                          Phone: +1 666222

In particular I want starting of phone and email to be aligned, as well as Name and Work to be aligned.
Any help appriciated.

A: \begin{tabular}[t]{@{}ll@{}}
Name& zz\\
Work& zzz
\end{tabular}%
\hfill
\begin{tabular}[t]{@{}rr@{}}
email& z\\
phone& zzz
\end{tabular}

You need to align each side in a box (eg tabular) then push them apart with \hfill

A: For this specific case, David Carlisle's answer works great. But, in general if you want table to span the entire \linewidth, I find using the X column from tabularx to be very useful:

Notes:

*

*The showframe package
was used just to show the page margins.
It is not needed in your actual use case.
was just to show the page margins.

*Here I have used the X column to be the blank column between the two groups of text. Hence the double && separating the two groups.

*The @{} at the left and right of the table remove the inter column padding that would normally be applied.
Code:
\documentclass{article}
\usepackage{tabularx}
\usepackage{showframe}

\begin{document}
\noindent
\begin{tabularx}{\linewidth}{@{}l l X l l@{}}
    Name: & XX   && Email: & abc@example.com\\
    Work: & YYY  && Phone: & +1 666222\\
\end{tabularx}%
\end{document}


text:
Q: PL/SQL - Oracle 9.1 Here is the scenario we are working on here. We have a customer table and a sales table. The tables join via the transaction ID in cust table.
A customer can buy any fruit from the store.
What we need to do is find out for example: how many customer bought apples before they bought cherries.
Table structure:

Cust - Cust ID, Transaction ID, ...
Sales - Transaction ID, Fruit ID, Insert date for record, ...

What would be the most cost efficient way of achieving this considering that a customer can have different transaction ID for same fruit ID as he might have bought the fruit multiple times.
So we need to find, when is the 1st apple and 1st cherry bought by cust then check the dates on them.

A: How can transaction_id be a column/attribute for customer ? That implies a customer can only have one transaction.
Assuming you have a table that has the customer_id, fruit_id and sale_date you can try
select cust_id,
       min(case when fruit_id = 'Apple' then sale_date end) first_apple_purchase,
       min(case when fruit_id = 'Cherry' then sale_date end) first_cherry_purchase
from transactions
group by cust_id
having min(case when fruit_id = 'Apple' then sale_date end) <
        min(case when fruit_id = 'Cherry' then sale_date end)

A: I second Gary's opinion of the data model, but that is irrelevant to the question.
This is one possible solution.  It is likely to be pretty efficient if there are lots of potential values for FRUIT_ID and that column is indexed.
select apple.cust_id
from
    ( select c.cust_id, min(s.sale_date) as sale_date
      from cust c
           join sales s
                on s.transaction_id = c.transaction_id
      where s.fruit_id = 'CHERRY'
      group by c.cust_id ) cherry
    ,
    ( select c.cust_id, min(s.sale_date) as sale_date
      from cust c
           join sales s
                on s.transaction_id = c.transaction_id
      where s.fruit_id = 'APPLE'
      group by c.cust_id ) apple
where cherry.cust_id = apple.cust_id
and cherry.sale_date > apple.sale_date
/

If there are fewer values of FRUIT_ID then a variation on Gary's suggestion would probably be more efficient:
select cust_id
from
    ( select c.cust_id
             , min(case when s.fruit_id = 'CHERRY' = s.sale_date else null end) as cherry_date
             , min(case when s.fruit_id = 'APPLE' = s.sale_date else null end) as apple_date
      from cust c
           join sales s
                on s.transaction_id = c.transaction_id
      group by c.cust_id ) cherry
where cherry_date > apple_date
/

Caveat lector: I currently don't have access to a database so these statements are untested and may have syntax errors.  I'll check them when I can.