text:
Q: Drag and drop imagebuttons having issues with onDrag I am developing an android app where the user can purchase buildings that are imagebuttons that implement the drag and drop api. My issue is that when the user buys two buildings, say colonyHutOne and colonyHutTwo, there is an issue with the x and y coordinates being saved in the onDrag. In my onDrag I pass in which building number in the onDragListener so i know what building i am dealing with in the onDrag class. This way i can save the coordinates to the appropriate building. The problem is that no matter what building number i pass into the onDrag, the most recently created building is the one that takes the coordinates. In the onDrag, it receives building number two every time even when its the first building that is being dragged (which is building number one). I have no idea if this has something to do with context that is passed to the onDrag or if it is because the onDragListeners are declared before the drag is made so it just takes the last created imagebutton. I have no idea how to get past this issue. Please help.
Here is the code for setting the on Drag listener of both buildings:
findViewById(R.id.topHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 1));
findViewById(R.id.bottomHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 1));
FrameLayout.LayoutParams  param1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
newColonyHutFrame.addView(newColonyHutOne, param1);

findViewById(R.id.topHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 2));
findViewById(R.id.bottomHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 2));
FrameLayout.LayoutParams  param1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
newColonyHutFrame.addView(newColonyHutTwo, param1);

Here is the onDrag class:
public class ColonyHutDrag implements OnDragListener
{
    SharedPreferences prefs;
    Context passedContext;
    Database data;
    int buildingNum = 0;

    public ColonyHutDrag(Context applicationContext, int num)
    {
        passedContext = applicationContext;
        buildingNum = num;
    }//end constructor

    @Override
    public boolean onDrag(View v, DragEvent event)
    {
        float x = 0, y = 0;
        switch(event.getAction())
        {
        case DragEvent.ACTION_DRAG_STARTED:
            //drag has started
            break;

        case DragEvent.ACTION_DRAG_ENTERED:
            //being dragged
            break;

        case DragEvent.ACTION_DRAG_EXITED:
            //stop drag
            break;

        case DragEvent.ACTION_DRAG_LOCATION:
            //find drag location
            break;

        case DragEvent.ACTION_DROP:
            if (v == v.findViewById(R.id.bottomHalf))
            {
                //find position where dropped
                x = event.getX();
                y = event.getY();

                //save the coordinates that the building was dropped at
                data = new Database(passedContext);
                data.open();
                if (buildingNum == 1)
                {
                    data.colonyHutOneXEntry(x);
                    data.colonyHutOneYEntry(y);
                    Toast.makeText(passedContext, "Going in1 -> x: " + x + " y: " + y, Toast.LENGTH_SHORT).show();
                }//end if
                else if (buildingNum == 2)
                {
                    data.colonyHutTwoXEntry(x);
                    data.colonyHutTwoYEntry(y);
                    Toast.makeText(passedContext, "Going in2 -> x: " + x + " y: " + y, Toast.LENGTH_SHORT).show();
                }//end else if

                data.close();

                //use this to fix building loadup glitch
                View view = (View) event.getLocalState();
                ViewGroup group = (ViewGroup) view.getParent();
                group.removeView(view);
                FrameLayout contain = (FrameLayout) v;
                contain.addView(view);
                view.setX(x - (view.getWidth()/2));
                view.setY(y - (view.getHeight()/2));
                view.setVisibility(View.VISIBLE);
            }//end if
            else
            {
                View view = (View) event.getLocalState();
                view.setVisibility(View.VISIBLE);
            }//end else
            break;

        default:
            break;
        }//end switch
        return true;
    }//end onDrag function
}//end ColonyHutOneDrag class

Here is the onTouchlistener for the drag and drop:
public class BuildingsClick implements OnTouchListener
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());

        String[] mimeTypes = { ClipDescription.MIMETYPE_TEXT_PLAIN };
        ClipData data = new ClipData(v.getTag().toString(), mimeTypes, item);
        DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);

        v.startDrag(data, shadowBuilder, v, 0);
        v.setVisibility(View.INVISIBLE);

        return false;
    }//end onTouch function

}//end BuildingsClick class

I really appreciate any help. I have no idea how to fix the problem. It is almost like since the second building is being dealt with, then the first one can no longer be referenced.
Thanks guys.
Edit:
Code in BuildingsClick class
//find which building is being dragged
if (v.getTag() == "NewColonyHutOne")
{
    ColonyHutDrag.setType(ColonyHutOneDrag.getType());
}//end if
else if (v.getTag() == "NewColonyHutTwo")
{
    ColonyHutDrag.setType(ColonyHutTwoDrag.getType());
}//end if

Code for ColonyHutOneDrag class:
public class ColonyHutOneDrag extends ColonyHut
{

    @Override
    public int getType()
    {
        return 1;
    }//end getType

}//end ColonyHutOneDrag

The code for the ColonyHutTwoDrag class is the same as the first one but returns 2.
This is the getType in ColonyHutDrag:
public void setType(int type)
{
    buildingNum = type;
}//end setType

A: You are incorrectly as assigning the OnDragListeners again.
You can't
findViewById(R.id.topHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 1));
findViewById(R.id.bottomHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 1));
FrameLayout.LayoutParams  param1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);

and then
findViewById(R.id.topHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 2));
findViewById(R.id.bottomHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext(), 2));
FrameLayout.LayoutParams  param1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);

The reason is because your second call overwrites your first, and you never listen for hut type of 1 to be dragged, because you passed which hut you are listening for in your constructor.
The solution to this is to change your assignment of the listener, like so:
findViewById(R.id.topHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext()));
findViewById(R.id.bottomHalf).setOnDragListener(new ColonyHutDrag(getApplicationContext());
FrameLayout.LayoutParams  param1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);

We're going to make an abstract class ColonyHut, and define public int getType();.
Get rid of your constructor for ColonyHutListener as well, we won't need that. Then you're going to make a class called ColonyHutOne, if you don't already have one. With that class, you're going to want to extend ColonyHut, and define getType() like so:
public int getType()
{
    return 1;
}

Then we'll define a function in your ColonyHutDrag class, called setType() like so:
public void setType(int type)
{
    buildingNum = type;
}

After that you're going to want to get the ColonyHutOne as a ColonyHut, like so ColonyHut currentlySelectedHut = view.getHutFromView() in your onTouchListener, and call colonyHutDrag.setType(currentlySelectedHut.getType()) before v.startDrag() and it should work. Do the same for ColonyHutTwo, except obviously then you should make getType() return 2.
I'll leave defining view.getHutFromView(), and making colonyHutDrag visible in your BuildingsClick class. After all EVERYTHING can't be a free-be :-).


text:
Q: How can I trace rules in the Business Rules service on Bluemix? I am using the Business Rules service on Bluemix, and it does not seem to use the Decision Warehouse. Is there another way to trace the rule firing?

A: As you noticed, the Decision Warehouse is not a feature within the Business Rules service. Also, rule traces are disabled.
You can add trace filter tags to the payload request. Use the REST form (&trace=true) to view the trace filter tags:

https://brsv2-instanceID.domain/DecisionService/run.jsp?path=/ruleApp/1.0/ruleset/1.0&trace=true

(You can get the values for instanceID, domain, ruleApp, ruleset and the corresponding versions from the "URL" in the Ruleset Details page.)
If you work with XML, choose the XML option, in which case the generated payload will contain filter tags such as:
 <!--Optional:-->
 <trac:all>false</trac:all>
 <!--Optional:-->
 <trac:none>true</trac:none>
 <!--Optional:-->
 <trac:executionDuration>true</trac:executionDuration>
 <!--Optional:-->
 <trac:executionDate>true</trac:executionDate>

