text:
Q: Select concat between colections by linq
I have Two collections, every collection is type of **Model Object** , **Type Object** , ** Version Object** and I need to get a list of **ConcateName Object** by linq, this object has concatination of 2 names of Type and Model and Version plus a list of details of every name(details in Classes section):
Classes
class Model
{
    public string name { get; set; } // Exemple: "M1"
    public string Id { get; set; }  // Exemple:  "codeM1"
}

class Type
{
    public string name { get; set; }  // Exemple: "T1"
    public string Id { get; set; }  // Exemple: "codeT1"
}

class Version
{
    public string name { get; set; } // Exemple: "V1"
    public string Id { get; set; }  // Exemple:  "codeV1"
}

class ConcateName
{
    public string ConcateName { get; set; } // exemple:  "M1 T1"
    public List<ConcateNameInfo> ConcateNameInfos { get; set; }
}

class ConcateNameInfo
{
    public Guid TechnicalId { get; set; }
    public string Criteria { get; set; }  "M1"
    public Guid ValueId { get; set; }  "CodeM1"
}

List of Models
var models = new List<Model>();
var model1 = new Model(){name ="M1", id= "CodeM1"};
var model2 = new Model(){name ="M2", id= "CodeM2"};
models.Add(model1);
models.Add(model2);

List of Types
var types = new List<Type>();
var type1 = new type(){name ="T1", id= "CodeT1"};
var type2 = new type(){name ="M2", id= "CodeT2"};
models.Add(type1);
models.Add(type2);

List of Versions
var versions = new List<Version>();
var version1 = new Version(){name ="V1", id= "CodeV1"};
var type2 = new Version(){name ="V2", id= "CodeV2"};
models.Add(type1);
models.Add(type2);

The OUTPUT WILL 12 Objects of ConcateName
        var ConcateName1 = new ConcateName()
{
    ConcateName = "M1 P1",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M1",
                                                            ValueId = "codeM1"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "T1",
                                                        ValueId     = "codeT1"
                                                        }
    }
}

var ConcateName2 = new ConcateName()
{
    ConcateName = "M1 P2",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M1",
                                                            ValueId = "codeM1"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "T2",
                                                        ValueId     = "codeT2"
                                                        }
    }
}

var ConcateName3 = new ConcateName()
{
    ConcateName = "M2 P1",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M2",
                                                            ValueId = "codeM2"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "T1",
                                                        ValueId     = "codeT1"
                                                        }
    }
}

var ConcateName4 = new ConcateName()
{
    ConcateName = "M2 P2",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M2",
                                                            ValueId = "codeM2"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "T2",
                                                        ValueId     = "codeT2"
                                                        }
    }
}

var ConcateName5 = new ConcateName()
{
    ConcateName = "M1 V1",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M1",
                                                            ValueId = "codeM1"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "V1",
                                                        ValueId     = "codeV1"
                                                        }
    }
}

var ConcateName6 = new ConcateName()
{
    ConcateName = "M1 V2",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M1",
                                                            ValueId = "codeM1"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "V2",
                                                        ValueId     = "codeV2"
                                                        }
    }
}

var ConcateName7 = new ConcateName()
{
    ConcateName = "M2 V1",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M2",
                                                            ValueId = "codeM2"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "V1",
                                                        ValueId     = "codeV1"
                                                        }
    }
}

var ConcateName8 = new ConcateName()
{
    ConcateName = "M2 V2",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "M2",
                                                            ValueId = "codeM2"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "T2",
                                                        ValueId     = "codeV2"
                                                        }
    }
}

var ConcateName9 = new ConcateName()
{
    ConcateName = "T1 V1",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "T1",
                                                            ValueId = "codeT1"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "V1",
                                                        ValueId     = "codeV1"
                                                        }
    }
}

var ConcateName10 = new ConcateName()
{
    ConcateName = "T1 V2",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "T1",
                                                            ValueId = "codeT1"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "V2",
                                                        ValueId     = "codeV2"
                                                        }
    }
}

var ConcateName11 = new ConcateName()
{
    ConcateName = "T2 V1",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "T2",
                                                            ValueId = "codeT2"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "V1",
                                                        ValueId     = "codeV1"
                                                        }
    }
}

var ConcateName12 = new ConcateName()
{
    ConcateName = "T2 V2",
    ConcateNameInfos = new List<ConcateNameInfo>() {
                                                        new ConcateNameInfo
                                                        {
                                                            TechnicalId = Guid.newGuid(),
                                                            Criteria = "T2",
                                                            ValueId = "codeT2"
                                                        },

                                                        new ConcateNameInfo
                                                        {
                                                             TechnicalId = Guid.newGuid(),
                                                        Criteria    = "T2",
                                                        ValueId     = "codeV2"
                                                        }
    }
}