If you work with JSON, choose the JSON option instead. The generated payload will contain filter entries, for example:

 "_TraceFilter_":{
  "infoRulesetProperties":true,
  "infoOutputString":false,
  "infoInputParameters":false,
  "infoOutputParameters":true,
  ...

Add these tags/entries with the appropriate filter enabled in the execution request. The payload response will contain the requested traces.
Another way is to enable the Decision trace information when getting the WSDL or WADL. See the documentation at "Decision trace information" in the IBM ODM documentation at "IBM Operational Decision Manager 8.7.0>Operational Decision Manager 8.7> Decision Server Rules>Rule Execution Server console online help>Viewing and managing transparent decision services>Viewing or downloading an HTDS description file", Step 6 and collect the execution information on the client side.

redpajama_set_name: RedPajamaStackExchange


text:
Q: App freeze the OS Good afternoon, I have a question.
We have an "alarm monitor" (called DIVERA247) in our fire brigade, where various details of the incoming operation are displayed.
Now I have the problem that the monitor hangs daily and the screen freezes. So the clock also stops, at first I thought it was the mouse/keyboard, but I can probably rule that out.
In the energy settings, switching off the monitor etc. was switched off, as the monitor should always be in operation.
Ubuntu Desktop 22.04.2 LTS is installed on a BMAX B2.
Now I am not so experienced in Linux, can I read out an error log somewhere? I cant find it.
Or where would it make sense to look?
The Problem exist only by Running this App.


text:
Q: condition on javascript if json_encode contains a character from a database query I am creating a restriction of buttons for my page that will be based on database. I could use the json_encode if a cell is == A .
But I would like to validate if the json result contains a letter A on it.
database :
| id | Config  |
| 02| ABCD  |
please see my current code below
on my restriction.php page
if($client >= 0){
$data = $con->query("SELECT Config FROM data WHERE id = ".$userid." limit 1;");
$configuration_data = $data->fetch_assoc();
}
echo '<script>window.configuration_data = '.json_encode ($configuration_data).'</script>';

on my config.js this code validates only if the result is A but i would like if the cell has a letter A on it
if(window.configuration_data.Config == "A"){
  $('.Modify').hide();
}

A: Check if the string contains the "A" character.
if(window.configuration_data.Config.indexOf("A") != -1){
  $('.Modify').hide();
}

A:

window.configuration_data = {"Config":"ABCD"};
if(window.configuration_data.Config.indexOf('A') > -1) {
  console.log('hide .Modify here')
  //$('.Modify').hide();
}

A: You can use mysql LIKE clause, LIKE '%A%'
$data = $con->query("SELECT Config FROM data WHERE id = ".$userid." AND Config LIKE '%A%' limit 1;");
This query only return value if Config cell has letter A on value.
Or you can use JavaScript to compare substring like:
var string = window.configuration_data.Config,
substring = "A";
string.indexOf(substring) !== -1;`

Using search or RexEx you can achive this too.
var string = "foo",
    expr = /oo/;
string.search(expr);

var string = "foo",
    expr = /oo/;
expr.test(string);


text:
Q: Reading a label from input file that can be in a random order and assigning to variables I am trying to create a program that will read a user given input file and assign values to some variables in the code for a school project.
Here are a couple input file examples:
a 3
b 4
c 5
? equilateral

? equilateral
a 8
c 6
b 8

These input files can have the four items in any order, but I can't figure out how to read the label in the input file and assign it to my variables that I've assigned. I have to use an if-then-else-if to decide which label needs to be read, and the code should be able to be copied 3 times so that there is no modification needed to read every label and assign the variables.
#include <iostream>
#include <cmath>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

int main()
{
  string filename, guess;
  double a, b, c;

  cout << "Opening input file: " << filename;
  cin << filename;
  fstream InFile;
  InFile.open(filename.c_str());
  if(InFile.fail())
  {
    cout << string(15,'*') << " File Open Error " << string(15,'*') << endl;
    cout << "==> Input file failed to open properly!!\n";
    cout << "==> Attempted to open file: " << filename << endl;
    cout << "==> Terminating program!!!\n";
    cout << string(47,'*') << endl << endl;
     return 1;
  }

  if()
  {

  }
  else if()
  {

  }
  else if()
  {

  }
  else
  {

  }

  cout << "\nReading Values From Input File..." << endl;
  cout << "Summary of Data Read..." << endl;
  cout << "Side A = " << a << endl;
  cout << "Side B = " << b << endl;
  cout << "Side C = " << c << endl;
  cout << "Guess  = " << guess << endl;

  InFile.close();
  return 0;
}

Any Help is greatly appreciated!

A: I'll assume equilateral is the only valid type (thus there can only be 3 sides), also that the user input is always valid (eg.: No side is missing, etc)
With this the solution becomes pretty simple:
#include <iostream>
#include <fstream>

int main() {
    std::ifstream InFile("input.txt");

    // Assume there are no trailing new-lines, and what not

    double a, b, c;
    do {
        char chr;
        InFile.read(&chr, 1); // Read first char on line

        // If we were doing error checking here it should be checked if `InFile.valid()` (Otherwise `chr` won't have a valid value)
        std::cout << "Read:" << c << '\n';
        switch (chr) {
        case '?':
            break; // Ignore this, nothing to do
        case 'a':
            InFile >> a;
            break;
        case 'b':
            InFile >> b;
            break;
        case 'c':
            InFile >> c;
            std::cout << "case c: " << c << '\n';
            break;
        default:
            break; // If this point is reached something was invalid
        }

        InFile.ignore(10000, '\n'); // Ignore up to next new line charcter
    } while (InFile.good());

    std::cout
        << "a = " << a
        << "; b = " << b;
        << "; c = " << c;

}

There's quite a lot of error checking it's missing, but that's fine, its supposed to show how it can be done.


text:
Q: Best option for 3D scatterplot with different plot symbols I would like to make a 3D scatterplot with different shape symbols to represent different categories of data. In 2D, this is straightforward using the pch argument in the plot function, and I would like to extend it to the rgl plot3d function
However, as discussed in this thread,
rgl: plot3d with "extended" plotting symbols
rgl::plot3d returns a single symbol regardless of pch argument, while pch3d doesn't embed the symbols in 3d axes. The best option suggested in the thread uses text3d and generates a 3D plot with no axes labels, e.g. for all_symbol a vector of n1 0's, n2 1's, n3 2's etc
library(rgl)
rgl::open3d()
for(i in 1:49){
    rgl::text3d(scores.df$PC1[i], scores.df$PC2[i], scores.df$PC3[i], text = intToUtf8(all_symbol[i]), cex = 2, usePlotmath = TRUE)
}
rgl::box3d()

generates no axes labels or tick marks.
Is there some graphics library that will give me the same basic 3d plotting functionality of rgl while allowing me to do the rather straightforward tasks such as using symbols for classes of data and labeling axes?

A: Don't use box3d(), use decorate3d() if you want axes with labels.  You didn't include any data in your question, so I'll illustrate with fake data:
library(rgl)
fake <- matrix(rnorm(3*49), ncol = 3)
open3d()
pch3d(fake, pch = 1:49, cex = 0.3)
decorate3d()

A: I just came across another package, scatterplot3D which seems to make this type of scatterplot very straightforward:
http://www.sthda.com/english/wiki/scatterplot3d-3d-graphics-r-software-and-data-visualization


text:
Q: Does removefromsuperview remove subviews? If I have nested subviews, will all subviews get disposed if i call removefromsuperview?
Pseudocode:
UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(0 , 0, 100, 100)];
[self.view addSubview:viewA];
UIView *viewB = [[UIView alloc] initWithFrame:CGRectMake(25 , 25, 50, 50)];
[viewA addSubview:viewB];
UIButton *buttonC = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[viewB addSubview:buttonC];

And then buttonC is pressed:
[viewA removeFromSuperView];

All views are removed from the screen, but are they removed properly?
Do I need to remove all views manually?

A: All views will be removed. If you maintain a strong reference to viewA then all of the views will still be there and can be added again later. If you don't, they will all be destroyed.

A: As long as you have no other references to your views A..C, they will be removed and destroyed

A: You can check it easy. Create subclass of uiview, overide it dealloc method and set brakepoint there. Than create instance of this class and add it to your view as subview.
When you`ll call removeFromSuperview in your view brakepoint will be activated.
That`s it.


text:
Q: Why doesn't max-width override min-width? I'm trying to create a responsive layout in which two boxes sit next to each other if the screen size allows it, and have them below each other if it doesn't. If the boxes are below each other, I'd like them to be centred to their parent. I've set up a jsfiddle to demonstrate the problem:
http://jsfiddle.net/leongersen/KsU23/
width: 50%;
min-width: 350px;
max-width: 100%;

Try resizing the 'result' pane to below 350px. The elements will overlap their parent.
My question:
Why isn't the specified max-width honoured, even though it comes after the min-width?

A: Because of the CSS standards:

The following algorithm describes how the two properties influence the
  used value of the 'width' property:

*

*The tentative used width is calculated (without 'min-width' and
  'max-width') following the rules under "Calculating widths and
  margins" above.

*If the tentative used width is greater than
  'max-width', the rules above are applied again, but this time using
  the computed value of 'max-width' as the computed value for 'width'.

*If the resulting width is smaller than 'min-width', the rules above
  are applied again, but this time using the value of 'min-width' as
  the computed value for 'width'.

As such min-width always 'wins'. Within a specific CSS rule there's no precedence anyway, all values are applied atomically. Precedence only occurs when different rules all apply to the same element, and even then it is based on specificity first before file order is considered.

A: I know, I'm late ...
But one exact solution could be this:
p {
    display: inline-block;
    font-size: 15px;
    text-align: left;
    width: 50%;
    border: 1px solid blue;
    min-width: 350px;
}
@media (max-width: 700px) {
  p {
    width:100%;
    display:block;
  }
}


text:
Q: TensorFlow Classification I used TensorFlow to train a model that could identify 8 categories.I want to train on the basis of the original model and increase the category to 10.I don't want to train from scratch. What should I do?Thank you!

A: What you can do is change the output layer to 10 categories, and set the checkpoint file as the one you used for 8 categories. Then you continue training from that point on. You can research on "transfer learning" regarding this.


text:
Q: When I browse to user profiles, SharePoint tells me that there are profiles but doesn't list any of them When I navigate to the User Profile service and click "Manage User Profiles," Sharepoint tells me there are 11 profiles.  But none are listed and searches do not appear to return results.
I am having sync issues, but I don't see where that should matter.  After all, there are already 11 profiles on SharePoint.  Shouldn't I be able to see them?
On another install, I added a user profile manually.  It shows a count of 1 but doesn't actually list any profiles.
Really confused by this

A: What version of SharePoint are you using?
If SharePoint 2010, you can use the following method to view list of all users.

*

*Open central administration, click manage service applications under service applications,

*Click user profile service application, then click manage user profiles,

*Type your exact domain name in the textbox after "find profile", then click find.

*Check the effect.

For more information on User Profile Service administration, see http://technet.microsoft.com/en-us/library/ee721050.aspx.

A: Are you using Active Directory groups?
If you are then the user profile information will not show individual users from the AD group until they have contributed to the site.


text:
Q: SPARK: Load Data from Dataframe or RDD to DynamoDB / dealing with null values I am using spark 2.1 on EMR and i have a dataframe like this:
 ClientNum  | Value_1  | Value_2 | Value_3  | Value_4
     14     |    A     |    B    |   C      |   null
     19     |    X     |    Y    |  null    |   null
     21     |    R     |   null  |  null    |   null

I want to load data into DynamoDB table with ClientNum as key fetching:
Analyze Your Data on Amazon DynamoDB with Apache Spark
Using Spark SQL for ETL
here is my code that I tried to solve:
  var jobConf = new JobConf(sc.hadoopConfiguration)
  jobConf.set("dynamodb.servicename", "dynamodb")
  jobConf.set("dynamodb.input.tableName", "table_name")
  jobConf.set("dynamodb.output.tableName", "table_name")
  jobConf.set("dynamodb.endpoint", "dynamodb.eu-west-1.amazonaws.com")
  jobConf.set("dynamodb.regionid", "eu-west-1")
  jobConf.set("dynamodb.throughput.read", "1")
  jobConf.set("dynamodb.throughput.read.percent", "1")
  jobConf.set("dynamodb.throughput.write", "1")
  jobConf.set("dynamodb.throughput.write.percent", "1")

  jobConf.set("mapred.output.format.class", "org.apache.hadoop.dynamodb.write.DynamoDBOutputFormat")
  jobConf.set("mapred.input.format.class", "org.apache.hadoop.dynamodb.read.DynamoDBInputFormat")

  //Import Data
  val df = sqlContext.read.format("com.databricks.spark.csv").option("header", "true").option("inferSchema", "true").load(path)

I performed a transformation to have an RDD that matches the types that the DynamoDB custom output format knows how to write.  The custom output format expects a tuple containing the Text and DynamoDBItemWritable types.
Create a new RDD with those types in it, in the following map call:
  //Convert the dataframe to rdd
  val df_rdd = df.rdd
  > df_rdd: org.apache.spark.rdd.RDD[org.apache.spark.sql.Row] = MapPartitionsRDD[10] at rdd at <console>:41

  //Print first rdd
  df_rdd.take(1)
  > res12: Array[org.apache.spark.sql.Row] = Array([14,A,B,C,null])

  var ddbInsertFormattedRDD = df_rdd.map(a => {
  var ddbMap = new HashMap[String, AttributeValue]()

  var ClientNum = new AttributeValue()
  ClientNum.setN(a.get(0).toString)
  ddbMap.put("ClientNum", ClientNum)

  var Value_1 = new AttributeValue()
  Value_1.setS(a.get(1).toString)
  ddbMap.put("Value_1", Value_1)

  var Value_2 = new AttributeValue()
  Value_2.setS(a.get(2).toString)
  ddbMap.put("Value_2", Value_2)

  var Value_3 = new AttributeValue()
  Value_3.setS(a.get(3).toString)
  ddbMap.put("Value_3", Value_3)

  var Value_4 = new AttributeValue()
  Value_4.setS(a.get(4).toString)
  ddbMap.put("Value_4", Value_4)

  var item = new DynamoDBItemWritable()
  item.setItem(ddbMap)

  (new Text(""), item)
  })

This last call uses the job configuration that defines the EMR-DDB connector to write out the new RDD you created in the expected format:
ddbInsertFormattedRDD.saveAsHadoopDataset(jobConf)

fails with the follwing error:
Caused by: java.lang.NullPointerException

null values caused the error, if I try with ClientNum and Value_1 it works data is correctly inserted on DynamoDB table.


text:
Q: Combinatorics and Latin squares Let's have two Latin squares, in this case, the two which are shown in this question.
If we superimpose them we get 34 different combinations, with two repetitions, namely 4B and 1E. Can someone find two Latin squares, which when superimposed have fewer than two repetitions?

A: Neither B1 nor E4 appear at all, as a result of B4 and E1 appearing twice. One of the two coordinates for each pair has been permuted with the other pair. Since repeating that permutation would return the original pairs, it is of order 2.
Since the shortest odd permutation that is not identical is order 3, and a permutation identical to a Graeco-Latin square of order 6 is impossible, you cannot make a square that has fewer repeated pairs (or missed pairs) than shown.


text:
Q: Get Vim on Mac terminal to copy to the clipboard I'm using Vim on a Mac, installed via homebrew, version 8.0.
Vim --version shows +clipboard, and -xterm_clipboard.
I've tried
 set clipboard=unnamed

in .vimrc
But I cannot get yanks to go on to the system clipboard. What do I do?

A: It should "just work" on MacVim. One of the reasons I'm using it is for its OSX integration, including clipboard.
brew install macvim
mvim defaults to graphical mode. To run it in terminal mode:
mvim -v
In the past, I had an alias for vim -> mvim -v which handles most cases. These days I use the following script in ~/bin/vim, which is in my $PATH:
#!/bin/bash
mvim -v "$@"

A: seems like something is overriding your clipboard setting after loading your vimrc.
try :verbose set clipboard?. It should tell you when and where this variable was last set.
This guide gives you a bunch of hints on what to do to figure out what's going on and fix the problem


text:
Q: C function for combining an array of strings into a single string in a loop and return the string after freeing the allocated memory I'm working on a procfs kernel extension for macOS and trying to implement a feature that emulates Linux's /proc/cpuinfo similar to what FreeBSD does with its linprocfs. Since I'm trying to learn, and since not every bit of FreeBSD code can simply be copied over to XNU and be expected to work right out of the jar, I'm writing this feature from scratch, with FreeBSD and NetBSD's linux-based procfs features as a reference. Anyways...
Under Linux, $cat /proc/cpuinfo showes me something like this:
processor       : 0
vendor_id       : AuthenticAMD
cpu family      : 25
model           : 33
model name      : AMD Ryzen 9 5950X 16-Core Processor
stepping        : 0
microcode       : 0xa201016
cpu MHz         : 2195.107
cache size      : 512 KB
physical id     : 0
siblings        : 32
core id         : 0
cpu cores       : 16
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 16
wp              : yes
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca
bugs            : sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass
bogomips        : 6787.02
TLB size        : 2560 4K pages
clflush size    : 64
cache_alignment : 64
address sizes   : 48 bits physical, 48 bits virtual
power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14]

I'm using XNU's i386_cpu_info structure in i386/cpuid.h to accomplish most of this, but so far I have not been able to get the 'flags' field to display correctly.
XNU's i386/cpuid.h defines each feature flag as such:
#define CPUID_FEATURE_FPU       _Bit(0)   /* Floating point unit on-chip */
#define CPUID_FEATURE_VME       _Bit(1)   /* Virtual Mode Extension */
#define CPUID_FEATURE_DE        _Bit(2)   /* Debugging Extension */
#define CPUID_FEATURE_PSE       _Bit(3)   /* Page Size Extension */
#define CPUID_FEATURE_TSC       _Bit(4)   /* Time Stamp Counter */
...

And the i386_cpu_info structure has a field that should correspond to these definitions:
typedef struct i386_cpu_info {
    ...
    uint64_t        cpuid_features;
    ...
}

In my 'main' do_cpuinfo() function, for example, I use one of these to check if the FPU feature is supported, as such:
/*
 * Check if the FPU feature is present.
 */
char *fpu, *fpu_exception;

 /*
  * The cpuid_info() function sets up the i386_cpu_info structure and returns a pointer to the structure.
  */
if (cpuid_info()->cpuid_features & CPUID_FEATURE_FPU) {
    fpu = "yes";
    fpu_exception = "yes";
} else {
    fpu = "no";
    fpu_exception = "no";
}

And it works just as expected. However once I start adding arrays into the mix, things start getting erratic.
I set up a char array containing the string for each flag as such:
const char *feature_flags[] = {
    /* 1 */  "fpu",
    /* 2 */  "vme",
    /* 3 */  "de",
    /* 4 */  "pse",
    /* 5 */  "tsc",
    …
}

Then set up a correspnding uint64_t array containing each flag as defined in i386/cpuid.h:
uint64_t feature_list[] = {
    /* 1 */  CPUID_FEATURE_FPU,
    /* 2 */  CPUID_FEATURE_VME,
    /* 3 */  CPUID_FEATURE_DE,
    /* 4 */  CPUID_FEATURE_PSE,
    /* 5 */  CPUID_FEATURE_TSC,
    …
}

Then I wrote a function that is supposed to iterate over these arrays to check if a feature is present with the same method I used for the FPU detection, but instead of doing something like "cpuid_info()->cpuid_features & CPUID_FEATURE_FPU" for each flag, I want cpuid_info()->cpuid_features to get each flag from the feature_list array and, if supported, copy it to the flags variable, move the resulting string to the static ret variable, so we can then free the allocated memory and return ret.
char *
get_cpu_flags(void)
{
    int i = 0;
    char *flags = NULL;
    static char *ret;

    /*
     * Allocate memory for our flag strings.
     */
    flags = _MALLOC(sizeof(feature_flags), M_TEMP, M_WAITOK);

    do {
        /*
         * If the CPU supports a feature in the feature_list[],
         * move its corresponding flag from the feature_flags[]
         * into the buffer.
         */
        if ((cpuid_info()->cpuid_features & feature_list[i]) == feature_list[i]) {
            strlcat(flags, feature_flags[i], strlen(feature_flags[i]));
        //             |    |                |
        //             |    |                * The length of the string I want to amend to the 'flags' variable
        //             |    * The flag string in the array I want to amend to the 'flags' variable.
        //             * The variable I want the flag string to be amended to.
        }

        /*
         * Move the flag strings to a static variable before freeing the allocated memory
         * so we can free it before returning the resulting string.
         */
        ret = flags;

        /*
         * Add 1 to the counter for each iteration.
         */
        i++;

        /*
         * If the counter exceeds the number of items in the array,
         * break the loop.
         */
        if (i > nitems(feature_flags)) {
            /*
             * Free the allocated memory before breaking the loop.
             */
            _FREE(&feature_flags, M_TEMP);
            break;
        } else {
            continue;
        }
    } while (i < nitems(feature_flags));

    return ret;
}

This function then gets called by the main do_cpuinfo() function that prints the info into userspace. To save space I'm providing a minimal example here dealing only with the 'flags' field:
int
procfs_docpuinfo(__unused procfsnode_t *pnp, uio_t uio, __unused vfs_context_t ctx)
{
    vm_offset_t pageno, uva, kva;
    int len = 0, xlen = 0;
    off_t page_offset = 0;
    size_t buffer_size = 0;
    char *buffer;

    uint32_t max_cpus = *_processor_count;
    uint32_t cnt_cpus = 0;

    /*
     * Set up the variables required to move our data into userspace.
     */
    kva = VM_MIN_KERNEL_ADDRESS;                                        // kernel virtual address
    uva = uio_offset(uio);                                                                   // user virtual address
    pageno = trunc_page(uva);                                                         // page number
    page_offset = uva - pageno;                                                       // page offset
    buffer_size = sizeof(i386_cpu_info_t) + (LBFSZ * 2);                 // buffer size
    buffer = _MALLOC(buffer_size, M_TEMP, M_WAITOK);           // buffer

    char *flags = get_cpu_flags();

    do {
        if (cnt_cpus <= max_cpus) {
            /*
             * len should snprintf our flags via uiomove.
             */
            len += snprintf(buffer, buffer_size, "flags\t\t\t: %s\n", flags);

            /*
             * Subtract the uva offset from len.
             */
            xlen = len - uva;
            xlen = imin(xlen, uio_resid(uio));

            /*
             * Copy our data into userspace.
             */
            uiomove(buffer, xlen, uio);

            /*
             * Set len back to 0 before entering into the next loop.
             */
            if (len != 0) {
                len = 0;
            }

            /*
             * Update the CPU counter.
             */
            cnt_cpus++;

            /*
             * Continue unless the counter exceeds the
             * available processor count.
             */
            continue;
        } else if (cnt_cpus > max_cpus) {
            /*
             * If the counter exceeds the processor count,
             * free the associated memory and break the loop.
             */
            _FREE(&buffer, M_TEMP);
            break;
        }
    } while (cnt_cpus < max_cpus);

    return 0;
}

However, this is the result I get when executing cat on cpuinfo (with the full function intact obviously and not the minimal example provided above):
processor       : 0
vendor_id       : AuthenticAMD
cpu family      : 25
model           : 1
model name      : AMD Ryzen 9 5950X 16-Core Processor
microcode       : 186
stepping        : 0
cpu MHz         : 3393.62
cache size      : 512 KB
physical id     : 0
siblings        : 32
core id         : 0
cpu cores       : 16
apicid          : 0
initial apicid  : 0
fpu             : yes
fpu_exception   : yes
cpuid level     : 16
wp              : yes
flags           : fpappclm syscalpre
bugs            :
bogomips        : 6786.62
TLB size        : 2560 4K pages
clflush_size    : 64
cache_alignment : 64
address sizes   : 48 bits physical, 48 bits virtual
power management:

As you can see,  the flags field seems to combine fragments of the flag strings together in some very minimalistic fashion rather than the full flags string.
Note: The space you see is the result of there being four categories of features (cpuid_features, cpuid_extfeatures, cpuid_leaf7_features and cpuid_leaf7_extfeatures) in XNU so I made a function like get_cpu_flags() for each category. As such in my main code the snprintf function is expecting four sets of strings with a space between them ("flags\t\t\t: %s %s %s %s\n", cpuflags, cpuextflags, leaf7flags, leaf7extflags), yet it only prints out two of them and neither is printing out correctly once in userspace.
I assume the issue arises within the get_cpu_flags() function and its sister functions, but I'm not sure what the matter actually is. If I move 'ret = flags' out of the loop and put _FREE(&feature_flags, M_TEMP) right after it, I get a kernel panic and this is the stack trace:
panic(cpu 18 caller 0xffffff8019a9b8c6): "address 0xffffff7fb66cd110 inside vm entry 0xffffff802abc21e0 [0xffffff7f9a410000:0xffffff8000000000), map 0xffffff802abb10f8"com.apple./System/Volumes/Data/SWE/macOS/BuildRoots/36806d33d2/
Library/Caches/com.apple.xbs/Sources/xnu/xnu-7195.141.19/osfmk/kern/kalloc.c:651
Backtrace (CPU 18), Frame : Return Address
0xffffffa0ef283690 : 0xffffff8019a8c26d mach_kernel : _handle_debugger_trap + 0x3fd
0xffffffa0ef2836e0 : 0xffffff8019bd3993 mach_kernel : _kdp_i386_trap + 0x143
0xffffffa0ef283720 : 0xffffff8019bc3f8a mach_kernel : _kernel_trap + 0x55a
0xffffffa0ef283770 : 0xffffff8019a30a2f mach_kernel : _return_from_trap + 0xff
0xffffffa0ef283790 : 0xffffff8019a8ba8d mach_kernel : _DebuggerTrapWithState + 0xad
0xffffffa0ef2838b0 : 0xffffff8019a8bd83 mach_kernel : _panic_trap_to_debugger + 0x273
0xffffffa0ef283920 : 0xffffff801a29c8da mach_kernel : _panic + 0x54
0xffffffa0ef283990 : 0xffffff8019a9b8c6 mach_kernel : _ipc_thread_port_unpin + 0x116
0xffffffa0ef2839c0 : 0xffffff8019a9bf33 mach_kernel : _kfree + 0x263
0xffffffa0ef283a10 : 0xffffff8019a9be3f mach_kernel : _kfree + 0x16f
0xffffffa0ef283a70 : 0xffffff7fb66c5713 com.stupid.filesystems.procfs : _get_cpu_flags + 0xe3
0xffffffa0ef283aa0 : 0xffffff7fb66c4f4f com.stupid.filesystems.procfs : _procfs_docpuinfo + 0x24f
0xffffffa0ef283d50 : 0xffffff7fb66ca4c0 com.stupid.filesystems.procfs : _procfs_vnop_read + 0xb0
0xffffffa0ef283d90 : 0xffffff8019d4449c mach_kernel : _utf8_normalizeOptCaseFoldAndMatchSubstring + 0x72c
0xffffffa0ef283e30 : 0xffffff801a04c3b8 mach_kernel : _read_nocancel + 0x328
0xffffffa0ef283ee0 : 0xffffff801a04c145 mach_kernel : _read_nocancel + 0xb5
0xffffffa0ef283f40 : 0xffffff801a13ed0e mach_kernel : _unix_syscall64 + 0x2ce
0xffffffa0ef283fa0 : 0xffffff8019a311f6 mach_kernel : _hndl_unix_scall64 + 0x16
Kernel Extensions in backtrace:
com.stupid.filesystems.procfs(1.0)[89308435-3658-3ED4-990A-F8AF63358857]com.apple.0xffffff7fb66c3000-com.apple.driver.0xffffff7fb66ccfff

For the record, I'm just an amateur trying to learn C and kernel programming on my own because it's something that has fascinated me for a long time. I'm fairly new to working with character arrays and memory allocation so any advice would be deeply appreciated. I asked a similar question before, but got pointed out to me that I should be more specific and provide more extensive examples. Then I was also exclusively struggling with kernel panics but now that doesn't seem to be the main issue so I've deleted my old one and filed this new question based on the tips I received before and my progress since then. I hope I managed to present my question better this time but, if not, please let me know and I'll try to improve.
My full source code for these functions can be found here: https://github.com/somestupidgirl/procfs_kext/blob/main/kext/procfs_cpu.c
Edit 1:
A sizeof for each flag array gives me the following results:
 * sizeof(feature_flags)            = 480
 * sizeof(feature_ext_flags)        = 64
 * sizeof(leaf7_feature_flags)      = 368
 * sizeof(leaf7_feature_ext_flags)  = 96

I've been trying to do this without malloc, as has been suggested, but it always results in a kernel panic with the stack trace not telling me anything useful, really. So either I'm misunderstanding or the kernel simply won't allow it.
One thing I would also like to iterate is that I don't want 'get_cpu_flags' to do the 'snprintf' bit. What I want that function to do is gather the list of supported cpu feature flags, store them in a string, and return that string that should now contain a list of the supported cpu flags for the current cpu. Then I define a char* variable inside 'procfs_docpuinfo' with 'get_cpu_flags' that, once called by the 'snprintf' should print out the list of supported flags.
For a better reference, here is my full 'procfs_docpuinfo' function as it looks currently:
int
procfs_docpuinfo(__unused procfsnode_t *pnp, uio_t uio, __unused vfs_context_t ctx)
{
    vm_offset_t pageno, uva, kva;
    int len = 0, xlen = 0;
    off_t page_offset = 0;
    size_t buffer_size = 0;
    char *buffer;

    /*
     * Overall processor count for the current CPU.
     *
     * Not to be conflated with cpu_cores (number of cores)
     * as these are not the same.
     */
    uint32_t max_cpus = *_processor_count;

    /*
     * Initialize the processor counter.
     * This should always begin at 0 and
     * add 1 for each loop according to the
     * number of processors present.
     */
    uint32_t cnt_cpus = 0;

    /*
     * The core id should always start at 0.
     */
    int core_id = 0;

    /*
     * Initialize the TSC frequency variables.
     */
    uint64_t freq = *_tscFreq;
    int fqmhz = 0, fqkhz = 0;

    /*
     * Set the TSC frequency variables
     */
    if (freq != 0) {
        fqmhz = (freq + 4999) / 1000000;
        fqkhz = ((freq + 4999) / 10000) % 100;
    }

    /*
     * The apicid variable begins at 0 and get increased
     * by 2 for each loop until the number becomes greater
     * than max_cpus, in which case the loop resets the
     * variable to a value of 1 and then contines increasing
     * that number by 2 for each loop.
     */
    int apicid = 0, initial_apicid = 0;

    /*
     * Here we can utilize the i386_cpu_info structure in i386/cpuid.h
     * to get the information we need. The cpuid_info() function sets up
     * the i386_cpu_info structure and returns a pointer to the structure.
     */
    char *vendor_id = _cpuid_info()->cpuid_vendor;
    uint8_t cpu_family = _cpuid_info()->cpuid_family;
    uint8_t model = _cpuid_info()->cpuid_model; // FIXME
    char *model_name = _cpuid_info()->cpuid_brand_string;
    uint32_t microcode = _cpuid_info()->cpuid_microcode_version; // FIXME
    uint32_t cache_size = _cpuid_info()->cpuid_cache_size;
    uint8_t stepping = _cpuid_info()->cpuid_stepping;
    uint32_t cpu_cores = _cpuid_info()->core_count;
    uint32_t cpuid_level = cpu_cores;
    uint32_t tlb_size = _cpuid_info()->cache_linesize * 40;
    uint32_t clflush_size = _cpuid_info()->cache_linesize;
    uint32_t cache_alignment = clflush_size;
    uint32_t addr_bits_phys = _cpuid_info()->cpuid_address_bits_physical;
    uint32_t addr_bits_virt = _cpuid_info()->cpuid_address_bits_virtual;

    /*
     * Check if the FPU feature is present.
     */
    char *fpu, *fpu_exception;
    if (_cpuid_info()->cpuid_features & CPUID_FEATURE_FPU) {
        fpu = "yes";
        fpu_exception = "yes";
    } else {
        fpu = "no";
        fpu_exception = "no";
    }

    /*
     * Get the CPU flags.
     */
    char *cpuflags, *cpuextflags, *leaf7flags, *leaf7extflags;

    cpuflags = get_cpu_flags();
    cpuextflags = get_cpu_ext_flags();
    leaf7flags = get_leaf7_flags();
    leaf7extflags = get_leaf7_ext_flags();

    /*
     * Check for CPU write protection.
     */
    char *wp;
    if (get_cr0() & CR0_WP) {
        wp = "yes";
    } else {
        wp = "no";
    }

    /* TODO */
    //char *bugs = get_cpu_bugs();
    char *bugs = "";
    //char *pm = get_cpu_pm();
    char *pm = "";

    /*
     * Set up the variables required to move our data into userspace.
     */
    kva = VM_MIN_KERNEL_ADDRESS;                                        // kernel virtual address
    uva = uio_offset(uio);                                              // user virtual address
    pageno = trunc_page(uva);                                           // page number
    page_offset = uva - pageno;                                         // page offset
    buffer_size = (LBFSZ * 4);                                          // buffer size
    buffer = _MALLOC(buffer_size, M_TEMP, M_WAITOK);                    // buffer

    do {
        if (cnt_cpus <= max_cpus) {
            /*
             * The data which to copy over to userspace.
             */
            len += snprintf(buffer, buffer_size,
                "processor\t\t: %u\n"
                "vendor_id\t\t: %s\n"
                "cpu family\t\t: %u\n"
                "model\t\t\t: %u\n"
                "model name\t\t: %s\n"
                "microcode\t\t: %u\n"
                "stepping\t\t: %u\n"
                "cpu MHz\t\t\t: %d.%02d\n"
                "cache size\t\t: %d KB\n"
                "physical id\t\t: %u\n"
                "siblings\t\t: %u\n"
                "core id\t\t\t: %d\n"
                "cpu cores\t\t: %u\n"
                "apicid\t\t\t: %u\n"
                "initial apicid\t\t: %u\n"
                "fpu\t\t\t: %s\n"
                "fpu_exception\t\t: %s\n"
                "cpuid level\t\t: %u\n"
                "wp\t\t\t: %s\n"
                "flags\t\t\t: %s %s %s %s\n"
                "bugs\t\t\t: %s\n"
                "bogomips\t\t: %d.%02d\n"
                "TLB size\t\t: %u 4K pages\n"
                "clflush_size\t\t: %u\n"
                "cache_alignment\t\t: %d\n"
                "address sizes\t\t: %d bits physical, %d bits virtual\n"
                "power management\t: %s\n\n",
                cnt_cpus,               // processor
                vendor_id,              // vendor_id
                cpu_family,             // cpu family
                model,                  // model
                model_name,             // model name
                microcode,              // microcode
                stepping,               // stepping
                fqmhz, fqkhz,           // cpu MHz
                cache_size,             // cache size
                0,                      // physical id
                max_cpus,               // siblings
                core_id,                // core id
                cpu_cores,              // cpu cores
                apicid,                 // apicid
                initial_apicid,         // initial apicid
                fpu,                    // fpu
                fpu_exception,          // fpu exception
                cpuid_level,            // cpuid level
                wp,                     // wp
                cpuflags,               // flags
                cpuextflags,            // flags
                leaf7flags,             // flags
                leaf7extflags,          // flags
                bugs,                   // bugs
                fqmhz * 2, fqkhz,       // bogomips
                tlb_size,               // TLB size
                clflush_size,           // clflush_size
                cache_alignment,        // cache_alignment
                addr_bits_phys,         // address size physical
                addr_bits_virt,         // address size virtual
                pm                      // power management
            );

            /*
             * Subtract the uva offset from len.
             */
            xlen = len - uva;
            xlen = imin(xlen, uio_resid(uio));

            /*
             * Copy our data into userspace.
             */
            uiomove(buffer, xlen, uio);

            /*
             * Set len back to 0 before entering into the next loop.
             */
            if (len != 0) {
                len = 0;
            }

            /*
             * Reset the max_cpus variable at the end of each loop.
             * Otherwise it tends to behave erratically.
             */
            if (max_cpus != *_processor_count) {
                max_cpus = *_processor_count;
            }

            /*
             * Increase by 2 for each loop.
             */
            apicid += 2;
            if (apicid >= max_cpus) {
                /* If the number exceeds max_cpus, reset to 1. */
                apicid = 1;
            }

            /*
             * The initial apicid is the same as apicid.
             */
            initial_apicid = apicid;

            /*
             * Update the CPU counter.
             */
            cnt_cpus++;

            /*
             * Update the core_id.
             */
            core_id++;

            /*
             * The core_id should never exceed the number of cores.
             * Start over if it does.
             */
            if (core_id > cpu_cores - 1) {
                core_id = 0;
            }

            /*
             * Continue unless the counter exceeds the
             * available processor count.
             */
            continue;
        } else if (cnt_cpus > max_cpus) {
            /*
             * If the counter exceeds the processor count,
             * free the associated memory and break the loop.
             */
            _FREE(&buffer, M_TEMP);
            break;
        }
    } while (cnt_cpus < max_cpus);

    return 0;
}

And here is my slightly updated 'get_cpu_flags' function:
STATIC char *
get_cpu_flags(void)
{
    int i = 0;
    int size = 0;
    char *flags;
    static char *ret;

    size = sizeof(feature_flags);
    flags = _MALLOC(size, M_TEMP, M_WAITOK);

    do {
        /*
         * If the CPU supports a feature in the feature_list[]...
         */
        if (_cpuid_info()->cpuid_features & feature_list[i]) {
            /*
             * ...amend its flag to 'flags'.
             */
            strlcat(flags, feature_flags[i], sizeof(flags));
        }

        ret = flags;

        /*
         * Add 1 to the counter for each iteration.
         */
        i++;

        /*
         * If the counter exceeds the number of items in the array,
         * break the loop.
         */
        if (i > nitems(feature_flags)) {
            _FREE(&flags, M_TEMP);
            break;
        } else {
            continue;
        }
    } while (i < nitems(feature_flags));

    return ret;
}

The result from executing cat on cpuinfo is still pretty much the same as before. I'm still digesting all the replies I've received and hopefully I can come up with a solution that works sooner than later thanks to y'all. <3
Edit 2:
I finally managed to figure it out! The 'get_cpu_flags' function now looks like this:
STATIC char *
get_cpu_flags(void)
{
    int i = 0;
    int size = (sizeof(feature_flags) * 2);
    char *flags[size];

    do {
        /*
         * If the CPU supports a feature in the feature_list[]...
         */
        if (_cpuid_info()->cpuid_features & feature_list[i]) {
            /*
             * ...amend its flag to 'flags'.
             */
            strlcat(flags, feature_flags[i], sizeof(flags));
        }

        /*
         * Add 1 to the counter for each iteration.
         */
        i++;

    } while (i < nitems(feature_flags));

    return flags;
}

And the output from cat on the cpuinfo file now looks like this:
processor           : 0
vendor_id           : AuthenticAMD
cpu family          : 25
model               : 1
model name          : AMD Ryzen 9 5950X 16-Core Processor
microcode           : 186
stepping            : 0
cpu MHz             : 3393.63
cache size          : 512 KB
physical id         : 0
siblings            : 32
core id             : 0
cpu cores           : 16
apicid              : 0
initial apicid      : 0
fpu                 : yes
fpu_exception       : yes
cpuid level         : 16
wp                  : yes
flags               : fpuvmedepsetscmsrpaemcecx8apicsepmtrrpgemcacmovpatpse36clfshmmxfxsrssesse2httsse3pclmulqdqmonssse3fmacx16sse4.1sse4.2movbepopcntaesxsaveosxsaveavx1.0f16crdrand
bugs                :
bogomips            : 6786.63
TLB size            : 2560 4K pages
clflush_size        : 64
cache_alignment     : 64
address sizes       : 48 bits physical, 48 bits virtual
power management    :

Thanks to chqrlie for providing the right answer, and everyone else who chimed in! I truly appreciate all of your inputs! Now the only thing left is to add a space between each flag, but now that I have a better understanding of what I'm doing it shouldn't be too big of a challenge. Thanks again everyone and peace out. <3

A: Very nice that you want to learn C and even nicer that you are getting into kernel programming. Fantastic topic. Keep that work of yours going!
Now to your question. I noticed the following if-statement in your code:
if (i > nitems(feature_flags)) {
    /*
     * Free the allocated memory before breaking the loop.
     */
    _FREE(&feature_flags, M_TEMP);
    break;
} else {
    continue;
}

From my understanding, this is never true since the highest value that i reaches is nitems(feature_flags).
I also noticed that you use strlcat, which really just appends to the provided string. This might make it tricky to separate flags. You could instead do something like: offset += snprintf(flags + offset, len[i] + 1, " %s", feature_flags[i]);, where len[i] = strnlen(feature_flags[i], max_len);
Note the +1 for the NUL character.
I think that some of the problems could also stem from the construct you use with the static char array ret. I would suggest to either pass a "large enough" char array to the function and fill that or malloc something in the function and return the pointer to that, basically assuming the caller takes care of it. But that would be you in this case. In that case you could simply free after having used the string.
I think that an ad-hoc Implementation with malloc would look like this:
char*
get_cpu_flags(void)
{
     // NOTE: This only works because feature_flags is an actual array. This not necessarily works for pointers
    int n = sizeof(feature_flags) / sizeof(feature_flags[0]);
    char *flags = _MALLOC(n, M_TEMP, M_WAITOK);

    int offset = 0;
    for (int i = 0; i < n; ++i) {
        if ((cpuid_info()->cpuid_features & feature_list[i]))
            offset += snprintf(flags + offset, some_upper_bound, " %s", feature_flags[i]);
    }

    return flags;
}

An implementation with memory coming from outside could look like this:
void
get_cpu_flags(char* array, size_t size)
{
    int offset = 0;
    for (int i = 0; i < size; ++i) {
        if ((cpuid_info()->cpuid_features & feature_list[i]))
            offset += snprintf(flags + offset, some_upper_bound, " %s", feature_flags[i]);
    }
}

Beware that I'm typing this on my phone :^)
In any case, I hope that I could help you with these insights and an example how one could put together a string from a string array.
Appendix:
Reading the answer before, I have to agree that for, in this case ~300 bytes, a local char array would do and spare you some malloc. I would suggest to use that approach.

A: There is no need to allocate memory for this task: pass a pointer to a local array along with its size and use strlcat properly:
strlcat(flags, feature_flags[i], size);

Calling strlcat() with a size argument that is the length of the copied string is a mistake, the size argument should be the size of the destination array for strlcat to truncate the destination.
For example:
char *get_cpu_flags(char *dest, size_t size) {
    /* avoid patching dest if size is 0 */
    if (!size)
        return;
    /* initialize dest as an empty string */
    *dest = '\0';
    /* repeat these tests: */
    if (cpuid_info()->cpuid_features & [...]) {
        /* append flag name, truncating if necessary */
        strlcat(dest, " flagname", size);
        }
    }
    [...]
    /* return argument so the composed string can be passed
       to snprintf directly */
    return dest;
}


text:
Q: Google+ Sign in from Javascript - Invalid Parameter value for origin I've been going through the steps to add a Google+ Sign-in to my web application as found in https://developers.google.com/+/web/signin/
When used in a 'typical' web site, the 'client side' flow works just fine. Now, I'm trying to integrate this Google+ sign inside PhoneGap. Since PhoneGap runs the web page as a file:// URL, the origin that gets sent in the request is file://. In every other PhoneGap I've written, this hasn't been a problem.
However, when I click the Google+ sign in button from my page in PhoneGap, the origin being sent as file:// causes the following error message:
Error: invalid_request
Invalid parameter value for origin: Missing authority: file://
I went to the Google API console and tried to assign file:// as an authorized Javascript origin. But, of course, it doesn't allow file:// to be entered as an origin.
So I'm wondering if anyone has any insight in how to do this kind of web-style (Javascript) Google+ sign in from within PhoneGap (or from a local web page where there is no server - just a page being run as a file://). I really don't want to have to do the sign-in in native code and then integrate the token back over into the 'PhoneGap' realm since that kind of defeats the purpose of writing the app once for multiple platforms.

A: My understanding is that you cannot use the standard client-side flow with Cordova/PhoneGap because file:// is not a valid origin.
However, you can use the In-App Browser plugin along with window.open, which will allow to initiate a "standard" client-side flow from within the application. You then listen to events on the opened window to deal with the responses.
The plugin works cross-platform so you won't have to maintain multiple native implementations.
The ng-cordova-oauth library implements this for AngularJS.
For more details about the implementation, see this tutorial for details, as well as the Google OAuth documentation.

A: For file://, the thing works differently.. try this as your origin: http://localhost:4567

or try this tutorial: here


text:
Q: How to show the differential form $\nu$ satisfies $\nu(v_1, \ldots, v_n)=\det(a_{ij})$? In $\mathbb R^n$ consider the differential form $\nu$ satisfying $\nu(e_1, \ldots, e_n)=1$. For every $i=1, \ldots, n$ consider the vector  $\displaystyle v_i=\sum_{j=1}^n a_{ij} e_j$. How to show $\nu(v_1, \ldots, v_n)=\det(a_{ij})$? I can see it is true, but I can't argue why that is true..
I guess I should use the relation $$f^*\omega=\det(df)dx_1\wedge \ldots \wedge dx_n,$$ where $f:\mathbb R^n\longrightarrow \mathbb R^n$, $f=(f_1, \ldots, f_n)$, $y_i=f(x_1, \ldots, x_n)$ and $\omega=dy_1\wedge \ldots \wedge dy_n$. Using this, given $v_i=\sum_{j=1}^n a_{ij} e_j$, I defined $f:\mathbb R^n\longrightarrow \mathbb R^n$, $f=(f_1, \ldots, f_n)$, setting $$f_i(x_1, \ldots, x_n)=\sum_{j=1}^n a_{ij} x_j.$$
Then $\partial_j f_i=a_{ij}$ hence $$(f^*\omega)(e_1, \ldots, e_n)=\det(a_{ij})dx_1\wedge \ldots \wedge dx_n(e_1, \ldots, e_n)=\det(a_{ij}).$$
So the problem amounts showing $(f^*\omega)(e_1, \ldots, e_n)=\nu(v_1, \ldots, v_n)$, but still I can't do that.
Can anyone give me some hint?
Obs:
(i) I still don't know $\displaystyle\det(a_{ij})=\sum_{\sigma} \textrm{sign}(\sigma) a_{1\sigma(1)}\cdots a_{n\sigma(n)}$.
(ii) $(f^*\omega)(v_1, \ldots, v_n)=\omega(df(v_1), \ldots, df(v_n))$ (in simplified notation, i.e., ommiting the point the form came from).


text:
Q: How to Convert StackFrame Collection to String? I have a IEnumerable<System.Diagnostics.StackFrame> frames for store some custom StackFrame.
I want to convert that to the string type like StackTrace.ToString() format.
for example:
   at TestStackTrace.Form1.button2_Click(Object sender, EventArgs e) in
d:\Programming\temp\TestStackTrace\TestStackTrace\Form1.cs:line 66
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)

A: Use the stateprinter framework. It can turn object graphs into strings and even automate the assert part of testing. See https://github.com/kbilsted/StatePrinter/blob/master/doc/AutomatingUnitTesting.md
For making a string
string s = new Stateprinter().PrintObject(stackframe)

A: I've use Microsoft Reference Source to reflect (mscorlib).system\diagnostics\stacktrace.cs codes and seen what happen in that ToString() methods to convert that StackFrames to string.
So, with that, i could to write a function without dependence.
public static string StackFramesToString(this StackFrame[] frames, int numMethodsToSkip = 0)
{
    bool displayFilenames = true;   // we'll try, but demand may fail
    String word_At = "at";
    String inFileLineNum = "in {0}:line {1}";

    bool fFirstFrame = true;
    StringBuilder sb = new StringBuilder(255);
    for (int iFrameIndex = 0; iFrameIndex < frames.Count(); iFrameIndex++)
    {
        StackFrame sf = GetFrame(iFrameIndex, frames, numMethodsToSkip);
        MethodBase mb = sf.GetMethod();
        if (mb != null)
        {
            // We want a newline at the end of every line except for the last
            if (fFirstFrame)
                fFirstFrame = false;
            else
                sb.Append(Environment.NewLine);

            sb.AppendFormat(CultureInfo.InvariantCulture, "   {0} ", word_At);

            Type t = mb.DeclaringType;
            // if there is a type (non global method) print it
            if (t != null)
            {
                sb.Append(t.FullName.Replace('+', '.'));
                sb.Append(".");
            }
            sb.Append(mb.Name);

            // deal with the generic portion of the method
            if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod)
            {
                Type[] typars = ((MethodInfo)mb).GetGenericArguments();
                sb.Append("[");
                int k = 0;
                bool fFirstTyParam = true;
                while (k < typars.Length)
                {
                    if (fFirstTyParam == false)
                        sb.Append(",");
                    else
                        fFirstTyParam = false;

                    sb.Append(typars[k].Name);
                    k++;
                }
                sb.Append("]");
            }

            // arguments printing
            sb.Append("(");
            ParameterInfo[] pi = mb.GetParameters();
            bool fFirstParam = true;
            for (int j = 0; j < pi.Length; j++)
            {
                if (fFirstParam == false)
                    sb.Append(", ");
                else
                    fFirstParam = false;

                String typeName = "<UnknownType>";
                if (pi[j].ParameterType != null)
                    typeName = pi[j].ParameterType.Name;
                sb.Append(typeName + " " + pi[j].Name);
            }
            sb.Append(")");

            // source location printing
            if (displayFilenames && (sf.GetILOffset() != -1))
            {
                // If we don't have a PDB or PDB-reading is disabled for the module,
                // then the file name will be null.
                String fileName = null;

                // Getting the filename from a StackFrame is a privileged operation - we won't want
                // to disclose full path names to arbitrarily untrusted code.  Rather than just omit
                // this we could probably trim to just the filename so it's still mostly usefull.
                try
                {
                    fileName = sf.GetFileName();
                }
                catch
                {
                    // If the demand for displaying filenames fails, then it won't
                    // succeed later in the loop.  Avoid repeated exceptions by not trying again.
                    displayFilenames = false;
                }

                if (fileName != null)
                {
                    // tack on " in c:\tmp\MyFile.cs:line 5"
                    sb.Append(' ');
                    sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber());
                }
            }
        }
    }

    return sb.ToString();
}

public static StackFrame GetFrame(int index, StackFrame[] frames, int numMethodsToSkip)
{
    if ((frames != null) && (index < frames.Count()) && (index >= 0))
        return frames[index + numMethodsToSkip];

    return null;
}


text:
Q: Linux - auto restarting with sleep Current code of mine is
while true; do ./program; done;

I don't have access to a linux box right now and only way to do my request will be made on the live server and I don't want to test and jeopardize something, so I would be happy if I could get some help
Is this the way it should be if I want my program to sleep 2 seconds after each restart?
while true; sleep(2); do ./program; done;

A: Almost fine.

*

*sleep is a program, so pass him the arguments as space-separated list.

*logical test (i.e. true) should be followed immediately by do

*If sleep is before ./program, the latter is sleeped before, not after. You could consider reordering them.

while true; do ./program; sleep 2; done;

A: do keyword enters the loop. Write it before any command that you want to repeat.
while true; do
    sleep(2);
    ./program;
done

A: while true; do
    ./program
    sleep 2
done


text:
Q: Syncing output of OpenGL FBO I'm doing a little bit of video processing in real time using OpenGL.
I do a render to texture via FBO+RBO and shaders for simple processing on the video frame. Then I use that texture to render (not blit) to the default frame buffer.
Some of my video processing needs to be frame accurate. If I step through the video frame by frame everything looks good; when I play it back at video rate it gets out of sync.
I'm thinking that the texture I'm getting out of the FBO+RBO is not based on the texture I input because of buffering/other issues.
This seems like a relevant question but there is no answer to it yet: double buffering with FBO+RBO and glFinish()
In my case I am using a Qt QGLWidget with the QGL::DoubleBuffer format option.
I need to flush the output of FBO; alternatively if I could work out which frame texture has come out of the FBO I can compensate for the sync issue.


text:
Q: JUnit vs TestNg - For a New Project that using Spring MVC Looking at the latest versions of JUnit[v 4.11] and TestNg[v 6.8.5] as of today, I see no big differences in both the frameworks.
If I am using Spring MVC in my project and have several layers and need unit/integration tests at all the controller / service / dao layers what framework would really be helpful for me.
I have prior experience working on JUnit but never used TestNg. Any advice?

A: jUnit is great for unit testing, gets the job done well, however it was never built for integration testing, but in the last year or so it has been geared towards integration/automation testing.
TestNG from a very early stage was suitable for integration/automation testing, it has a more powerful version of dataprovider than jUnit, even before jUnit had dataprovider capabilities. It has much better annotation support than jUnit and unlike jUnit TestNG does not require your before/after class methods to be static. It has better multi thread/parallel execution support and has method dependency, as well as order execution. All of which jUnit needs or does poorly.
TestNG even has better reporting, please google for ReportNG or (my fav) TestNG-XLST.
if you want only simple unit testing, IMO go with jUnit, if you require a more robust test framework to meet your unit/integration/performance/automation testing, then I would very much recommend TestNG.

A: While you can do almost everything JUnit can do in TestNG, it takes a lot more work to have the facilities of TestNG in a JUnit environment.
One important facility required in integration testing, at an level, is to be able to order the tests you run, both for early bail out (it makes no sense to test application functionality when the database tests are failing) and for efficiency (having provisioning tests run before operational tests). While certain classes of unit tests (leaf tests) should be specified without order, almost all of the interesting stuff is done in non-leaf methods, with non-trivial setup.
Another area is parameterizing tests: TestNG has somewhat stronger handling of parameterization.
I can't present the benefits of JUnit over TestNG as the benefits of test ordering far outweigh not being able to order tests.

A: The difference isn't that big,
use the one you are familiar and comfortable with.
A little clarification:
With Junit 4.xx you can easily do almost anything that TestNG does (and you have the ability to easily extend it as well)

*

*Set the tests order: @FixMethodOrder(MethodSorters.NAME_ASCENDING)

*Use parameters for test data:  @RunWith(Parameterized.class)

or
@Rule
    public DataSetRule rule = new DataSetRule();


text:
Q: Problems with twilio java library into android project with build.gradle I am facing few problems including the twilio library into an android project.
First I included with
 compile group: 'com.twilio.sdk', name: 'twilio', version: '7.4.0'

But I started getting this ill-advised or mistaken problem as mentioned int this SO question
So, I excluded the javax library with
compile (group: 'com.twilio.sdk', name: 'twilio', version: '7.4.0'){
    exclude group: 'javax.xml.bind', module: 'jaxb-api'
}

But then I am getting run time errors complaining that twilio can't make HTTP call because it can't find the NetworkHttpClient
com.twilio.http.NetworkHttpClient.<init>(NetworkHttpClient.java:33)
The dependency chain for twilio library looks like this.

Any ideas on how to solve this? All I want to do this make a couple of HTTP calls to twilio to make a telephone call in my test and I can very well do this with a simple curl statement, so alternative approaches are welcome as well.

A: Twilio developer evangelist here.
The Java library is not meant to be used with Android, and as you've seen, when you try to use it, you will end up with networks errors since the library uses a version of Apache HTTP that is not supported by Android.
Now, back to what you're trying to do, I suggest that instead of trying to make requests to the Twilio API from Android directly, you add a backend server, that way, you just need to make a request to that backend server from your app. This stops your credentials being visible to anyone who downloads your app.
I described how to send SMS from Android in this blog post, but you should be able to modify it so you can also make telephone calls.
Then on your app you can do something like:
Call post(String url, Callback callback) throws IOException{
    RequestBody formBody = new FormBody.Builder()
            .add("To", mTo.getText().toString())
            .add("Body", mBody.getText().toString())
            .build();
    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();

If what you're trying to do however is make Voip calls, then you should look at the Twilio Programmable Voice SDK. The page has examples of how to use it.
Hope this helps you!


text:
Q: Subset dataframe with userinput shiny I want to subset a data frame based on userinput
...
df <- eventReactive(input$button,{
  df2 <- read.csv(foo(), sep = ";")
  df2$date <- as.Date.character(df2$date,  format = '%d.%m.%Y')

  #input$Main2 element of (a,b,c)
  input1<- input$Main2

 #Does not work:
 df3 <- subset(df2, input1 %in% input$Main2_1)
 #Works:
  df3 <- subset(df2, a %in% input$Main2_1)

  df3
  })
....

Where input1 is a single variable name. It works fine if I directly write the variable name instead of input1.

A: You can try
df3 <- df2[df2[[input1 ]]%in% input$Main2_1,]


text:
Q: How to copy contents of a directory to another location in Android I want to copy contents from one location to another.
I tried few of the methods, but I am interested in a faster approach for copying of the files.
I have few constraints,
I cannot use org.apache.commons.io package or use exec call for cp -r
Is there any android utility method or a simple faster program for doing the same.
I tried the below code, but it seems slower.
public static void copyDirectory(String sourceDirectoryLocation, String destinationDirectoryLocation)
      throws IOException {
        Files.walk(Paths.get(sourceDirectoryLocation))
          .forEach(source -> {
              Path destination = Paths.get(destinationDirectoryLocation, source.toString()
                .substring(sourceDirectoryLocation.length()));
              try {
                  Files.copy(source, destination);
              } catch (IOException e) {
                  e.printStackTrace();
              }
          });
    }


text:
Q: Changing the Keyboard for Specific App on Android
I am developing a "Nepali Dictionary Android App" using Cordova. Using jQuery I have been able to map the keyboard character to Devnagari.  For example If you pressed the 'k' from keyboard 'क' will be displayed in editable text inputs. Now , I am trying to change the keyboard characters so that the users could see Nepali characters in keyboard.
I don't know If it is possible or not, but I think it should be. I am not a java programmer and using cordova api to build the android applications. I am also planning to create MultiKeyboard Phonegap / Cordova Plugin for android (in future ) if It is possible.
My Question is :
How can I change the android keyboard characters for some specific apps ?
WHAT HAVE I TRIED
I have not started coding for this because I don't know if it is possible or not. Please show me the right way.
Thanks.

A: You could change char value with different value if the given input values will not be used. What i mean is if 'k' will never be used you could catch that input in for example
var tempChar;

variable and swap it's value from a HashMap, but I don't know if you can change the layout of keyboard using PhoneGap only. If you can't do, you can draw your own keyboard using jQuery Mobile if there is way to disable Android keyboard for your app.


text:
Q: jQuery UI dialog open callback executes only once, but I want it to execute everytime the dialog opens jQuery UI dialog open callback executes only once, but I want it to execute every time the dialog opens..
$('
'+ text +'
').dialog({
  title: 'User(s) with a similar name',
  modal: true,
  autoOpen: true,
  height: 'auto',
  width: 400,
  resizable: false,
  open: function(){
    $('#smartpaginate').smartpaginator({
      totalrecords: 3,
      recordsperpage: 2,
      datacontainer: 'all-tabs',
      dataelement: 'table',
      theme: 'green'
    });
  },
  buttons: {
    "Close": function(){
      $(this).dialog('close');
      return false;
    }
  }
});

The callback function for open executes correctly and generates pagination, but after closing, every time it opens without a pagination.

A: try removing the dialog from DOM:
$('
'+ text +'
').dialog({
  title: 'User(s) with a similar name',
  modal: true,
  autoOpen: true,
  height: 'auto',
  width: 400,
  resizable: false,
  open: function(){
    $('#smartpaginate').smartpaginator({
      totalrecords: 3,
      recordsperpage: 2,
      datacontainer: 'all-tabs',
      dataelement: 'table',
      theme: 'green'
    });
  },
  buttons: {
    "Close": function(){
$(this).remove();
      return false;
    }
  }
});


text:
Q: A word for "modify/delete/change a newspaper article" a word for " a person/politician asking to review/modify a newspaper article before it is published"

A: The term vetting is often used

to subject to usually expert appraisal or correction: vet a manuscript

The phrase sign off is also used

to approve or acknowledge something by or as if by a signature: sign off on a memo

A: Some terms like  quote approval,  veto power, and green light appear in a recent Guardian article on the subject of right-of-review.
Quote approval also appears in a recent CNN article, along with terms like  on background (where interviewee insists on no quotes), Faustian bargain (as Dan Rather calls pre-publication-review agreements), and lapdogs (his term for journalists who agree to such provisions).  I suppose that if you agree with the second term, you could call the  person or politician asking to review or modify a newspaper article before publication  Faust.
The verb redact ("To censor...",  "To black out text..."), mentioned in comment below, leads to nouns  redaction ("The change or changes made while editing", "The process of editing or censoring") and  redactor ("A person who redacts").  I think of redaction as occurring either post-publication (eg copies of a book or newspaper might have pages or articles removed) or in a document-release process (eg a letter or article may be reviewed and parts of it deleted before delivery or release) rather than before publication.  However, the two senses  of redaction quoted above seem to allow changes before publication, although the etymology of redact (essentially, "back action") militates against that interpretation.

A: "pre-publication review" or "pre-publication approval"?