A: var output = models.SelectMany(m => types.Select(t => new ConcateName
{
    ConcateName = m.Name + " " + t.Name,
    ConcateNameInfos = new List<ConcateNameInfo>
    {
        new ConcateNameInfo
        {
            TechnicalId = Guid.NewGuid(),
            Criteria = m.Name,
            ValueId = m.Id
        },
        new ConcateNameInfo
        {
            TechnicalId = Guid.NewGuid(),
            Criteria = t.Name,
            ValueId = t.Id
        }
    }
});

For an arbitrary number of classes, you would need to introduce an interface:
interface IHasNameAndId
{
    string Name { get; }
    string Id { get; }
}

Then you can calculate the Cartesian Product:
public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(
    this IEnumerable<IEnumerable<T>> enumerables)
{
    return enumerables.Aggregate
    (
        new [] { Enumerable.Empty<T>() }.AsEnumerable(),
        (accumulator, enumerable) =>
            accumulator.SelectMany(x => enumerable.Select(x.Append))
    );
}

Which can be projected into your required structure:
var lists = new IHasNameAndId[] { models, types, //...
var output = lists
    .CartesianProduct()
    .Select(x => new ConcateName
    {
        ConcateName = string.Join(" ", x.Select(y => y.Name)),
        ConcateNameInfos = x.Select(y => new ConcateNameInfo
        {
            TechnicalId = Guid.NewGuid(),
            Criteria = y.Name,
            ValueId = y.Id
        })
        .ToList()
    });


text:
Q: get user role by user id in moodle I want to get user role from user id. I am using loop in my code where i want to show all user except admin. i used below code but its not working.
$context = get_context_instance (CONTEXT_SYSTEM);
$roles = get_user_roles($context, $USER->id, false);
$role = key($roles);
$roleid = $roles[$role]->roleid;

Its provide me blank array as like screenshot. Also below my all code.
https://prnt.sc/gq8p12
$allUsers = $DB->get_records('user');
    $SQL = "SELECT * FROM `".$CFG->prefix."config` WHERE `name` LIKE 'siteadmins'";
    $getSiteAdmins = $DB->get_record_sql($SQL);
    $explodeAdminIds = explode(',', $getSiteAdmins->value);
    $context = get_context_instance (CONTEXT_SYSTEM);

    if(!empty($allUsers))
    {
        foreach ($allUsers as $allUser)
        {
            if(!in_array($allUser->id, $explodeAdminIds))
            {
                $roles = get_user_roles($context, $allUser->id, false);
                $role = key($roles);
                $roleid = $roles[$role]->roleid;

                echo 'USER ID -- '.$allUser->id.' >>> ';
                print_r($roles); echo '
';

                $name = 'wwwroot . '/user/profile.php?id='.$allUser->id.'&mid=4">'.$allUser->id.'_'.$allUser->firstname.' '.$allUser->lastname.'';
                $confirmed = ($allUser->confirmed == 1) ? 'Active' : 'In-active';
                $table->data[] = array(
                    $i,
                    $name,
                    'Team Name',
                    $allUser->email,
                    $allUser->phone1,
                    'Role',
                    $confirmed,
                    //empty($coachusrarr)?'--':implode(',',$coachusrarr),
                    //empty($tmpleaderarr)?'--':implode(',',$tmpleaderarr),
                    //$coach,
                );
                $i++;
            }
        }
    }

A: The basic problem is that get_user_roles($context, $userid) will only get you a list of roles assigned at that particular context level. Very few users have roles assigned at the system context, it is much more usual for roles to be assigned at a course level. This allows users to have different roles in different courses (a teacher on one course, might be enrolled as a student on another course).
If you want to get all the roles for a user, then you're going to need to do something like this:
$roleassignments = $DB->get_records('role_assignments', ['userid' => $user->id]);

You can then loop through all the $roleassignments and extract the 'roleid' from them (alternatively, you could use the $DB->get_fieldset command, to extract the roleids directly).
Note also that you should be using context_system::instance() instead of the old get_context_instance(CONTEXT_SYSTEM) (unless you are using a very old and insecure version of Moodle).
For getting the site admins, use get_admins() (or, if you really want to access the config value, use $CFG->siteadmins).

A: If you want to get a user role for a course by user id then this script will help you.
$context = context_course::instance($COURSE->id);
$roles = get_user_roles($context, $USER->id, true);
$role = key($roles);
$rolename = $roles[$role]->shortname;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I insert an MD5("value" + CURRENT_TIMESTAMP) using prepared statements? I'm doing this:
String columns = "UserHash,EMail,Name,Gender,BirthYear,Birthday,MaritalStatus,UserID,ReferralUser,Likes";

String sql = "INSERT INTO Users ("+ columns+") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
        byte[] bytesOfUserHash = user.getId().getBytes("UTF-8");

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] userHash = md.digest(bytesOfUserHash);

        stmt  = con.prepareStatement(sql);
        stmt.setBytes(1,userHash);
        stmt.setString(2, user.getEmail());
        stmt.setString(3, user.getName());
        stmt.setInt(4, user.getGender().value());
        stmt.setString(5, birthday.split("-")[0]);
        stmt.setString(6, birthday);
        stmt.setInt(7, user.getRelationshipStatus().value());
        stmt.setString(8, user.getId());
        stmt.setString(9, referraluser);
        stmt.setString(10, likesjson);
        stmt.executeUpdate();

All values are being inserted except for userHash, so the query is succeeding.  What should I check?
Also, note I'm just hashing the userid right now, but I would like to hash the userid + CURRENT_TIMESTAMP.
UPDATE:
As a sanity check, I just tried tossing a string into the UserHash column as it is of type VARCHAR(45) and that's not working either.  Something is obviously amiss independent of the MD5 issue.

A: You can use MySQL's built in MD5 function and only pass userId as parameter
    String sql = "INSERT INTO Users ("+ columns+") VALUES (MD5(CONCAT(?,CURRENT_TIMESTAMP), ?, ?, ?, ?, ?, ?, ?, ?, ?);";

    stmt  = con.prepareStatement(sql);
    stmt.setInt(1,user.getId());
    ...


text:
Q: Enterprise Library DAAB 6 and ODP.NET - Connection string for the default database 'XXX' does not exist I am using enterprise library DAAB 6. To communicate with Oracle database I am using EntLib Contrib library.
Configuration file of my application looks like
<configuration>
    <configSections>
        <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <dataConfiguration defaultDatabase="OracleConnectionString">
        <providerMappings>
            <add databaseType="EntLibContrib.Data.OdpNet.OracleDatabase, EntLibContrib.Data.OdpNet, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"
                name="Oracle.DataAccess.Client" />
        </providerMappings>
    </dataConfiguration>
    <connectionStrings>
        <add name="OracleConnectionString" connectionString="Data Source=localhost:1521/dev;User ID=db_owner;Password=admin;"
            providerName="Oracle.DataAccess.Client" />
    </connectionStrings>
<configuration>

I have installed all the required packages using NuGet. Package.Config file looks like:
<packages>
    <package id="EnterpriseLibrary.Common" version="6.0.1304.0" targetFramework="net45" />
    <package id="EnterpriseLibrary.Data" version="6.0.1304.0" targetFramework="net45" />
    <package id="EntLibContrib.Data.OdpNet" version="6.0.1304.0" targetFramework="net45" />
</packages>

I have also added a reference to the Oracle.DataAccess.dll file.
I connect to the database using the following line of code
var database = new DatabaseProviderFactory().CreateDefault();

The above line generates a very weird error message. Full stack trace is given below:
System.InvalidOperationException: The connection string for the default database 'OracleConnectionString' does not exist or does not have a valid provider.
---> System.Configuration.ConfigurationErrorsException: The requested database OracleConnectionString does not have a valid ADO.NET provider name set in the connection string. (C:\Test\OraConsole\bin\Debug\OraConsole.vshost.exe.Config line 13)
   at Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSyntheticConfigSettings.GetDatabase(String name)
   at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseProviderFactory.DatabaseConfigurationBuilder.<CreateDefault>b__2(String n)
   --- End of inner exception stack trace ---
   at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseProviderFactory.DatabaseConfigurationBuilder.<CreateDefault>b__2(String n)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseProviderFactory.DatabaseConfigurationBuilder.CreateDefault()
   at Microsoft.Practices.EnterpriseLibrary.Data.DatabaseProviderFactory.CreateDefault()
   at Data.OdpNet.QuickStarts.Console.Program.Main(String[] args) in c:\Test\OraConsole\Program.cs:line 15

tnsping is working fine for the Oracle database.
I have googled this particular error message but I am unable to find the solution for this problem. I have also tried the QuickStart code sample available with Contrib source. Its also generating the same error message.

A: It sounds like DbProviderFactories is not setup for Oracle.  Usually when installing ODP.NET the machine config will get updated with something like:
<system.data>
    <DbProviderFactories>
      <add name="Oracle Data Provider for .NET Version 11.1.0.6.0"
           invariant="Oracle.DataAccess.Client Version 11.1.0.6.0"
           description="Oracle Data Provider for .NET Version 11.1.0.6.0"
           type="Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess,
           Version=2.111.6.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
    </DbProviderFactories>
</system.data>

See ODP.NET Configuration.  I would verify the machine.config is setup.  You could also set up the provderfactories in your app/web.config.


text:
Q: return array of controls as aggregation in sap ui5 I have a use case where I want to add two sap.m.Input controls in the FormElement. But I have certain conditions on which these two Input controls can be changed. As I have seen in many examples, .bindAggregation method returns only one control. Can I make it return array of controls?
var oInput1 = new sap.m.Input();
var oInput2 = new sap.m.Input();
var oInput3 = new sap.m.Input();

var oFormElement = new sap.ui.layout.form.FormElement();
oFormElement.bindAggregation("fields", "properties", function(sId, oContext){
    var value = oContext.getProperty("value");
    if (value > 5) {
        return [oInput1, oInput3];
    } else {
        return [oInput1, oInput2];
    }
});

I have written this sample but it show nothing. How to return array of controls in .bindAggregation. I was trying to use HBox in the fields, but it has a risk of causing the layout issues. Can anyone help?
Thanks in advance.

A: You can't return multiple elements in your factory function. The factory function will be called for each context and must return exactly one element.
If you can't modify your service to return one context for each input, you might consider constructing your form in JavaScript instead of using data binding. This means to

*

*request the properties from your service

*loop through each property and add input(s) to the form element using the FormElement.addField method.


text:
Q: Objects added into my arrayList are being overridden by the last object that was added? why is this? Okay so this is a homework related question just so you all know.
Question: Why do my objects in my arrayList have different Course names (like they should)
but all the Letter Grades are the same as the last added Course in the arrayList (they should be whatever Grade that was passed as a parameter when the addCourse method was called)?
Any help you guys can provide would be extremely helpful, if you have any other questions about why I wrote things the way I did then feel free to ask. This place is like a font of wisdom and I'm here to learn everything I can.
I know some of the methods are not completed but I can't actually finish until I figure out how to fix this arrayList issue :)
My output looks like this:
Student ID: 11234
Student Name: Cody

[
Course: COP2013
Letter Grade: A
GPA in course: 3.67,
Course: COP2014
Letter Grade: A
GPA in course: 3.67,
Course: COP2015
Letter Grade: A
GPA in course: 3.67,
Course: COP2016
Letter Grade: A
GPA in course: 3.67,
Course: COP2017
Letter Grade: A
GPA in course: 3.67]

Course.java:
 import java.lang.String.*;

public class Course {

//global variables
private String courseID;
private static String letterGrade;
private static Double numberGrade;

//CONSTRUCTORS
//param
public Course(String id, String letter){
courseID = id;
letterGrade=letter;
compute(letter);
}
//default
public Course(){
    courseID = "COP2053";
    numberGrade = 4.0;
    letterGrade = "A";
    compute(getLetterGrade());
}

//COMPUTING GRADES AND UPDATING
private static Double compute(String letter){
    Double a = 0.0;

    if(letter == "A+"){a = 4.0;}
    else if(letter == "A"){a = 3.67;}
    else if(letter == "A-"){a = 3.33;}
    else if(letter == "B+"){a = 3.00;}
    else if(letter == "B"){a = 2.67;}
    else if(letter == "B-"){a = 2.33;}
    else if(letter == "C+"){a = 2.00;}
    else if(letter == "C"){a = 1.67;}
    else if(letter == "C-"){a = 1.33;}
    else if(letter == "D+"){a = 1.0;}
    else if(letter == "D"){a = .67;}
    else if(letter == "D-"){a = .33;}
    else if(letter == "F"){a = 0.0;}

    return a;

}

public static void updateGrade(String newGrade){
    letterGrade=newGrade;
    numberGrade=compute(newGrade);
}

@Override
public String toString(){
    String a = "\nCourse: "+getCourseID()+"\nLetter Grade: "+getLetterGrade()
            +"\nGPA in course: "+compute(getLetterGrade());
    return a;
}

//GETTERS
public String getCourseID(){
    return courseID;
}

public String getLetterGrade(){
    return letterGrade;
}

public Double getNumberGrade(){
    return numberGrade;
}

}

Transcript.java:
import java.util.ArrayList;

public class Transcript {

private ArrayList<Course> classesTaken = new ArrayList<Course>();

public Transcript(String studentID, String studentName){
 System.out.println("\nStudent ID: "+studentID+"\nStudent Name: "+studentName);
}

public void addCourse(String courseID, String letterGrade){
    Course myCourse = new Course(courseID,letterGrade);
    classesTaken.add(myCourse);
}

public void updateCourse(String courseID, String newLetterGrade){

    for(int i=0; i<classesTaken.size(); i++){

        if(classesTaken.contains(courseID)){
        Course.updateGrade(newLetterGrade);
        }
    }
}

public void getGPA(){
calculateGPA();
}

private Double calculateGPA(){
    for(int i=0; i<classesTaken.size(); i++){
    }

    return 0.0;
}

public void printArray(){
    System.out.println("\n"+classesTaken);
}

}

transcriptTester.java:
public class TranscriptTester {

public static void main(String[] args){
    Transcript test = new Transcript("11234", "Cody");
    test.addCourse("COP2013","A+");
    test.addCourse("COP2014","B+");
    test.addCourse("COP2015","B+");
    test.addCourse("COP2016","D+");
    test.addCourse("COP2017","A");
    test.updateCourse("COP2013", "B-");
    test.updateCourse("COP2014", "A+");
    test.getGPA();
    test.printArray();
}
}

A: You are learning now why we recommend that you avoid over-use of static fields since this is causing your problems. The solution: Don't use static fields to hold an object's state.
Think of static fields as a field shared by all objects of the class. If you change it once it changes for all objects (actually it doesn't even belong to the object but to the class itself).
public class Course {

  //global variables
  private String courseID;

  // the fields below are shared by all the instances of Course.
  private static String letterGrade;
  private static Double numberGrade;

You have some other problems in your code including calling compute(...) and ignoring the answer that is returned, but that's for discussion in another question, I suppose.


text:
Q: How to get a list of classes in a dll without the need for references? c# reflection I want to get the list of classes in an assembly file like below:
Assembly a = Assembly.LoadFrom(dll);
classesList = a.GetTypes();

This assembly uses other references that I haven't them and during getting the classes that exist in them, this error happens:

Could not load file or assembly 'test.dll Version=1.0.7233.5369, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Actually I want to skip getting those classes that do not exist in the current assembly and just get its own classes. but GetTypes() method doesn't have any skip and it crashes.


text:
Q: Passing Custom Data to Fancybox Instances I am trying to integrate Fancybox 3 into my app. In this, I am creating a custom button which process functions based on that instance and it requires additional data about that instance, for example photoId and settingsId for that instance. As an example:
HTML:
In this HTML, I want to pass an object data like {photoId : 1, settingsId: 30}, for each instance that will be used in the custom fancybox button method.

Jquery:
// Create template for custom button
$.fancybox.defaults.btnTpl.custombutton = '<button data-fancybox-custombutton class="fancybox-button fancybox-button--download" title="Download" >' +
              '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">' +
                '<path d="M18.62 17.09V19H5.38v-1.91zm-2.97-6.96L17 11.45l-5 4.87-5-4.87 1.36-1.32 2.68 2.64V5h1.92v7.77z"></path>' +
              '</svg>' +
'</button>';

// Make button clickable using event delegation
$('body').on('click', '[data-fancybox-custombutton]', function() {
                  // Here I need to access the object data for each of that respective instance
                  // For example: {photoId : 1, settingsId: 30}

 });

$().fancybox({
     selector : '.fbelements',
     closeExisting: true,
     fullScreen: true,
     thumbs: false,
     touch: true,
     infoBar: true,
     buttons: [
        "custombutton",
        "zoom",
        "slideShow",
        "fullScreen",
        "close"
     ],
   });

How is that possible? How can I pass additional data for each fancybox gallery instances so that data can be used in the custom button for that image?

A: *

*Use data-* attributes (https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) to store custom data on your links.

*This is how you get reference to original trigger element (e.g., link or button) for current item:
$.fancybox.getInstance().current.opts.$orig

*Then simply use .data() (https://api.jquery.com/data/#data-html5) to retrieve your data from your trigger element.
Demo - https://codepen.io/anon/pen/RXbeQL?editors=1010


text:
Q: Calling module constant? I have the following Angular module. How can i call for example APIHost from one of my controllers?
angular.module('configuration', [])
    .constant('APIHost','http://api.com')
    .constant('HostUrl','http://example.com')
    .constant('SolutionName', 'MySite');

A: Like this, just like any service or factory.
I have also include structure for industry standard (kind of) from john papa's coding guidelines.
(function() {
    'use strict';

    angular
        .module('configuration')
        .controller('ctrlXYZ', ctrlXYZ);
    //Just inject as you would inject a service or factory
    ctrlXYZ.$inject = ['APIHost'];

    /* @ngInject */
    function ctrlXYZ(APIHost) {
        var vm = this;

        activate();

        function activate() {
            //Go crazy with APIHost
            console.log(APIHost);
        }
    }
})();

Hope the helps!

A: Constant is nothing but one kind of provider recipe.
You need to inject constant dependency inside your controller factory function, that's it.
app.controller('testCtrl', function($scope, APIHost){
  console.log(APIHost)
})

Make sure your configuration module has been added to main module as dependency
  to get use of constant's provider like below

var app = angular.module('app', ['configuration', 'otherdependency']);
app.controller( ... ) //here you can have configuration constant available


text:
Q: Creating and Accessing Databases WITHOUT MySQL? I'm having troubles installing MySQL, is there any way to use databases without MySQL?
For exmaple, are there any database files that I can put in my website root directory?

A: You might give sqlite a try: http://www.sqlite.org/about.html.
Have you submitted questions about your installation difficulty on here or on superuser?

A: SQLite (PHP API) is a file-based database, but it must be installed as well. However, since it doesn't run a server it is easier to manage than a server-based RDBMS like MySQL. It is recommended only for low traffic, low volume sites.
You should not store the database at the site root, however.  The file should be stored outside the site's document root so it is not accessible from the web.
(SQLite homepage)


text:
Q: VBA script in Excel to populate the .from field from a cell in the worksheet I have sucessfully configured a VBA script based on an example from http://www.rondebruin.nl to send a copy of an active worsheet in excel as an attachment using a gmail account and CDO.
What I would like to modify is the ability to alter the .From field with the email address of the user that fills out the spreadsheet.  The email address will be filled in the spreadsheet as a part of the process.  Right now, I can only have the .From field populate with a hard coded email address or the email address of the SMTP account being used to send the attachment.
Is my idea possible?
Here is my code as of now.
Option Explicit

'This procedure will send the ActiveSheet in a new workbook
'For more sheets use : Sourcewb.Sheets(Array("Sheet1", "Sheet3")).Copy

Sub CDO_Mail_ActiveSheet_Or_Sheets()
'Working in 97-2007
Dim FileExtStr As String
Dim FileFormatNum As Long
Dim Sourcewb As Workbook
Dim Destwb As Workbook
Dim TempFilePath As String
Dim TempFileName As String
Dim iMsg As Object
Dim iConf As Object
Dim Flds As Variant

With Application
    .ScreenUpdating = False
    .EnableEvents = False
End With

Set Sourcewb = ActiveWorkbook

'Copy the ActiveSheet to a new workbook
ActiveSheet.Copy

'Or if you want to copy more then one sheet use:
'Sourcewb.Sheets(Array("Sheet1", "Sheet3")).Copy

Set Destwb = ActiveWorkbook

'Determine the Excel version and file extension/format
With Destwb
    If Val(Application.Version) < 12 Then
        'You use Excel 97-2003
        FileExtStr = ".xls": FileFormatNum = -4143
    Else
        'You use Excel 2007
        'We exit the sub when your answer is NO in the security dialog that you only
        'see  when you copy a sheet from a xlsm file with macro's disabled.
        If Sourcewb.Name = .Name Then
            With Application
                .ScreenUpdating = True
                .EnableEvents = True
            End With
            MsgBox "Your answer is NO in the security dialog"
            Exit Sub
        Else
            Select Case Sourcewb.FileFormat
            Case 51: FileExtStr = ".xlsx": FileFormatNum = 51
            Case 52:
                If .HasVBProject Then
                    FileExtStr = ".xlsm": FileFormatNum = 52
                Else
                    FileExtStr = ".xlsx": FileFormatNum = 51
                End If
            Case 56: FileExtStr = ".xls": FileFormatNum = 56
            Case Else: FileExtStr = ".xlsb": FileFormatNum = 50
            End Select
        End If
    End If
End With

'    'Change all cells in Destwb to values if you want
'    For Each sh In Destwb.Worksheets
'        sh.Select
'        With sh.UsedRange
'            .Cells.Copy
'            .Cells.PasteSpecial xlPasteValues
'            .Cells(1).Select
'        End With
'        Application.CutCopyMode = False
'    Next sh
'    Destwb.Worksheets(1).Select

'Save the new workbook/Mail it/Delete it
TempFilePath = Environ$("temp") & "\"
TempFileName = "FRAT 135 Helo" & Format(Now, "dd-mmm-yy h-mm-ss")
'TempFileName = "Part of " & Sourcewb.Name & " " & Format(Now, "dd-mmm-yy h-mm-ss")

With Destwb
    .SaveAs TempFilePath & TempFileName & FileExtStr, FileFormat:=FileFormatNum
    .Close savechanges:=False
End With

Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")

iConf.Load -1    ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
    .Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "xxx@testsite.net"
    .Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"

    .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    .Update
End With

With iMsg
    Set .Configuration = iConf
    .To = "safety@xxxx.net"
    .CC = ""
    .BCC = ""
    'I tried this but it doesn't work
    '.From = ThisWorkbook.Sheets("Sheet2").Range("D5").Value

    .From = """Insert Name Here"" <test@yahoo.com>"
    .Subject = "FRAT 135 Helo Submission"
    .TextBody = "Hi There"
    .HTMLBody = "
Dear Safety Advisor
" & _
                 "The attached spreadsheet has been submitted by a member of your team.
" & _
                "Please view this and respond as needed"
                '"Corporate Website"
    .AddAttachment TempFilePath & TempFileName & FileExtStr
    .Send
End With

'Delete the file you have send
Kill TempFilePath & TempFileName & FileExtStr

With Application
    .ScreenUpdating = True
    .EnableEvents = True
End With

End Sub

A: It's definitely possible. Anything you can hard-code can be replaced with a variable value.
You just have to make sure the data that you are reading from the sheet is in the correct format.
You can use the following to make sure you are getting a valid value from the sheet:
Sub EmailFrom()
    Dim hardCodedFrom As String
    Dim fromField As String

    hardCodedFrom = """Insesrt Name Here"" <test@yahoo.com>"
    fromField = ThisWorkbook.Sheets("Sheet2").Range("D5").Value
    MsgBox "The hard-coded .From email is " & hardCodedFrom & vbCrLf & _
            "The variable .From email is " & fromField
End Sub


text:
Q: Best way to pass an array from JavaScript to C#? I need to pass an array from JavaScript to a page method in C#. I have tried using a parameter in the C# method of IList and also a string[] array. Both ways throw an exception "cannot convert an object of type system.string to xxx", where xxx is the parameter type in the C# method. I am passing the object from jQuery as a json object, and looks like it is coming through properly. Here is what it looks like:
{"testNumbers":"5555555555,3333333333,4444444444"}

What am I doing wrong here?
EDIT: C# Code:
[WebMethod()]
public static void ProcessAction(string[] testNumbers)
{
    var dataProvider = new DataProvider();
    dataProvider.ProcessAction(testNumbers);
}

A: You need to use one of the .NET JSON Deserializers:
http://msdn.microsoft.com/en-us/library/bb299886.aspx

A: Hmm, two things:

*

*JSON arrays have square brackets around them

*JSON numbers aren't quoted.

Try this instead:
{"testNumbers": [5555555555,3333333333,4444444444]}

A: {"testNumbers":["5555555555","3333333333","4444444444"]}

should i think do the trick along with a deserialiser. see http://www.json.org/ which has a great graphical representation of the json syntax.


text:
Q: php anchor tag with image in between hello i keep getting an error message when i try to place a image file inbetween 2 anchor tags. i am using echo for the obvous reason i am using php but i get this message when i try to refresh the page:
*Parse error: syntax error, unexpected '<' in E:\Game Downloads\Applications\Xampp\htdocs\WEBSITE DESIGN(PHP)\signed_in.php on line 189*
below is what i have got so far but ive been messing around with the way the speech marks are used and the quotation marks
echo"
";
   echo"""" "";
echo"
";

A: Make it simple as below -
echo  '';

A: Try this:
echo "

";

A: Try this:
print '
';
print '';
print '
;

or similarily:
print '

';


text:
Q: Tamaño del ancho de la columna no coincide con el ancho del filtro thead usando jQuery.datatables
Tengo una tabla con jquery.datatables y en una columna realizo un filtro
initComplete: function () {
                this.api().columns(2).every( function () {
                    var column = this;
                    //var select = $(''<select><option value=""></option></select>'')
                    var select = $(''<select><option value="">'' + $(this.header()).html() + ''</option></select>'')
                        .appendTo( $(column.header()).empty() )
                        .on( ''change'', function () {
                            var val = $.fn.dataTable.util.escapeRegex(
                                $(this).val()
                            );
                            column
                                .search( val ? ''^''+val+''$'' : '''', true, false )
                                .draw();
                        } );
                    column.data().unique().sort().each( function ( d, j ) {
                        select.append( ''<option value="''+d+''">''+d+''</option>'')
                    } );
               } );
            }

Pero mi tbody, no tiene el mismo tamaño que mi celda del filtro.
¿Me pueden ayudar a proporcionar un ejemplo, para que tengan el mismo tamaño?

A: Revisa este ejemplo:
Espero que te pueda ayudar, si tienes alguna duda con gusto te respondo. Saludos.

$(document).ready(function() {
  // Setup - add a text input to each footer cell
  //$('#example tfoot th').each(function() { //Con este ejemplo poniendo en el footer del grid
  $('#example thead th').each(function() {
    var title = $(this).text();
    //Si es la columna Office <-- aqui pongo el combo
    if (title == 'Office') {
      //$(this).html('<input type="text" placeholder="Search ' + title + '" />');

      //Recorro todos los rows para obtener los valores
      ObtenerValoresCombo();
      var combo = '<select style="width:100%">';
        combo += '<option id="0"></option>'
      $.each(valoresCombo, function(i, v) {
        combo += '<option id="' + i + '">' + v + '</option>'
      });
      combo = combo + '</select>';

      $(this).html(combo);
    }
  });

  // DataTable
  var table = $('#example').DataTable({
   sort:false
  });

  // Apply the search
  table.columns().every(function() {
    var that = this;

 $('select', this.header()).on('keyup change', function() {
      if (that.search() !== this.value) {
        that
          .search(this.value)
          .draw();
      }
    });
 /*
 //Ejemplo con el footer
    $('select', this.footer()).on('keyup change', function() {
      if (that.search() !== this.value) {
        that
          .search(this.value)
          .draw();
      }
    });*/
  });
});

var valoresCombo = [];

function ObtenerValoresCombo() {
 valoresCombo = [];
 $('#example tbody tr').each(function(indiceFila) {
  $(this).children('td').each(function(indiceColumna) {
   if(indiceColumna == 2){//Indice de la columna Office
    valoresCombo.push($(this).text());
   }
  });
 });

 //Remuevo los duplicados
 valoresCombo = valoresCombo.unique();
};

Array.prototype.unique=function(a){
  return function(){return this.filter(a)}}(function(a,b,c){return c.indexOf(a,b+1)<0
});
tfoot input {
  width: 100%;
  padding: 3px;
  box-sizing: border-box;
}
<link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css" rel="stylesheet" />

      Name
      Position
      Office
      Age
      Start date
      Salary

      Tiger Nixon
      System Architect
      Edinburgh
      61
      2011/04/25
      $320,800

      Garrett Winters
      Accountant
      Tokyo
      63
      2011/07/25
      $170,750

      Ashton Cox
      Junior Technical Author
      San Francisco
      66
      2009/01/12
      $86,000

      Cedric Kelly
      Senior Javascript Developer
      Edinburgh
      22
      2012/03/29
      $433,060

      Airi Satou
      Accountant
      Tokyo
      33
      2008/11/28
      $162,700

      Brielle Williamson
      Integration Specialist
      New York
      61
      2012/12/02
      $372,000

      Herrod Chandler
      Sales Assistant
      San Francisco
      59
      2012/08/06
      $137,500

      Rhona Davidson
      Integration Specialist
      Tokyo
      55
      2010/10/14
      $327,900

      Colleen Hurst
      Javascript Developer
      San Francisco
      39
      2009/09/15
      $205,500

      Sonya Frost
      Software Engineer
      Edinburgh
      23
      2008/12/13
      $103,600

      Jena Gaines
      Office Manager
      London
      30
      2008/12/19
      $90,560

      Quinn Flynn
      Support Lead
      Edinburgh
      22
      2013/03/03
      $342,000

      Charde Marshall
      Regional Director
      San Francisco
      36
      2008/10/16
      $470,600

      Haley Kennedy
      Senior Marketing Designer
      London
      43
      2012/12/18
      $313,500

      Tatyana Fitzpatrick
      Regional Director
      London
      19
      2010/03/17
      $385,750

      Michael Silva
      Marketing Designer
      London
      66
      2012/11/27
      $198,500

      Paul Byrd
      Chief Financial Officer (CFO)
      New York
      64
      2010/06/09
      $725,000

      Gloria Little
      Systems Administrator
      New York
      59
      2009/04/10
      $237,500

      Bradley Greer
      Software Engineer
      London
      41
      2012/10/13
      $132,000

      Dai Rios
      Personnel Lead
      Edinburgh
      35
      2012/09/26
      $217,500

      Jenette Caldwell
      Development Lead
      New York
      30
      2011/09/03
      $345,000

      Yuri Berry
      Chief Marketing Officer (CMO)
      New York
      40
      2009/06/25
      $675,000

      Caesar Vance
      Pre-Sales Support
      New York
      21
      2011/12/12
      $106,450

      Doris Wilder
      Sales Assistant
      Sidney
      23
      2010/09/20
      $85,600

      Angelica Ramos
      Chief Executive Officer (CEO)
      London
      47
      2009/10/09
      $1,200,000

      Gavin Joyce
      Developer
      Edinburgh
      42
      2010/12/22
      $92,575

      Jennifer Chang
      Regional Director
      Singapore
      28
      2010/11/14
      $357,650

      Brenden Wagner
      Software Engineer
      San Francisco
      28
      2011/06/07
      $206,850

      Fiona Green
      Chief Operating Officer (COO)
      San Francisco
      48
      2010/03/11
      $850,000

      Shou Itou
      Regional Marketing
      Tokyo
      20
      2011/08/14
      $163,000

      Michelle House
      Integration Specialist
      Sidney
      37
      2011/06/02
      $95,400

      Suki Burks
      Developer
      London
      53
      2009/10/22
      $114,500

      Prescott Bartlett
      Technical Author
      London
      27
      2011/05/07
      $145,000

      Gavin Cortez
      Team Leader
      San Francisco
      22
      2008/10/26
      $235,500

      Martena Mccray
      Post-Sales support
      Edinburgh
      46
      2011/03/09
      $324,050

      Unity Butler
      Marketing Designer
      San Francisco
      47
      2009/12/09
      $85,675

      Howard Hatfield
      Office Manager
      San Francisco
      51
      2008/12/16
      $164,500

      Hope Fuentes
      Secretary
      San Francisco
      41
      2010/02/12
      $109,850

      Vivian Harrell
      Financial Controller
      San Francisco
      62
      2009/02/14
      $452,500

      Timothy Mooney
      Office Manager
      London
      37
      2008/12/11
      $136,200

      Jackson Bradshaw
      Director
      New York
      65
      2008/09/26
      $645,750

      Olivia Liang
      Support Engineer
      Singapore
      64
      2011/02/03
      $234,500

      Bruno Nash
      Software Engineer
      London
      38
      2011/05/03
      $163,500

      Sakura Yamamoto
      Support Engineer
      Tokyo
      37
      2009/08/19
      $139,575

      Thor Walton
      Developer
      New York
      61
      2013/08/11
      $98,540

      Finn Camacho
      Support Engineer
      San Francisco
      47
      2009/07/07
      $87,500

      Serge Baldwin
      Data Coordinator
      Singapore
      64
      2012/04/09
      $138,575

      Zenaida Frank
      Software Engineer
      New York
      63
      2010/01/04
      $125,250

      Zorita Serrano
      Software Engineer
      San Francisco
      56
      2012/06/01
      $115,000

      Jennifer Acosta
      Junior Javascript Developer
      Edinburgh
      43
      2013/02/01
      $75,650

      Cara Stevens
      Sales Assistant
      New York
      46
      2011/12/06
      $145,600

      Hermione Butler
      Regional Director
      London
      47
      2011/03/21
      $356,250

      Lael Greer
      Systems Administrator
      London
      21
      2009/02/27
      $103,500

      Jonas Alexander
      Developer
      San Francisco
      30
      2010/07/14
      $86,500

      Shad Decker
      Regional Director
      Edinburgh
      51
      2008/11/13
      $183,000

      Michael Bruce
      Javascript Developer
      Singapore
      29
      2011/06/27
      $183,000

      Donna Snider
      Customer Support
      New York
      27
      2011/01/25
      $112,000


text:
Q: Second MPI_Send is hanging if buffer size is over 256 int n, j, i, i2, i3, rank, size,  rowChunk,  **cells, **cellChunk;

MPI_Status status;

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if(!rank){
    printf("\nEnter board size:\n");
    fflush(stdout);
    scanf("%d", &n);

    printf("\nEnter the total iterations to play:\n");
    fflush(stdout);
    scanf("%d", &j);

    srand(3);

    rowChunk = n/size; //how many rows each process will get

    for(i=1; i<size; i++){

        MPI_Send(&n,1, MPI_INT, i, 0, MPI_COMM_WORLD);
        MPI_Send(&j,1, MPI_INT, i, 7, MPI_COMM_WORLD);
    }

    cells = (int**) malloc(n*sizeof(int*));    //create main 2D array

    for(i=0; i<n; i++){

        cells[i] = (int*) malloc(n*sizeof(int));
    }

    for(i=0; i<n; i++){
        for(i2=0; i2<n; i2++){           //fill array with random data

            cells[i][i2] = rand() % 2;
        }
    }

    for(i=1; i<size; i++){        //send blocks of rows to each process
        for(i2=0; i2<rowChunk; i2++){ //this works for all n

            MPI_Send(cells[i2+(rowChunk*i)], n, MPI_INT, i, i2, MPI_COMM_WORLD);
        }
    }

    cellChunk = (int**) malloc(rowChunk*sizeof(int*));

    for(i=0; i<rowChunk; i++){    //declare 2D array for process zero's array chunk

        cellChunk[i] = (int*) malloc(n*sizeof(int));
    }

    for(i=0; i<rowChunk; i++){   //give process zero it's proper chunk of the array
        for(i2=0; i2<n; i2++){

            cellChunk[i][i2] = cells[i][i2];
        }
    }

    for(i3=1; i3<=j; i3++){

        MPI_Send(cellChunk[0], n, MPI_INT, size-1,1,MPI_COMM_WORLD); //Hangs here if n >256
        MPI_Send(cellChunk[rowChunk-1], n, MPI_INT, 1,2,MPI_COMM_WORLD); //also hangs if n > 256

            ... //Leaving out code that works

This code works perfectly if n (array size) is less than or equal to 256. Any greater, and it hangs on the first MPI_Send. Also, when sending out the array row chunks to the other processes, (first MPI_Send) the other processes receive their data perfectly, even though n > 256. What would cause just this MPI_Send to hang if the buffer size is over 256?

A: You are never receiving any messages, and so the code will fill the local MPI buffer space and then deadlock waiting for an MPI_Recv (or similar) call to be run.  You will need to insert receive operations so that your messages will actually be sent and processed on the receivers.

A: MPI_Send is a blocking call.  The standard mandates that MPI_Send can return control as early as the message buffer can be safely modified.  Alternatively, the MPI_Send can wait to return until some time AFTER the MPI_Recv has started or completed.
The implementation of MPI you are using is likely doing an "eager" message progression if the message is <256 count (With an MPI_INT datatype, this would be a 1k message).  The message is copied into another buffer and control is returned "early."  For large(r) messages, the MPI_Send call does not return until (at least) the matching MPI_Recv call is executed.
If you post a complete reproducer, you will likely get a better answer.

A: MPI_Send "may block until the message is received.", so it is most likely that the matching receive is not reached. You need to make sure the MPI_Recvs are placed in the right order. Since you did not post your receive part, it is impossible to tell the details.
You could restructure your application, to make sure the matching receives are in order. It also might be convenient for you to use the combined MPI_Sendrecv or the nonblocking MPI_Isend, MPI_Irecv and MPI_Wait.


text:
Q: How to pass dynamically android xml layout as argument to custom array adapter class We are making a dynamic custom array adapter for our android project. Now we need to pass dynamic android layout object and other data source as argument when initialize this custom adapter class. After that everything will be dynamic.
public class CustomAdapterView extends ArrayAdapter<String> {
private Activity context;
private String[] googleProducts;
private String[] productDescription;
private Integer[] productImage;
private Layout listItemLayout;

public CustomAdapterView(Activity context, Layout listItemLayout, String[] googleProducts, String[] productDescription, Integer[] productImage) {

    super(context, R.layout.content_custom_listview, googleProducts);
    // Tring to do this
    //super(context, listItemLayout, googleProducts);
    //Error: Cannot resolve method 'super(android.app.Activity, android.text.Layout, java.lang.String[])'

    // Set Local Property
    this.context = context;
    this.googleProducts = googleProducts;
    this.productDescription = productDescription;
    this.productImage = productImage;
}

Now in the super() method we want to pass dynamic Layout for displaying custom list view.
super(context, listItemLayout, googleProducts);

//Error: Cannot resolve method 'super(android.app.Activity,
  android.text.Layout, java.lang.String[])'

Than call that from any Activity
// Initialize
    ListView lv = (ListView) findViewById(R.id.custom_listview);
    Layout dynamicLayout = null;

    // Our Custom Adapter Object
    CustomAdapterView cav = new CustomAdapterView(this, dynamicLayout, googleProducts, productDescription, productImage);
    //Set Adapter
    lv.setAdapter(cav);

A: R.layout.content_custom_listview is an int so, there won't be a super method for that signature. You can pass the int type directly to your adapter instead of Layout type.

A: You seem to be confusing a "layout" resource (i.e. an xml file with a bunch of views in it, accessed via an R.layout.foo constant), and an android.text.Layout object (which manages the internals of displaying text, e.g. in a TextView).
Layout resources are generally passed around as an int, or as a View inflated from that layout resource. Chances are very high that your custom adapter's constructor:
public CustomAdapterView(Activity context,
    Layout listItemLayout,
    String[] googleProducts,
    String[] productDescription,
    Integer[] productImage) {

    ...
}

should be declared like this instead:
public CustomAdapterView(Activity context,
    int listItemLayout,
    String[] googleProducts,
    String[] productDescription,
    Integer[] productImage) {

    ...
}


text:
Q: OpenCV Android Program Bottle-necked by Morphological Functions I have a function that performs erosion and dilation on a binary matrix:
void Detector::morphOps(Mat& binFrame) {
    Mat erodeElement = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
    Mat dilateElement = getStructuringElement(MORPH_ELLIPSE, Size(10, 10));

    erode(binFrame, binFrame, erodeElement);
    dilate(binFrame, binFrame, dilateElement);
    dilate(binFrame, binFrame, dilateElement);
}

This makes my program significantly more robust in detecting the objects I want to track. However, this code is a huge bottleneck for the rest of my program. I drop from 25-30 fps to <1 fps when the function is enabled. Is there something I can do to prevent it from killing my framerate (other than removing it from my program)? i.e. another opencv function that accomplishes the same task more efficiently?
I am also considering multithreading, but I am not sure how to implement it here as I am fairly new to android and opencv. The above code is native (jni) part of my program.
EDIT: Alternatives I have tried so far:

morphologyEx() opening + closing - Doesn't perform as well because the dilate size needs to be larger than the erode size.
morphologyEx() closing + dilate() - no significant performance boost on Android.
changing MORPH_ELLIPSE to MORPH_RECT. I now get ~8fps, but this is still very slow.

A: I tested it on my Zenfone 2 and didn't have much performance issue, it got from 30fps to 23fps but I used 640x360 resolution.
Try reducing the image resolution:
javaCameraView.setMaxFrameSize(size.width, size.height);

You can also make global vars so not to have to initialize it all the time:
Mat erodeElement = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
Mat dilateElement = getStructuringElement(MORPH_ELLIPSE, Size(10, 10));

void morphOps(Mat& binFrame) {
    erode(binFrame, binFrame, erodeElement);
    dilate(binFrame, binFrame, dilateElement);
    dilate(binFrame, binFrame, dilateElement);
}

Is your frame coming from javaCameraView ? it is also important how you pass the data from Java to C++, use like this:
@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)
{
    _imgBgrTemp = inputFrame.rgba();
    jniFrame(_imgBgrTemp.nativeObj);
    return _imgBgrTemp;
}

.nativeObj passes the pointer without recopying the data.
And about threads, it might be a good idea but it is very complicated to make it work safelly, I also have a question about "OpenCV multithreading on Android".
Here
At the time of writing this, there was no answer yet there, but you can follow with me.

A: Making use of the distance transform, you can emulate the morphological operations, especially those with a disk structuring element, and it runs much faster.
Instead of:
int closeDiam = 2 * closeRadius + 1;
Mat strel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(closeDiam, closeDiam));
Mat dst = new Mat();
Imgproc.morphologyEx(src, dst, Imgproc.MORPH_CLOSE, strel);

try:
Mat negSrc = new Mat();
Core.bitwise_not(src, negSrc);
Mat negSrcDT = new Mat();
Imgproc.distanceTransform(negSrc, negSrcDT, Imgproc.CV_DIST_L2, Imgproc.CV_DIST_MASK_PRECISE);
Mat dilated = new Mat();
Core.compare(negSrcDT, new Scalar(closeRadius), dilated, Core.CMP_LE);
Mat dilatedDT = new Mat();
Imgproc.distanceTransform(dilated, dilatedDT, Imgproc.CV_DIST_L2, Imgproc.CV_DIST_MASK_PRECISE);
Mat dst = new Mat();
Core.compare(dilatedDT, new Scalar(closeRadius), dst, Core.CMP_GT);

The running time is about 1/3 whith radius=10, 1/8 whith radius=20, 1/11 whith radius=30, 1/21 with radius=40, and 1/29 with radius=50.
For some reason, the results of the two methods are not exactly equivalent (almost indiscernable for radius=10, but they differ more as radius increases). Conceptually though, they are identical: dilation+erosion.


text:
Q: Shift coordinate points to origin I have a set of coordinate points
import matplotlib.pyplot as plt
xpos = [2419, 2597, 2678, 2691, 2967, 3350, 2227.5, 2781.0, 2278]
ypos = [4687, 4784, 4986, 4479, 4873.5, 3250, 4109, 3329, 3507]
plt.plot(xpos, ypos, '*')
plt.show()

The axes range is from (xmin,ymin) to (xmax, ymax).
I would like to shift the coordinates such that the axes range starts from origin.
Suggestions will be really helpful.


text:
Q: Запись в файл новой строки после вызова функции на С Здравствуйте, нужно написать на С функцию, что будет открывать определенный файл и добавлять туда число на 1 больше предыдущего т.е. функция должна считать последнюю строку и добавить на новую строку следующее число.
Например уже были числа(1, 2(с новой строки)) и должно появиться число 3
Либо этих чисел ещё не было в файле.
Мои попытки что-то создать:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int id(void)
{
        int i;
        char buff[] = "00001";
        char delim[] = "|";
        char *word;
        FILE *f;
        if ((f = fopen("bd2.txt", "a+"))==NULL)
  {
     fprintf(f, "%s\n", "00000");//но.....нет.(не выполняет.)

  }
        f = fopen("bd2.txt", "a+");//Для перехода в конец.
        if(!f)
                 puts("ERROR"), exit(1);
        word = strtok(buff, delim);//В нашей ситуации не нужно
        Num = atoi (word); //Вот только atoi надо использовать с f как-то
        fprintf(f, "%s\n ", word);
        word = strtok(NULL, delim);
        fclose(f);
        return 0;
}

//Выполняет только buff, пытался через atoi что-то сделать, но у меня программа //дальше не работает.
//В этой программе будет бесконечный цикл т.к. неправильно задал
//переменные(Скорее всего)  Но я не знаю как исправить.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//У программы бесконечный цикл, скорее всего. Ибо зависла.
int main(void)
{
        char buff[] = "0";
        char delim[] = "|";
        //char *word;
        int Num=0;//Список ID с 0 и по возрастающей.Дважды обьявляю?
        int i=0;//Чтоб программа потом выполнялась только 1 раз
        int k=1;//Аналогично
        FILE *f;
        if ((f = fopen("bd2.txt", "a+"))==NULL)
  {
     fprintf(f, "%d\n", Num);//но.....нет.

  }
        f = fopen("bd2.txt", "a+");//Для перехода в конец.
        if(!f)
                 puts("ERROR"), exit(1);
      //  word = strtok(buff, delim);//оставит до разделителя инфу.
        Num = atoi (buff);
        if (Num=0)//Хотел сделать на случай самого первого ID
        {
        for(int Num=0; Num<1; Num++)
        fprintf(f, "%d\n ", Num);
        fclose(f);
        }
        else //И на случай остальных ID, основная программа.
        {
          //Неверный цикл, я неправильно написал.(переменная k)
        for(int Num=k; Num>=1; i++)
        fprintf(f, "%d\n ", Num);
        Num=Num+1;
        }
        //  word = strtok(NULL, delim);
        k=k+1;
        fclose(f);
        return 0;
}

A: Мне лень выписывать полный код этой ф-ции, поэтому изображу на псевдокоде:
 1. Инициализация переменных
    N = 0;
    string = '';
 2. Считываем начальное значение N
    2.1. Открываем файл в режиме "r"
    2.2. Цикл до конца файла
         2.2.1. Читаем очередную строку
         2.2.2. Если не EOF, запоминаем её в string.
    2.3. Прочитана последняя строка, N = atoi(string);
    2.4. Закрываем файл
 3. N++;
 4. Записываем в файл
    4.1. Открываем файл в режиме "a"
    4.2. fprintf(Файл, N)
 5. Закрываем файл и выходим из функции


text:
Q: read hbase table salted with phoenix in hive with hbase serde I have created an hbase table with Phoenix SQL create table query and also specified salt_buckets. Salting adds prefix to the the rowkey as expected.
I have created an external hive table to map to this hbase table with hbase serde  The problem is when I query this table by filtering on rowkey:
where key = "value"
it doesn't work because I think salt pre-fix is also getting fetched for the key. This limits the ability to filter the data on key. The option:
"where rowkey like "%value"
works but it takes a long time as likely does the entire table scan.
My question is how can I query this table efficiently on row key values in hive (strip off salt pre-fix)?

A: Yes you're correct while mentioning

it doesn't work because I think salt pre-fix is also getting fetched for the key. '

One way to mitigate is to use hashing instead of random prefix.
And prefix the rowkey with the calculated hash
Using this technique you can calculate hash for the rowkey you want to scan for.:

mod(hash(rowkey),n) where n is the number of regions will remove the hotspotting issue

Using random prefix brings in the problem you mentioned in your question.

The option:
  "where rowkey like "%value"
  works but it takes a long time as likely does the entire table scan.

This is exactly what random prefix salting does. HBase is forced to scan the whole table to get the required value, so it would be better if you could prefix your rowkey with its calculated Hash.
But this hashing technique wont prove good in Range scans.
Now you may ask, why cant I simply replace my rowKey with its Hash and store the rowkey as separate column.
It may/may not work, but I would recommend implementing it this way because HBase is already very sensitive when it comes to Column Families.
But then again I am not clear on this solution.
You also might want to read this for more detailed explanation.


text:
Q: Version error when uploading Change Set I'm trying to deploy custom objects, custom fields, page layouts, compact layouts, Lightning pages and Global value set (global picklist) , when uploading changeset it is giving me API version error as out production platform version 46.0 and SB version is 47.0 , I'm not sure how to bring the version down to 46.0 (There are no Apex triggers/classes in the changeset). Any help would be really appreciated.

A: Looks like your sandbox is updated to the next release.The decision whether your org stays on winter 20 or previous release was documented and released.You can read here

The above chart will be helpful .You will need to know your sandbox instance and take action appropriately before you further build into the org .
Now what that you have built things in the org which is on 47.0 version?
There is simple alternative you can take
1)Use salesforce IDE (like vscode extension for salesforce) to retrieve the packet by changeset name.You can also try this workbench
2)Change the package.xml version to 46.0 and deploy using the IDE.

A: I have just downloaded a changeset in which I have this problem. Now I downloaded it with a Chrome extension, and the package xml in the downloaded zip shows v43. As I do not know how the extension works, I do not know whether the download is a perfect representation of a changeset.
Trying to deploy the zip file, (through sfdx mdapi), I do get an error for my Opportunity Page layout, it contains the Opportunity Contact Role related list, which is not customisable in earlier releases, but with release winter'20/api47, the OpportunityContactRole object has been updated.
Now there might be other changes, and the error provided by SF is not providing this info. So only way to find out what is the issue for you, is to (test) deploy smaller changesets, until you have found the culprit.


text:
Q: Mute Voice Directions in Here Maps iOS SDK I want to toggle the voice directions in my iOS app between on and off. The HERE maps instructions (https://developer.here.com/mobile-sdks/documentation/ios-hybrid-plus/topics_api_nlp_hybrid_plus/protocolnmaaudiomanagerdelegate-p.html) are still all in objective-C. It is quite clear in that language how to do this, but I am looking for the Swift 3 equivalent. That manual says:

*

*@optional (BOOL) audioManager:( NMAAudioManager *) audioManager shouldPlayOutput:( NMAAudioOutput *) output

  Called when the audio manager has output to play.
If the delegate returns YES, or the delegate does not implement this
  method, the output is played immediately. If the delegate returns NO,
  the delegate takes over responsiblity for handling the output.

I am guessing something similar to this, but I can't get it right:
func audioManagerShouldPlayOutput(_ audioManager: NMAAudioManager!, shouldPlayOutput:false) {
    }

A: This is the signature created using the XCode "Generated Interface" assistant editor, hopefully it is helpful! Looks like you are off just a little bit.
optional public func audioManager(_ audioManager: NMAAudioManager!, shouldPlay output: NMAAudioOutput!) -> Bool


text:
Q: HTTPS call not going in Cordova android release apk I am unable to post an HTTPs call in android release apk. I have an android app which makes a https call for login, the request does not even reach the server. However it works in the debug apk version(http). The server logs not showing any error or warnings since the request itself doesn't reach the server. The apk is signed with the actual SHA certificate that is used to host the domain.
    loginHandler(value) {
    this.loader.display(true);

        if (isNaN(value.email)) {
            value.email = value.email.toLowerCase();

        }
        else {
            value.email = value.email;

        }
        var loginValue = {
            'username': value.email,
            'password': value.password
        }

        this.loginService.loginService(loginValue)
        .subscribe(res => {
            this.loader.display(false);

            this.message = '';
            if (res.response.status === 'Success') {

            } else {
                this.errorMessage = res.response.validation;
                this.errorMessage == 'Email not verified. Please check your email.'
                                        ? this.showResendVerification = true
                                        : this.showResendVerification = false;
            }
            if (res.response.validation == "Email or phone number not verified.")
            {
                this.OTPHandler(value);
                this.router.navigate(['/otp-verification']);
            }
        });
}

A: In debug build of cordova android apps, SSL errors are ignored so you can access to any server event if there is no certificate or a bad certificate (for example a dev server).
It behaves diferrently for release build, https connections will fail if the server has :

*

*no SSL certificate

*a self-signed certificate

*a certificate delivered from an autority that is not trusted by the device

*a certificate delivered for a server/url different from the one you are trying to access.

To be sure, you should try to open the browser on the device and open the https url you use in your app. If you get a warning about security, you will know there's an issue with the server certificate.
You can also try to patch the cordova sources so the ssl errors are not ignored even in debug see this post. (then your ssl calls should fail even in debug)


text:
Q: How to use passport-local to authenticate in composer rest server I want to use passport-local to authenticate user to login into composer rest server like other passport strategies ( e.g passport-github,passport-google).
So first I try to set COMPOSER_PROVIDER variable like this
"local": {
    "provider": "local",
    "module": "passport-local",
    "usernameField": "username",
    "passwordField": "password",
    "authPath": "/auth/local",
    "successRedirect": "/",
    "failureRedirect": "/"}

Then i run the server in docker (with mongo as persisted datasource) and add some user in database collection
The question is what's next step that i need to use this passport.Because i run this command and still get response with 401 Unauthorized

curl -H "Content-Type: application/json" -X POST -d
  '{"username":"{USER_NAME}","password":"{USER_PASSWORD}"}'
  http://localhost:3000/auth/local

Is it not enough to use this passport? Does i need to start another service to locally authenticate this login (e.g. GitHub oAuth Application )?

A: It is possible to customize your composer-rest-server, based on the loopback framework, according to your requirements.
I suggest to read this tutorial from the official documentation.
https://hyperledger.github.io/composer/latest/integrating/customizing-the-rest-server

A: I wanted to do that also initially, but then I just edit the server.js file on the composer rest server for basic auth at the end.

*

*check where your composer-rest-server is stored

npm root -g

*Open where server.js is located

cd /home/ubuntu/.nvm/versions/node/v8.10.0/lib/node_modules/composer-rest-server/server

*Add this to the code

const basicauth = require('basicauth-middleware');
app.use(basicauth('username', 'password!');


text:
Q: how can I specify endogenous variables and instrumental variables in systemfit? I want to estimate a set of equations by R package systemfit.But I find that this package can't appoint endogenous variables ,I wonder if you tell me how to solve it.Details are following:
##I have a set of equations ,where x1、x2 and x3 are endogenous variables,X is a set of control variables,c1-c3 are constants.
eqsys <- list("y1=x1+X+c1","y2=x2+X+c2","y3=x3+X+c3")
##the Instrumental variable for each endogenous variable is z1、z2 and z3.

##In stata,we can solve this problem by this way
reg3 $eqlist, endog($x) exog($z)

But is systemfit,inst (instrument variable option) is a one-sided model formula/formulas specifying the instrumental variables,which means
instF <- ~z

and it can't appoint that endogenous variables are x1、x2 and x3.
I wonder if you can tell me how to mplement this line of code reg3 $eqlist, endog($x) exog($z)in systemfit


text:
Q: Retina performance much worse than non-retina in Windows on Parallels and VMWare I have been using Windows (8 then 10) in Parallels on a Mac for years. It has always been very fast.
Over 3 MacBook Air 11" with (2 then 4Gb RAM). Over many versions of MacOS and 2 versions of Windows.
I recently got a 12" MacBook (8Gb RAM) - and the VM also ran fine there. That was until I enabled retina mode in the VM. Then Parallels got slow - often locking up for 10 seconds.
So I spoke to Parallels and they couldn't fix it so I tried VMWare. It is a little better but also locks up from time to time in retina mode.
If you look at Geekbench the 12" is around 3000 - which is within 10% the Geekbench score of low-end MacBook i5 Pro 13" 2015 - and on par with Airs.
Is this a driver issue - or does retina just require a lot more speed?
Would a high-end new MacBook Pro likely fix this?
Has anyone had these issues and found a way to overcome them?

A: I figured this out after a long time.
In MacOS under 'displays' I had 'More Space' selected under resolution - rather than 'Default' or 'Default for display'.
This scales the screen which works OK on MacOS and in the VM in non retina mode - but this is what drastically slows things in Retina mode. Set this to Default (it's actually faster, smoother & more crisp in MacOS like that too as it's pixel perfect not scaled).


text:
Q: Content search webpart - term parents I am looking for a way to search in content via content search webpart by managed metadata. I need something like {Term.IdWithChildren}, but I need to search in parent terms, instead of child terms.
An example:
- root
-- BranchA
--- Node 1
--- Node 2
--BranchB
--- Node 3

If a user's current navigation node is Node 1 for example, I would like to find all items, which are tagged with Node 1, BranchA or root tag.

A: I found my way arround - I extended ContentBySearchWebPart webpart in a way that it modifies query string before querying sharepoint. It goes recursively by navigation terms from current up to root and per each node, one condition is added. Conditions are added to place in query string marked by string, so the condition can be enabled/disabled from UI.
public class MyContentBySearchWebPart : Microsoft.Office.Server.Search.WebControls.ContentBySearchWebPart
{
    protected override void OnLoad(EventArgs e)
    {
        // Hook replace procedure
        if (this.AppManager != null)
        {
            if (this.AppManager.QueryGroups.ContainsKey(this.QueryGroupName) &&
             this.AppManager.QueryGroups[this.QueryGroupName].DataProvider != null)
            {
                this.AppManager.QueryGroups[this.QueryGroupName].DataProvider.BeforeSerializeToClient += new BeforeSerializeToClientEventHandler(UpdateQueryText);
            }
        }
        base.OnLoad(e);
    }

    private void UpdateQueryText(object sender, BeforeSerializeToClientEventArgs e)
    {
        DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;

        // replace token in query with navigation Ids
        string currentQueryText = dataProvider.QueryTemplate;
        string token = "FilterMyTag";

        if (currentQueryText.Contains(token))
        {
            dataProvider.QueryTemplate = currentQueryText.Replace(token, BuildQuery());
        }
    }

    private string BuildQuery()
    {
        StringBuilder sb = new StringBuilder();

        // go thru all navigation nodes up to root
        NavigationTerm term = TaxonomyNavigationContext.Current.NavigationTerm;
        while(term != null)
        {
            sb.AppendFormat(" owstaxIdMyFieldWithTag:\"GP0:{0}\"", term.Id);
            term = term.Parent;
        }

        return sb.ToString();
    }
}


text:
Q: Debug jQuery code in a dialog I am using Chrome latest version (8.0.552.215).
I have a web page with an hyperlink that, when clicked, open up a jquery dialog and makes an ajax call that return HTML markup. the ajax call, upon success, add the returned markup to the dialog.
The returned markup contains also some jquery code to execute upon $(document).ready().
How can I debug that code inside the dialog?
EDIT:
I have added the debugger; directive to my script as per the @Gaby answer
$(document).ready(function () {
    $("#myTabs").tabs();

    debugger;

    var auth = "<% = Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value %>";

But unfortunately when the debugger stops at the directive I am not able to see the code that is executing

A: Set the debugger; directive in your code to call the debugger at a specific point.
you need to have the developer tools open : Ctrl+Shift+j
(For future reference remember that this works with firebug for firefox as well.)
Have a look at http://www.nsbasic.com/app/technotes/TT10.htm#tracing

Update
After comments and update to question.
I don't think you can show the code in the debugger as it is in memory..
A cumbersome alternative would be use console.log(..) for the parts you want to debug.


text:
Q: GL_Triangles with Tessellation Shaders When i am using Tessellation Shaders, do I have to pass from my CPU Program Patches rather then Triangles?.
    glDrawArrays(GL_PATCHES, 0, 3); //Works with Tess Shaders

    glDrawArrays(GL_TRIANGLES, 0, 3); //Works not with Tess Shaders

What is a Patch exactly to visualize it? Can it be a triangle which is being subdivided?

A: A patch is just a collection of points with no real intrinsic structure... your TCS and TES are what make sense out of them. Unlike GL_TRIANGLES (which is strictly defined by 3 vertices), GL_PATCHES has no pre-defined number of vertices per-patch. You set the number of vertices in a patch yourself with:
glPatchParameteri (GL_PATCH_VERTICES, N);
// where N is some value less than GL_MAX_PATCH_VERTICES

Then, every N-many vertices drawn defines a new patch primitive.
Patches are really just a collection of control points for the evaluation of a surface. This is literally why there is an optional stage called Tessellation Control Shader that feeds data to a Tessellation Evaluation Shader. Without more details about the type of surface you are evaluating, about the only way to visualize them is as a point cloud (e.g. GL_POINTS).
Update:
Assuming you are discussing a Bézier surface, then the control points can be visualized thus:

The red points are the control points (vertices in GL_PATCHES), the blue lines are artifical (just for the sake of visualization) and the black squares are the evaluated surface (result of a Tessellation Evaluation Shader). If you tried to visualize this before tessellation evaluation, then your patch would be nothing but red dots and you would have a heck of a time trying to make sense of them.


text:
Q: What does `cat-file` stand for in git? In git, what does cat-file stand for in this command?
$ git cat-file <...>

My first thought is "concatenate file" because the Unix command cat stands for "concatenate", but this doesn't correspond to the function of git cat-file.

A: to read the content ( or blob ) of a git object
git cat-file -p <SHA1>

to read its type
git cat-file -t <SHA1>

A: While cat does stand for "concatenate", what it actually does is simply display one or multiple files, in order of their appearance in the command line arguments to cat. The common pattern to view the contents of a file on Linux or *nix systems is:
cat <file>

The main difference between cat and Git's cat-file is that it only displays a single file (hence the -file part). Git's cat-file doesn't really stand for "concatenate"; it simply is a reference to the behavior of the cat command.

git-cat-file - Provide content or type and size information for repository objects

Technically, you can use git cat-file to concatenate files, if you use Batch Output mode:

BATCH OUTPUT
If --batch or --batch-check is given, cat-file will read objects from stdin, one per line, and print information about them. By default, the whole line is considered as an object, as if it were fed to git-rev-parse[1].

A:
The main difference between cat and Git's cat-file is that it only displays a single file (hence the -file part)

A single file, ... or a list of single files.

In the second form, a list of objects (separated by linefeeds) is provided on stdin, and the SHA-1, type, and size of each object is printed on stdout.
The output format can be overridden using the optional <format> argument.

This is important when you consider git cat-file --batch, which prints object information and contents for each object provided on stdin.
See also git cat-files --batch-command with Git 2.36 (Q2 2022).
And With Git 2.34 (Q4 2021), the "ref-filter" machinery that drives the "--format" option of "git for-each-ref"(man) and its friends evolves, to be used in git cat-file  --batch(man)".
See commit bff9703 (01 Jul 2021) by Junio C Hamano (gitster).
See commit b9dee07, commit e85fcb3, commit 7121c4d, commit bd0708c, commit 311d0b8 (26 Jul 2021) by ZheNing Hu (adlternative).
(Merged by Junio C Hamano -- gitster -- in commit bda891e, 24 Aug 2021)

ref-filter: add %(rest) atom
Reviewed-by: Jacob Keller
Suggected-by: Jacob Keller
Mentored-by: Christian Couder
Mentored-by: Hariom Verma
Signed-off-by: ZheNing Hu

%(rest) is a atom used for cat-file batch mode, which can split the input lines at the first whitespace boundary, all characters before that whitespace are considered to be the object name; characters after that first run of whitespace (i.e., the "rest" of the line) are output in place of the %(rest) atom.
In order to let "cat-file --batch=%(rest)" use the ref-filter interface, add %(rest) atom for ref-filter.
Introduce the reject_atom() to reject the atom %(rest) for "git for-each-ref"(man), "git branch"(man), "git tag"(man) and git verify-tag".

So both command should return the same result:
git cat-file commit refs/tags/testtag^{} >expected &&
git for-each-ref --format="%(*raw)" refs/tags/testtag

basic atom: refs/tags/testtag *raw

Same for:
git rev-parse refs/mytrees/first | git cat-file --batch >expected &&
git for-each-ref --format="%(objectname) %(objecttype) %(objectsize)%(raw)" refs/mytrees/first

Note that with Git 2.36 (Q2 2022), "git cat-file --help"(man) is clearer.
See commit 5fb2490, commit 83dc443 (10 Jan 2022), and commit 245b948, commit 9ce6000, commit 57d6a1c, commit b3fe468, commit 485fd2c, commit 5a40417, commit 97fe725, commit fa476be, commit 68c69f9, commit ddf8420 (28 Dec 2021) by Ævar Arnfjörð Bjarmason (avar).
(Merged by Junio C Hamano -- gitster -- in commit 008028a, 05 Feb 2022)

cat-file: correct and improve usage information
Signed-off-by: Ævar Arnfjörð Bjarmason

Change the usage output emitted on "git cat-file"(man) -h to group related options, making it clear to users which options go with which other ones.
The new output is:
Check object existence or emit object contents
    -e                    check if <object> exists
    -p                    pretty-print <object> content

Emit [broken] object attributes
    -t                    show object type (one of 'blob', 'tree', 'commit', 'tag', ...)
    -s                    show object size
    --allow-unknown-type  allow -s and -t to work with broken/corrupt objects

Batch objects requested on stdin (or --batch-all-objects)
    --batch[=<format>]    show full <object> or <rev> contents
    --batch-check[=<format>]
                          like --batch, but don't emit <contents>
    --batch-all-objects   with --batch[-check]: ignores stdin, batches all known objects

Change or optimize batch output
    --buffer              buffer --batch output
    --follow-symlinks     follow in-tree symlinks
    --unordered           do not order objects before emitting them

Emit object (blob or tree) with conversion or filter (stand-alone, or with batch)
    --textconv            run textconv on object's content
    --filters             run filters on object's content
    --path blob|tree      use a <path> for (--textconv | --filters ); Not with 'batch'

The old usage was:
<type> can be one of: blob, tree, commit, tag
    -t                    show object type
    -s                    show object size
    -e                    exit with zero when there's no error
    -p                    pretty-print object's content
    --textconv            for blob objects, run textconv on object's content
    --filters             for blob objects, run filters on object's content
    --batch-all-objects   show all objects with --batch or --batch-check
    --path <blob>         use a specific path for --textconv/--filters
    --allow-unknown-type  allow -s and -t to work with broken/corrupt objects
    --buffer              buffer --batch output
    --batch[=<format>]    show info and content of objects fed from the standard input
    --batch-check[=<format>]
                          show info about objects fed from the standard input
    --follow-symlinks     follow in-tree symlinks (used with --batch or --batch-check)
    --unordered           do not order --batch-all-objects output

While shorter, I think the new one is easier to understand, as e.g. "--allow-unknown-type" is grouped with "-t" and "-s", as it can only be combined with those options.
The same goes for "--buffer", "--unordered" etc.

Still with Git 2.36 (Q2 2022), optimize away strbuf_expand() call with a hardcoded formatting logic specific for the default format in git the --batch and --batch-check options of cat-file".
See commit eb54a33 (15 Mar 2022) by John Cai (john-cai).
(Merged by Junio C Hamano -- gitster -- in commit 889860e, 23 Mar 2022)

cat-file: skip expanding default format
Signed-off-by: Ævar Arnfjörð Bjarmason
Signed-off-by: John Cai

When format is passed into --batch, --batch-check, --batch-command, the format gets expanded.
When nothing is passed in, the default format is set and the expand_format() gets called.
We can save on these cycles by hardcoding how to print the information when nothing is passed as the format, or when the default format is passed.
There is no need for the fully expanded format with the default.
Since batch_object_write() happens on every object provided in batch mode, we get a nice performance improvement.
git rev-list --all > /tmp/all-obj.txt

git cat-file --batch-check </tmp/all-obj.txt

with HEAD^:
Time (mean ± σ): 57.6 ms ± 1.7 ms [User: 51.5 ms, System: 6.2 ms]
Range (min … max): 54.6 ms … 64.7 ms 50 runs

with HEAD:
Time (mean ± σ): 49.8 ms ± 1.7 ms [User: 42.6 ms, System: 7.3 ms]
Range (min … max): 46.9 ms … 55.9 ms 56 runs

If nothing is provided as a format argument, or if the default format is passed, skip expanding of the format and print the object info with a default format.
See this discussion.

Another difference between git cat-files and cat: mail-mapping: the ability to map author/committer names and/or E-Mail addresses.
With Git 2.38 (Q3 2022), "git cat-file"(man) has learned an option to use the mailmap when showing commit and tag objects.
See commit ec031da, commit 66a8a95, commit dc88e34, commit e9c1b0e (19 Jul 2022) by Siddharth Asthana (edith007).
(Merged by Junio C Hamano -- gitster -- in commit 87098a0, 03 Aug 2022)

cat-file: add mailmap support
Mentored-by: Christian Couder
Mentored-by: John Cai
Helped-by: Phillip Wood
Helped-by: Johannes Schindelin
Signed-off-by: Siddharth Asthana

git-cat-file(man) is used by tools like GitLab to get commit tag contents that are then displayed to users.
This content which has author, committer or tagger information, could benefit from passing through the mailmap mechanism before being sent or displayed.
This patch adds --[no-]use-mailmap command line option to the git cat-file command.
It also adds --[no-]mailmap option as an alias to --[no-]use-mailmap.

git cat-file now includes in its man page:

--[no-]mailmap
--[no-]use-mailmap
Use mailmap file to map author, committer and tagger names
and email addresses to canonical real names and email addresses.
See git shortlog.

In that context, Git 2.40 (Q1 2023) adds: 'cat-file' gains mailmap support for its '--batch-check' and '-s' options.
See commit a797c0e, commit 49050a0 (20 Dec 2022) by Siddharth Asthana (edith007).
(Merged by Junio C Hamano -- gitster -- in commit 319c3ab, 05 Jan 2023)

cat-file: add mailmap support to -s option
Mentored-by: Christian Couder
Mentored-by: John Cai
Helped-by: Taylor Blau
Helped-by: Ævar Arnfjörð Bjarmason
Signed-off-by: Siddharth Asthana

Even though the cat-file command with -s option does not complain when --use-mailmap option is given, the latter option is ignored.
Compute the size of the object after replacing the idents and report it instead.
In order to make -s option honour the mailmap mechanism we have to read the contents of the commit/tag object.

git cat-file now includes in its man page:

<object>. If used with --use-mailmap option, will show
the size of updated object after replacing idents using the
mailmap mechanism.

And:

cat-file: add mailmap support to --batch-check option
Mentored-by: Christian Couder
Mentored-by: John Cai
Helped-by: Taylor Blau
Helped-by: Ævar Arnfjörð Bjarmason
Signed-off-by: Siddharth Asthana

Even though the cat-file command with --batch-check option does not complain when --use-mailmap option is given, the latter option is ignored.
Compute the size of the object after replacing the idents and report it instead.
In order to make --batch-check option honour the mailmap mechanism we have to read the contents of the commit/tag object.
git cat-file --use-mailmap --batch-all-objects --batch-check --buffer --unordered

The command git cat-file can now use the mailmap mechanism to replace idents with canonical versions for commit and tag objects.
There are several options like --batch, --batch-check and --batch-command that can be combined with --use-mailmap.
But the documentation for --batch, --batch-check and --batch-command doesn't say so.
This patch fixes that documentation.

git cat-file now includes in its man page:

on stdin. May not be combined with any other options or arguments
except --textconv, --filters, or --use-mailmap.

*

*When used with --textconv or --filters, the input lines
must specify the path, separated by whitespace. See the section
BATCH OUTPUT below for details.

*When used with --use-mailmap, for commit and tag objects, the
contents part of the output shows the identities replaced using the
mailmap mechanism, while the information part of the output shows
the size of the object as if it actually recorded the replacement
identities.

A: add to @Matoeil answer,
You only need to specify 5 characters of your <SHA1>.
$ tree .git/

.git/
├── COMMIT_EDITMSG
├── HEAD
├── config
├── description
├── hooks
│   ├── applypatch-msg.sample
│   ├── commit-msg.sample
│   ├── fsmonitor-watchman.sample
│   ├── post-update.sample
│   ├── pre-applypatch.sample
│   ├── pre-commit.sample
│   ├── pre-push.sample
│   ├── pre-rebase.sample
│   ├── pre-receive.sample
│   ├── prepare-commit-msg.sample
│   └── update.sample
├── index
├── info
│   └── exclude
├── logs
│   ├── HEAD
│   └── refs
│       └── heads
│           ├── master
│           └── testBranch
├── objects
│   ├── 1e
│   │   └── e2a78c0b40dd8e5c6b08e31171a3ce1e8d931b
│   ├── 29
│   │   └── 33b9017f79a27ff5ad3c4e154f67b44ae8482c
│   ├── 4a
│   │   └── 6a376085b9b3b8e6e73d2cdcc5281cf6915c58
│   ├── 4b
│   │   └── 825dc642cb6eb9a060e54bf8d69288fbee4904
│   ├── 7e
│   │   └── 6965a8b2ff07da3e632a24ee024b9d2ec5245d
│   ├── ae
│   │   └── 853f7ece778281c463c1f0c603ef9d47a425b7
│   ├── info
│   └── pack
└── refs
├── heads
│   ├── master
│   └── testBranch
└── tags

17 directories, 28 files

$ git cat-file -t ae853
tree

$ git cat-file -p ae853
100644 blob 7e6965a8b2ff07da3e632a24ee024b9d2ec5245d    fil1.txt

here explain very well.

A: git cat-file - The Cat(concatenate) command It reads data from the file and outputs the contents.


text:
Q: Cannot convert from Type* to Type&& I have a simple class and I am using a std::vector to contain all of the instances of that class.  However when I do:
std::vector<MyType> v;
MyType m(1, 2, 3);
v.push_back(m);

Or if I do:
v.push_back(new MyType(1, 2, 3);

I get this error:
error C2664: 'void std::vector<_Ty>::push_back(_Ty &&)' : cannot convert parameter 1 from 'MyType *' to 'MyType &&'

And if it is important, here my MyType code:
class MyType
{
public:
  int a;
  int b;
  float c;

MyType(int A, int B, float C)
{
    a = A;
    b = B;
    c = C;
}
};

I don't understand what is going wrong.
EDIT: My original (first snippet) of code works. For whatever reason I had to rebuild the solution and afterwards it compiled fine.

A: In your code, MyType is a type, while m is an object, so new m(1,2,3) doesn't even make sense.
Write:
v.push_back(MyType(1, 2, 3)); //without new

Instead of push_back, you could also use emplace_back as :
v.emplace_back(1,2,3); //note there is no `MyType` now

emplace_back is preferable.


text:
Q: I want my carousel to be appeared in index page only in rails application I am new to rails and I want my carousel code to be seen in the index page only,please give a solution and below is my code :

  <%= render 'layouts/navigation'%>
  <%= render 'layouts/carousel' %>
  <%= render 'layouts/messages'%>

      <%= yield %>

A: Normally you'd want the move any code that's specific to a page out of the layout and into the template for the appropriate action.
However, in your case that piece of code looks embedded within the rest of the page skeleton so it could be hard to refactor it that way.
For this reason I'd suggest using conditional rendering by simply using a Boolean variable.
For example you could do:
<%= render 'layouts/carousel' if @render_carousel %>

And then you could just set the @render_carousel variable to true for any action that you'd want the carousel to appear in, e.g.:
def index
    # rest of the code
    @render_carousel = true
end