text:
Q: Haxe: Creating a code completion macro for JSON files I am trying to implement a code completion macro for JSON files by generating field definitions
    var classOfChild = Type.getClass(child); // `child` may look like this array: [[1,2,3],[0.1,0.2,0.3]]
    fields.push({
        "name": childName,
        "pos" : _pos,
        "kind": childType,
    });

I already watched some videos and read some tutorials on this, but there is no information how to get ComplexType from a Type.typeof(object) result.
I have tried code that doesn't work like:
                    //"kind": childType,
                    //"kind": childType.toString(),
                    //"kind": FVar(macro {childType.toString(); }),
                    //"kind": FVar(macro Array<$v{arrType}>)

but none of them worked (all of them raise some Error or )
Edit 1: here is my json data:
{"floatVar1":0.1, "str":"some string", "nullValueObject":null, "arrayOfInts":[11,20,9], "matrixLikeArray":[[14, 12, 13, 11, 18]], "floatMatrix":[[14.4, 12.3, 13.7, 11.9, 18.0]], "symbolPayouts":[0.05], "objectInObject":{"prop1":"some str", "prop2": "some str2", "prop3":10.17, "prop4":[[1,2,3],[19.3,20.4]]}}

I would like to create Definitions for prop4, ("prop4":[[1,2,3],[19.3,20.4]])
Edit 2: I have already figured out how to create the "kind" for the simple types ("kind": FVar(macro:Dynamic)) and the object (kind : FVar(TAnonymous( jsonFields ))). But how to do that for arrays, arrays of arrays, etc.
Edit 3: code in gist.github.com

A: When generating code with macros it is easy to attempt to generate something which isn't efficient and you did get side tracked by trying to define explicit types.
Based on your gist, you just need to define a json field and give it the content of your JSON file as the field's value as if you were defining the value as a Haxe literal object.
Your goal is then to generate something you could have written as:
private var json = { prop1:'hello', prop2:42, prop3:[1,2,3] };

The haxe compiler will strongly type this json field.
To achieve that, your macro just need to add one field with an initial value obtained from the JSON file; and likewise, the Haxe compiler will strictly type it.
Creating a variable with a type to be inferred by the compiler is simply FVar(null, valueExpr), which means your entire macro can be reduced to:
    var fields = Context.getBuildFields();
    var json = Json.parse(src);

    fields.push({
        name : "json",
        pos : Context.currentPos(),
        kind : FVar(null, macro $v{json}),
        access: [APrivate],
    });
    return fields;

For a more elaborated version I can point you on the following gist: ResourceGenerator.hx which will generate recursively "inlinable" and dce-friendly objects.
PS: sadly your "prop4":[[1,2,3],[19.3,20.4]] is impossible because it will be seen by the compiler as an Array of incompatible types ([Array<Int>, Array<Float>]).


text:
Q: Unit testing Spring Batch step with @BeforeStep I am trying to unit test and individual step in Spring Batch. This step has a reader, a processor and a writer. The reader has a method annotated with @BeforeStep in order to set StepExecution.
I want to add a key to StepExecution in order to promote it to future steps using a listener. Here is my configuration:
@Configuration
@EnableBatchProcessing
public class MyJob {

    @Bean
    public Job myJob() {
        return jobBuilderFactory.get("myJob")
                .incrementer(new RunIdIncrementer())
                .listener(jobIdToContextExecutionListener())
                .flow(myStep())
                .end()
                .build();
    }

    @Bean
    public Step myStep() {
        return stepBuilderFactory.get("myStep").<MyDto, OtherDto>chunk(chunk)
                .reader(myReader())
                .processor(myProcessor())
                .writer(myWriter(JOB_ID))
                .listener(myPromotionListener())
                .build();
    }

    @Bean
    public ExecutionContextPromotionListener myPromotionListener() {
        ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener();
        listener.setKeys(new String[] {"myKey"});
        return listener;
    }

    @Bean
    @StepScope
    ItemReader<DTO> myReader() {
        return new MyReader();
    }

    @Bean
    @StepScope
    ItemProcessor<MyDto> myProcessor() {
        return new MyProcessor();
    }
}

When I want to unit test this step, I get NullPointerException for stepExecution in sendForNextSteps method. Here is the code for my ItemReader:
public class MyReader implements ItemReader<MyDto> {

    private StepExecution stepExecution;

    @Override
    public MyDto read() {
        // some logic

        sendForNextSteps(someDto);
        return someDto;
    }

   private void sendForNextSteps(MyDto myDto){
            ExecutionContext stepContext = this.stepExecution.getExecutionContext();
            stepContext.put("mykey", myDto);
    }

    @BeforeStep
    public void saveStepExecution(StepExecution stepExecution) {
        this.stepExecution = stepExecution;
    }
}

Here is my code for the unit test:
@SpringBootTest
@ContextConfiguration(classes = {MyJob.class, JobLauncherTestUtilsWithoutDatasourceConfig.class, TransferItemService.class, DataUtils.class})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class JobStepUnitTest {

    @Test
    public void myTest() {

        /**
         * some mocking and arrangement irrelevant of spring batch
         */

        /**
         * when launching myStep
         */
        JobExecution jobExecution = jobLauncherTestUtils.launchStep("myStep");

        /**
         * some assertions on the number of calls to methods. also irrelevant to spring batch
         */

    }
}

Is there any way to unit test an individual step that manipulates StepContext (for example in my code, ItemReader adds a key to the context)?
I have seen examples that unit test a StepScope component like ItemReader but could not find a way to unit test the whole step. Thanks in advance.
I have also checked that answer in the following link:
link
but the difference is that in this link, we are testing a StepScope component. In my case, we are testing the whole step using jobLauncherTestUtils.launchStep(). I also tried adding getStepExecution method in my test class together with StepScopeTestExecutionListener.class for the @TestExecutionListeners annotation but no success

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Padding Amount With Zeros I have an amount field which is a decimal in the database.
I need to always display this amount with 10 numbers on the left of the decimal and two after.
Example:
Amount = 245.00 which should display as 0000000245.00
Additionally, the amount could be over 1,000 or 10,000 which should display as:
0000001245.00 and 0000011245.00
How can I format the amount to always have the appropriate number of zeros on the left side of the decimal with a variable amount size?

A: You should put 0's in your format string.  Something like this.
myValue.ToString("0000000000.00");

That will always give you 10 digits on the left side of your decimal point and two on the right.
If you do not want two digits on the right side... do this.
myValue.ToString("0000000000.##");

This says hey if we have a value display it; otherwise, skip it.

A: yourDecimalVariable.ToString("0000000000.00") should do the trick.

A: This should help... http://www.csharp-examples.net/string-format-int/
So you can use this
string.Format("{0:0000000000.00}", 15.25); // "0000000015.25"


text:
Q: What has happened to the salt with bcrypt? This is from the github page:
require 'bcrypt'

class User < ActiveRecord::Base
  # users.password_hash in the database is a :string
  include BCrypt

  def password
    @password ||= Password.new(password_hash)
  end

  def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
  end
end

It appears that to access the password method, you need to call it as an attribute from a create method:
@user.password = user_params[:password]
@user.save

Okay...fine? But where's the salt now stored? I just don't get it at all, how is this even remotely secure anymore?
To retrieve a hashed password, you need this method:
  def password
    @password ||= Password.new(password_hash)
  end

And call it as an attribute:
  if @user.password == params[:password]
    give_token
  else
    false
  end

So it appears everything's working without a salt...how does it do this?
This means I only need one column in my database to do with passowords now, right?password or password_hash instead of password_salt | password_hash?
Well then why does the github page say this:

But even this has weaknesses -- attackers can just run lists of
  possible passwords through the same algorithm, store the results in a
  big database, and then look up the passwords by their hash:
PrecomputedPassword.find_by_hash(<unique gibberish>).password #=> "secret1"
Salts

And then this is what really gets me:

The solution to this is to add a small chunk of random data -- called a salt -- to the password before it's hashed:

Why are they explaining all of this if bcrypt is handling everything automatically?

hash(salt + p) #=> <really unique gibberish>
The salt is then stored along with the hash in the database, and used to check potentially valid passwords:

<really unique gibberish> =? hash(salt + just_entered_password)
bcrypt-ruby automatically handles the storage and generation of these salts for you.

Could someone explain how bcrypt stores and generates these salts? Why does it say it handles it all for me and then goes on to tell me how to generate a salt? Do I need to run something like this in my model: self.password_hash = hash(salt + p)
Argh so confused I used to get salts and hashes utterly and now they've changed it all. Terrible, unclear docs...they appear to show you how to use bcrypt without a salt with loads of examples, and then briefly mention how to do it properly with a salt down at the bottom.
Could someone please give me an example how to use the new version of bcrypt to generate a salt and hash, and how to authenticate?

A: bcrypt got everything covered for you. Your password digest consists of a few types of information, bcrypt algorithm type, cost, salt and the checksum.
for example:
my_password = BCrypt::Password.create("my password")
#=> "$2a$10$.kyRS8M3OICtvjBpdDd1seUtlvPKO5CmYz1VM49JL7cJWZDaoYWT."

The first part: $2a$ is the variant of the algorithm see: Where 2x prefix are used in BCrypt?
The second part 10 is the cost parameter, you can increase it to slow down the process (logarithmic value) by providing a hash {cost: 12} as the second argument to create.
Now if you call my_password.salt you get "$2a$10$.kyRS8M3OICtvjBpdDd1se" which identifies the part that is being used as the key to creating your checksum.
And finally, your checksum is "UtlvPKO5CmYz1VM49JL7cJWZDaoYWT.". That's the reason if you call create the second time the string is going to be different as another salt will be used.
But as I mentioned earlier you don't need to do anything extra as all these are being taken care of for you.

A: Okay, the has_secure_password is really cool. You don't need to worry about salts and hashes anymore, the salt and hash are stored as one attribute ( password_digest) in the database.
It's saved in such a way that bcrypt knows which part of the password_digest string is the salt, and what is the hash.
If you're setting up authentication from scratch, you literally need to do the following:
1) Add the bcrypt rails gem:
gem bcrypt-rails

2) Add the has_secure_password method to the model tasked with handling your user records:
class User < ActiveRecord::Base
    has_secure_password
end

3) Make sure your users table has a password_digest column:
class CreateUser < ActiveRecord::Migration
    create_table :users do |t|
        t.username
        t.password_digest
    end
end

4) Create a new method to create a a new empty user instance for the form to use:
class UsersController < ApplicationController
    def new
        @user = User.new
    end
end

5) In the new view, make a form that creates populates the params hash' :password and :username entries:
<% form_for( @user ) do |f| %>
    <%= f.text_field :username %>
    <%= f.password_field :password %>
<% end %>

6) Back in our controller, permit the username and the password using strong params. The whole reason behind strong params is to prevent some cheeky chappy from using dev tools to create their own html form field (such as one pertaining to id) and populating the database with malicious data:
class UsersController < ApplicationController
    def new
        @user = User.new
    end

    private

    def user_params
           params.require(:user).permit(:username, :password)
    end
end

7) Let's create the create method that will use these permitted entries to create a new user, populated by the form:
class UsersController < ApplicationController
    def new
        @user = User.new
    end

    def create
            @user = User.new(user_params)
            @user.save
            redirect_to root_path
    end

    private

    def user_params
           params.require(:user).permit(:username, :password)
    end
end

Set up your routes as you see fit, and that's it! The user record's password_digest column will be automatically populated with one string comprised of a salt appended with the hash of the password. Very elegant.
All you need to remember: password -> password_digest.
In order to authorise the user and signout the user, create a sessions controller with a create method and a destroy method:
def create
  user = User.find_by_email(params[:email])
  if user && user.authenticate(params[:password])
    session[:user_id] = user.id
    redirect_to admin_root_path, :notice => "Welcome back, #{user.username}"
  else
    flash.now.alert = "Invalid email or password"
    redirect_to root_path
  end
end

def destroy
  reset_session
  flash[:info] = "Signed out successfully!"
  redirect_to root_path
end

Hope this helps someone!


text:
Q: elements of HashMap are in the wrong order I need to read two columns (both String) from a file and keep the values of the first column in a HashMap where the Integer is the counter.
For example if the file I am reading is
Apple Fruit
PC    Device
Pen   Tool
...

and the code is
    String line="";
    int counter=1;
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt"),"Unicode"));
    while ((line = reader.readLine()) != null)
    {
        String[] words;
        words= st.split(" ");
            tokens.put(counter, words[0]);
        counter+=1;
    }

The problem is when I print The HashMap values, I found the values are in different order of that in the origianl file
        for (Map.Entry<Integer, String> token:tokens.entrySet())
    {
        System.out.println(token.getKey() + token.getValue());
    }

I got the following
1   Apple
3   Pen
4   whatever
2   ..etc

I do not know what is the problem?! can you please help me with that

A: HashMap is not ordered.  You don't have any control over what order the items appear in.  If you want an ordered map, you can use, for example, TreeMap.
EDIT: thanks to those that brought this up: TreeMap will keep items in the natural sorting order (i.e. in your case in alphabetical order).  LinkedHashMap will preserve the order of insertion.

A: Use LinkedHashMap , if you want insertion order back. By default HashMap's iterator doesn't guarantee insertion order.

A: As the documentation clearly states, HashMaps are unordered.
The enumeration order is determined by the hascodes of the keys.
If you want to preserve insertion order when enumerating the map, use LinkedHashMap.
If you want enumeration order to follow the natural ordering of the keys, use TreeMap.

A: HashMap is not an ordered Collection. (It is not even a Collection) It is more like a dictionary.
If you want to perserve the order of the items you can either use a TreeMap or a LinkedHashMap.
The difference between these is that TreeMap keeps them ordered by their natural sort order while LinkedHashMap keeps the insertion order.
In most cases where you would like to have something like with using a List you can use the LinkedHashMap.
TreeMap uses a red-black tree for its internal implementation while LinkedHashMap uses doubly linked list.
My suggestion is that you should refer to the official documentation. There you will find thorough explanations.
Additionally the idiomatic way to iterate over Maps is this:
for(Integer key : map.keySet()) {
    String myString = map.get(key);
    // ...
}


text:
Q: Merge DataGrid ColumnHeaders I would like to merge two column-Headers. Before you go and mark this question as duplicate please read further. I don't want a super-Header. I just want to merge two column-headers. Take a look at image below:

Can you see two columns with headers Mobile Number 1 and Mobile Number 2? I want to show there only 1 column header as Mobile Numbers.
Here is the XAML used for creating above mentioned dataGrid:
<DataGrid Grid.Row="1" Margin="0,10,0,0" ItemsSource="{Binding Ledgers}" IsReadOnly="True" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Customer Name" Binding="{Binding LedgerName}" />
        <DataGridTextColumn Header="City" Binding="{Binding City}" />
        <DataGridTextColumn Header="Mobile Number 1" Binding="{Binding MobileNo1}" />
        <DataGridTextColumn Header="Mobile Number 2" Binding="{Binding MobileNo2}" />
        <DataGridTextColumn Header="Opening Balance" Binding="{Binding OpeningBalance}" />
    </DataGrid.Columns>
</DataGrid>

Update1:

Update2
I have created a converter as follows:
public class MobileNumberFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value != DependencyProperty.UnsetValue)
        {
            if (value.ToString().Length <= 15)
            {
                int spacesToAdd = 15 - value.ToString().Length;
                string s = value.ToString().PadRight(value.ToString().Length + spacesToAdd);
                return s;
            }

            return value.ToString().Substring(0, value.ToString().Length - 3) + "...";
        }

        return "";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I have used it in XAML as follows:
<DataGridTextColumn Header="Mobile Numbers">
    <DataGridTextColumn.Binding>
        <MultiBinding StringFormat=" {0} {1}">
            <Binding Path="MobileNo1" Converter="{StaticResource mobileNumberFormatConverter}"/>
            <Binding Path="MobileNo2" Converter="{StaticResource mobileNumberFormatConverter}"/>
        </MultiBinding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

The output I got:

Update3:
At last I got the desired output.
Here is the code for Converter:
public class MobileNumberFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null && value != DependencyProperty.UnsetValue)
        {
            if (parameter.ToString().ToUpper() == "N")
            {
                if (value.ToString().Length <= 15)
                {
                    return value.ToString();
                }
                else
                {
                    return value.ToString().Substring(0, 12);
                }
            }
            else if (parameter.ToString().ToUpper() == "S")
            {
                if (value.ToString().Length <= 15)
                {
                    int spacesToAdd = 15 - value.ToString().Length;
                    string spaces = "";
                    return spaces.PadRight(spacesToAdd);
                }
                else
                {
                    return "...";
                }
            }
        }

        return "";
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Here is my XAML:
<DataGridTemplateColumn Header="Mobile Numbers">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock>
                <Run Text="{Binding MobileNo1, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=N}" />
                <Run Text="{Binding MobileNo1, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=S}" FontFamily="Consolas"/>
                <Run Text="   " FontFamily="Consolas"/>
                <Run Text="{Binding MobileNo2, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=N}" />
                <Run Text="{Binding MobileNo2, Converter={StaticResource mobileNumberFormatConverter}, ConverterParameter=S}" FontFamily="Consolas"/>
            </TextBlock>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Output:

A: Try this
  <DataGridTextColumn Header="Mobile Numbers">
                <DataGridTextColumn.Binding>
                    <MultiBinding StringFormat=" {0} {1}" Converter="{StaticResource YourConverter}">
                        <Binding Path="MobileNo1"/>
                        <Binding Path="MobileNo2"/>
                    </MultiBinding>
                </DataGridTextColumn.Binding>
  </DataGridTextColumn>


text:
Q: How do I copy a list and keep items after list.clear(); I've been trying to add a list to a dictionary<int, struct arts>.
When I add it, then clear the list like list.clear(); then the
Information that I have copied in a dictionary is all cleared as well.
How can I fix this, please?
for (int i = 0; i < current_artslist1.Count; i++)//
                {
                    cnt++;
                    tmp_list1.Add(current_artslist1[i]);
                    if (cnt == limit)
                    {
                        art_small_page++;
                        cnt = 0;
                        artdict_small_tmp.Add(art_small_page, tmp_list1);
                        tmp_list1.Clear();
                    }
                }

A: The problem is:
artdict_small_tmp.Add(art_small_page, tmp_list1);

does not add the 'items' from the list.  It add a reference to tmp_list1, which you are then clearing.  So the reference to that list is pointing to the cleared list.
Use .ToList() to take a copy of the items in a list and put them in a new list:
artdict_small_tmp.Add(art_small_page, tmp_list1.ToList());

This adds a new list with the items from tmp_list1, not a reference to tmp_list1.
Now, when you clear tmp_list1, the new list created in the above line will remain untouched.


text:
Q: getting all html in the console trying ajax call with autocomplete <!DOCTYPE html>

    <meta http-equiv="Content-Language" content="en-us">
    <title>PHP MySQL Typeahead Autocomplete</title>
    <meta charset="utf-8">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

        </script>

<?php
/*include_once('connection.php');

$conn = new Database();*/

$hostname = "localhost";
$username = "root";
$password = "";
$databasae = "employee";
if(isset($_POST['term'])){
    $query = $_POST['term'];

 $db = new mysqli($hostname,$username,$password,$databasae);

    //get search term
    $searchTerm = $_POST['term'];

    //get matched data from skills table
    $query = $db->query("SELECT * FROM city WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
    while ($row = $query->fetch_assoc()) {
        $data[] = $row['name'];
    }

    //return json data
    echo json_encode($data);
}

?>

        Enter City Name:

        <input type="text" name="city" class="city" id="skills" placeholder="Enter City Name" id="city">

I'm getting correct value in the network but it does not populating data in suggestion-box div.
I can't figure out where i'm mistaking.

A: Is it possible that you accidentally replaced 'data' with 'success' in the 'success' callback?
                    $("#skills").keyup(function(){
                        $.ajax({
                            type: 'post',
                            url: 'singleton.php/',
                            data: 'term='+$(this).val(),
                            success: function(success){
                                $("#suggesstion-box").html(data);
                            },
                            error: function(error){
                                console.log("error");
                            }
                        })
                    })

Should't it be
success: function(data) {
    $("#suggesstion-box").html(data);
}

?


text:
Q: Why does rspec 3 fail with error: only `receive_messages` matchers are supported? I am attempting to upgrade a project from RSpec 2 to RSpec 3, but it is failing with the following error:
 Failure/Error: Unable to find matching line from backtrace
   only the `receive` or `receive_messages` matchers are supported with `expect(...).to`, but you have provided: #<RSpec::Matchers::BuiltIn::Equal:0x007f99a974a230>

Here is the line:
expect(last_response.ok?).to be true

This post suggests one need only
require 'rspec/expectations'
include RSpec::Matchers

However, I have done this and it still reports the error. This user also seemed to encounter this issue but has not been able to elicit a solution as of 3/30/2015.
I am using rspec with Sinatra and do not use cucumber or spinach.
Can anyone explain how to resolve this error in RSpec 3? Thanks.

A: I have corrected this issue by using extend instead of include for RSpec::Matchers. While debugging this and attempting to integrate pry, I found this post which suggested the change.
Thus, my code now looks like:
extend RSpec::Matchers

And not
include RSpec::Matchers


text:
Q: mat-tab-group exceeds parent div width I've a searched about this problem, and seems it's because mat-tab-group was created also with flex layouts, and for some reason, it's interfering or ignoring the widths of the parent div.

      <mat-tab-group>
        <mat-tab label="Records">
          <ng-template matTabContent>
            <app-voice-records>

            </app-voice-records>
          </ng-template>
        </mat-tab>
      </mat-tab-group>

How it looks. It shouldn't surpass the cyan background.

A: Sometimes vh and vw don't behave as expected. Seeing your layout it was evident that for some reason it wasn't taking the full width of the screen for it's calculations and this could be one of the side effects of using those units. This is because vh for example is equal to 1% of the height of the initial containing block and this containing block is not always the same. Also when fxFlex is being used I usually see people not using the units and often just using the number that I think that defaults to percentages which are, to me, more reliable but I think it all boils down to which block is taken as the initial containing one by the layout.


text:
Q: Refresh Folder in spring boot after uploading a file I upload a file using my spring boot Application in the path : C:\Users\myPC\eclipse-workspace\myPROJECT\src\main\resources\static\files\
The probleme is that the url :
http://localhost:8088/files/file_example.png not working unless i refresh the folder src/main/ressources/static/files manually from Eclipse IDE.
I search in web about this probleme but i found nothing to fix it.
Any help would be appreciated.
Thanks.

A: If you are working with Eclipse, such as my case, go to Window -> Preferences and search for workspace, then check Refresh using native hooks or polling.
it worked for me.


text:
Q: Custom layout with JsonArray Here is my code :
public class Fragment1 extends SherlockFragment {
        ListView lista;
        ArrayList<String> items = new ArrayList<String>();
        private ArrayList<MyListAdapter> thelista = new ArrayList<MyListAdapter>();
        View rootView;
        ListView list;
        TextView title, price;
        MyListAdapter adapter;

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            // TODO Auto-generated method stub
            super.onCreateOptionsMenu(menu, inflater);
            MenuInflater blowup = this.getSherlockActivity()
                    .getSupportMenuInflater();
            blowup.inflate(R.menu.menuxml, menu);
            return;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            rootView = inflater.inflate(R.layout.main, container, false);
            ActionBar ab = this.getSherlockActivity().getSupportActionBar();
            ab.setTitle("");
            title = (TextView) rootView.findViewById(R.id.title);
            price = (TextView) rootView.findViewById(R.id.details);

            list = (ListView) rootView.findViewById(R.id.list);
            SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(
                    this.getSherlockActivity(), R.array.phones_array,
                    android.R.layout.simple_spinner_dropdown_item);
            ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
            ab.setListNavigationCallbacks(mSpinnerAdapter, null);
            StrictMode.enableDefaults();
            getData();
            return rootView;

        }

        public void getData() {
            String result = "";
            InputStream isr = null;
            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httpost = new HttpPost(
                        "http://10.0.2.2/AndroidArabia/android3arabiya.php");
                HttpResponse resposne = httpclient.execute(httpost);
                HttpEntity entity = resposne.getEntity();
                isr = entity.getContent();

            } catch (Exception e) {
                Log.e("log_tag", "error in http connection" + e.toString());
                Toast.makeText(getSherlockActivity(),
                        "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                        .show();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        isr, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                isr.close();
                result = sb.toString();
            } catch (Exception e) {
                Log.e("log_tag", "Error converting Result " + e.toString());
            }
            try {
                JSONArray jArray = new JSONArray(result);
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json = jArray.getJSONObject(i);
                    thelista.add(new MyListAdapter(json.getString("PhoneName"),
                            json.getString("PhonePrice")));
                }
                list.setAdapter((ListAdapter) thelista);

            } catch (Exception e) {
                Log.e("lag_tag", "ERROR PARSING DATA" + e.toString());
                Toast.makeText(getSherlockActivity(),
                        "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                        .show();
            }

MyListAdapter Code :
public class MyListAdapter extends BaseAdapter {

    private String[] data;
    private String[] data2;
    private Context context;

    public MyListAdapter(String string, String string2) {
        // TODO Auto-generated constructor stub
    }

    @Override
    public int getCount() {
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        return data[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = LayoutInflater.from(context).inflate(R.layout.pricelist,
                parent, false);

        TextView text1 = (TextView) rowView.findViewById(R.id.title);
        TextView text2 = (TextView) rowView.findViewById(R.id.details);
        text1.setText(data[position]);
        text2.setText(data2[position]);
        return rowView;
    }

}

            }

price list xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="5dip" >

    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip"
        android:background="@drawable/image_bg"
        android:padding="3dip" >

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="50dip"
            android:layout_height="50dip" />
    </LinearLayout>

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/thumbnail"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Smartphone Name"
        android:textColor="#040404"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="sans" />

    <TextView
        android:id="@+id/details"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:layout_marginTop="1dip"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Smartphone Price"
        android:textColor="#343434"
        android:textSize="10dip" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/rating" />

</RelativeLayout>

And Finally main xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp" >
    </ListView>

</LinearLayout>

I'm not an expert in custom layout but i'm getting an error in parsing the JSON Array into the custom listview. Of course my main goal is to fill the custom listview with the JSON array but i don't have any clue how to do it and non of question asked before have helped me.
Can anyone help me right here?
Here all the info, the program is stopping at the JSon catch exception and giving me the toastBox : Couldn't connect to the internet. any suggestion? :)

A: Fragment1.java

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.app.ActionBar;
    import android.os.Bundle;
    import android.os.StrictMode;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SpinnerAdapter;
    import android.widget.TextView;
    import android.widget.Toast;

    public class Fragment1 extends SherlockFragment {
            ArrayList<String> items = new ArrayList<String>();
            ArrayList<BeanClass> beanClass=new ArrayList<BeanClass>();
            View rootView;
            ListView list;
            TextView title, price;
            MyListAdapter adapter;

            @Override
            public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
                // TODO Auto-generated method stub
                super.onCreateOptionsMenu(menu, inflater);
                MenuInflater blowup = this.getSherlockActivity()
                        .getSupportMenuInflater();
                blowup.inflate(R.menu.menuxml, menu);
                return;
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                    Bundle savedInstanceState) {
                rootView = inflater.inflate(R.layout.main, container, false);
                ActionBar ab = this.getSherlockActivity().getSupportActionBar();
                ab.setTitle("");
                title = (TextView) rootView.findViewById(R.id.title);
                price = (TextView) rootView.findViewById(R.id.details);

                list = (ListView) rootView.findViewById(R.id.list);
                SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(
                        this.getSherlockActivity(), R.array.phones_array,
                        android.R.layout.simple_spinner_dropdown_item);
                ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
                ab.setListNavigationCallbacks(mSpinnerAdapter, null);
                StrictMode.enableDefaults();
                getData();
                return rootView;

            }

            public void getData() {
                String result = "";
                InputStream isr = null;
                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httpost = new HttpPost(
                            "http://10.0.2.2/AndroidArabia/android3arabiya.php");
                    HttpResponse resposne = httpclient.execute(httpost);
                    HttpEntity entity = resposne.getEntity();
                    isr = entity.getContent();

                } catch (Exception e) {
                 /*   Log.e("log_tag", "error in http connection" + e.toString());
                    Toast.makeText(getSherlockActivity(),
                            "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                            .show();*/
                }
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            isr, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    isr.close();
                    result = sb.toString();
                } catch (Exception e) {
                    Log.e("log_tag", "Error converting Result " + e.toString());
                }
                try {
                    JSONArray jArray = new JSONArray(result);
                    for (int i = 0; i < jArray.length(); i++) {
                        JSONObject json = jArray.getJSONObject(i);
                    /*    thelista.add(new MyListAdapter(json.getString("PhoneName"),
                                json.getString("PhonePrice")));*/
                        beanClass.add(new BeanClass(json.getString("PhoneName"),
                                json.getString("PhonePrice"));
                    }
                    list.setAdapter(new MyListAdapter(Fragment1.this, beanClass));

                } catch (Exception e) {
                    Log.e("lag_tag", "ERROR PARSING DATA" + e.toString());
                    Toast.makeText(getSherlockActivity(),
                            "Couldn't Connect To The Internet", Toast.LENGTH_LONG)
                            .show();
                }

Your Adapter

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<BeanClass> beanClass=new ArrayList<BeanClass>();

    public MyListAdapter(Context context,ArrayList<BeanClass> beanClass) {
        // TODO Auto-generated constructor stub
        this.context=context;
        this.beanClass=beanClass;
    }

    @Override
    public int getCount() {
        return beanClass.size();
    }

    @Override
    public Object getItem(int position) {
        return beanClass.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View rowView = LayoutInflater.from(context).inflate(R.layout.pricelist,
                parent, false);

        TextView text1 = (TextView) rowView.findViewById(R.id.title);
        TextView text2 = (TextView) rowView.findViewById(R.id.details);
        text1.setText(beanClass.get(position).phoneName);
        text2.setText(beanClass.get(position).phonePrice);
        return rowView;
    }

}

            }

BeanClasss

public class BeanClass {

    String phoneName;
    String phonePrice;
    public String getPhoneName() {
        return phoneName;
    }
    public String getPhonePrice() {
        return phonePrice;
    }
    public void setPhoneName(String phoneName) {
        this.phoneName = phoneName;
    }
    public void setPhonePrice(String phonePrice) {
        this.phonePrice = phonePrice;
    }
    public BeanClass(String phoneName, String phonePrice) {
        super();
        this.phoneName = phoneName;
        this.phonePrice = phonePrice;
    }

}


text:
Q: GNUPLOT remove overlapping between xtick labels In GnuPlot, i am setting xtics to something like this:

set xtics
  ("AIM" 0.00000, "gtalk" 2.00000, "rtp-multicast-filetransfer" 4.00000,
  "sipc_music" 6.00000, "skype1" 8.00000, "skype2" 10.00000,
  "voip-extension" 12.00000, "voip-extension2downata" 14.00000,
  "ymessenger" 16.00000)

The problem is, that these labels overlap with each other in the plot, so how can i remove/overcome this overlapping?
Can I increase the length between xticks or write some kind of legend showing:
rmf : rtp-multicast-filetransfer ?

A: This might not be the solution you want, but you can rotate labels with:
set xtics rotate by -45
This would rotate tick labels at the x-axis by -45°.


text:
Q: Implementing Prim's MST in Java I'm having trouble getting my code to follow CLRS's example of a Minimum Spanning Tree (MST) in page 635. I'm also implementing CLRS's pseudo-code for MST-Prim quite literally, which is

In particular, I'm implementing the following graph using an adjacency list:
So I actually have two issues. The first is that after adding the node b to the MST, my code picks as next element in the PriorityQueue node h instead of node c. I'm not sure how Java's implementation picks elements in case of ties, so if there's something I can do about this please advise.
To temporarily circumvent this issue I modified the edge a-h to have a weight of 9.
Everything then runs fine until it picks node d instead of g after adding f to the MST, which I find really strange since the PriorityQueue clearly has g with key=6.
My implementation is below:
import java.util.LinkedList;
import java.util.PriorityQueue;

class Edge{

    private Node source;
    private Node destination;
    private int weight;

    public void setSource(Node source) {
        this.source = source;
    }

    public void setDestination(Node destination) {
        this.destination = destination;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

    public int getWeight() {
        return this.weight;
    }

    public Node getSource() {
        return this.source;
    }

    public Node getDestination() {
        return this.destination;
    }

}

class Node implements Comparable<Node>{
    private String label;
    private LinkedList<Edge> edges;
    private int key;
    private Node daddy;

    Node() {
        this.edges = new LinkedList();
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public void setKey(int key) {
        this.key = key;
    }

    public void setDaddy(Node daddy) {
        this.daddy = daddy;
    }

    public String getLabel() {
        return this.label;
    }

    public int getKey() { return this.key; }

    public LinkedList getEdges() {
        return this.edges;
    }

    @Override
    public int compareTo(Node o) {
        if (this.getKey() > o.getKey()) {
            return 1;
        }
        else if (this.getKey() < o.getKey()) {
            return -1;
        }
        else {
            return 0;
        }
    }
}

public class Graph {

    private int numberOfNodes;
    private Node[] weightedGraph;

    public Graph(int graphV) {

        this.numberOfNodes = graphV;
        this.weightedGraph = new Node[this.numberOfNodes];
        for (int i = 0; i < this.numberOfNodes; i++) {
            this.weightedGraph[i] = new Node();
        }
    }

    public void addEdge(String sourceLabel, String destinationLabel, int weight) {

        Node sourceNode = null;
        Node destinationNode = null;

        for (Node node: this.weightedGraph) {
            if (node.getLabel().contains(sourceLabel)) {
                sourceNode = node;
            }
            if (node.getLabel().contains(destinationLabel)) {
                destinationNode = node;
            }
        }

        Edge e = new Edge();
        e.setWeight(weight);
        e.setSource(sourceNode);
        e.setDestination(destinationNode);
        sourceNode.getEdges().add(e);

    }

    public void minimumSpanningTree(String root) {
        Node rootNode = null;
        for (Node vertex: this.weightedGraph) {
            vertex.setKey(Integer.MAX_VALUE);
            vertex.setDaddy(null);
            if (vertex.getLabel().contains(root)) {
                rootNode = vertex;
            }
        }

        rootNode.setKey(0);

        PriorityQueue<Node> nodePriorityQueue = new PriorityQueue<>();

        for (Node vertex: this.weightedGraph) {
            nodePriorityQueue.add(vertex);
        }
        int min = 0;
        while (!nodePriorityQueue.isEmpty()) {

            Node u = nodePriorityQueue.peek();

            LinkedList<Edge> uEdges= u.getEdges();
            for (Edge e: uEdges) {
                Node v = e.getDestination();
                int u_vWeight = e.getWeight();
                if (nodePriorityQueue.contains(e.getDestination()) && u_vWeight < v.getKey()) {
                    v.setDaddy(u);
                    v.setKey(u_vWeight);
                }
            }
            nodePriorityQueue.remove(u);
            min += u.getKey();
        }

    }

    public static void main(String[] args) {

        Graph graph = new Graph(9);
        String[] nodes = new String[9];
        nodes[0] = "a";
        nodes[1] = "b";
        nodes[2] = "c";
        nodes[3] = "d";
        nodes[4] = "e";
        nodes[5] = "f";
        nodes[6] = "g";
        nodes[7] = "h";
        nodes[8] = "i";
        int pos = 0;
        for (String s: nodes) {
            graph.weightedGraph[pos].setLabel(s);
            pos += 1;
        }

        graph.addEdge("a", "b", 4);
        graph.addEdge("a", "h", 9);
        graph.addEdge("b", "h", 11);
        graph.addEdge("b", "c", 8);
        graph.addEdge("h", "i", 7);
        graph.addEdge("i", "g", 6);
        graph.addEdge("c", "f", 4);
        graph.addEdge("c", "d", 7);
        graph.addEdge("d", "e", 9);
        graph.addEdge("d", "f", 14);
        graph.addEdge("e", "f", 10);
        graph.addEdge("h", "g", 1);
        graph.addEdge("c", "i", 2);
        graph.addEdge("g", "f", 2);

        graph.minimumSpanningTree("a");

    }
}

Essentially I have three classes, Node, Edge and Graph. I included a Comparator in Node to allow the PriorityQueue to reorder elements as needed.
I build the graph, call minimumSpanningTree, which prints the following MST:
a
b
c
i
f
d
e
h
g

Instead of doing a-b-c-i-f-g as in CLRS's example which I show below:

I don't really understand why it's picking node d instead of g when g clearly has the lowest key, which inspecting by debugging the priorityQueue corroborates.
Help is greatly appreciated.

A: I figured out my problem. It turns out that the edges in the adjacency list representation I built are directed. To solve this I just added the reverse edges and everything works as expected.
And it also turns out that the priority queue does not update its elements upon removal of one of them. According to some other answers on SO about priority queues (PQ) not updating, I removed and added the nodes from the PQ whose keys are updated inside the for loop. Does anyone have a better suggestion? Updated code of minimumSpanningTree is below:
public void minimumSpanningTree(String root) {

        ArrayList<Node> msTree = new ArrayList<>();

        Node rootNode = null;
        for (Node vertex: this.weightedGraph) {
            vertex.setKey(Integer.MAX_VALUE);
            vertex.setDaddy(null);
            if (vertex.getLabel().contains(root)) {
                rootNode = vertex;
            }
        }

        rootNode.setKey(0);

        PriorityQueue<Node> nodePriorityQueue = new PriorityQueue<>();

        for (Node vertex: this.weightedGraph) {
            nodePriorityQueue.add(vertex);
        }
        int min = 0;
        while (!nodePriorityQueue.isEmpty()) {

            Node u = nodePriorityQueue.peek();

            LinkedList<Edge> uEdges= u.getEdges();
            for (Edge e: uEdges) {
                Node v = e.getDestination();
                int u_vWeight = e.getWeight();
                if (nodePriorityQueue.contains(e.getDestination()) && u_vWeight < v.getKey()) {
                    nodePriorityQueue.remove(v);
                    v.setDaddy(u);
                    v.setKey(u_vWeight);
                    nodePriorityQueue.add(v);
                }
            }
            msTree.add(u);
            System.out.println(u.getLabel());
            nodePriorityQueue.remove(u);
        }

EDIT: However, I'm having the same problem with edges a-h and a-b. I think its still a MST, but is there a way I can prioritize visiting node b before h? I.e. in case of ties in the priority queue, prioritize a key with a lower alphanumeric priority?


text:
Q: Is there a concept of a master page (like in asp.net) for WPF? I've started a WPF (web-based) application and it has multiple pages.  I want to implement the concept of a Master page in WPF, so that when I make changes in the design/layout of one page then all the others pages will follow suit without all the copy and paste.

A: I don't think the concept of Master Page is valid in WPF basically because there are no pages.
In WPF exists styles, templates and DataTemplates. Not only that, using the DockPanel and other containers you can achieve most of the functionality provided by ASP.NET Master Pages.
In any case, if you still the need of the master pages, I suggest check this article:
http://www.codeproject.com/KB/WPF/WPFMasterPageControl.aspx
HTH

A: The WPF Magellan Framework (open source) have Master pages (and other several interesting concepts)

A: use a master view and put a ContentControl with the master view, then bind the Content property to a property on your data context and set the property to an instance of a  UserControl which will then populate the content section.
I will provide some more detail later

A: You can use global styles to apply a consistent look and feel across your app.  As for functionality of a master page.  Look at the MVVM pattern.  Microsoft has an implementation but there are others.
It let's you define a shell in xaml and specify regions that act sort of like content placeholder's in ASP.NET.  Then you write user controls that get loaded into those regions in the shell.  It's a lot more involved than using a master page with ASP.NET though.  But conceptually similar as far as screen layout goes.
As always, not a bad place to start getting an overview
http://en.wikipedia.org/wiki/MVVM
Tons more stuff on MSDN and so on.

A: You can use Prism open source framework (downloadable from: patterns & practices: Prism) and using that you can create a Shell Window, which can be used as the MainWindow for your WPF project. Then, inside your Shell window, you can create Regions and inject your views into those regions.
Below is what MSDN has to say about Shell (See: Composing the User Interface using Prism):

The shell is the application root object that contains the primary UI content. In a Windows Presentation Foundation (WPF) application, the shell is the Window object. In a Silverlight application, the shell is the RootVisualUserControl.
  The shell plays the role of a master page providing the layout structure for the application. The shell contains one or more named regions where modules can specify the views that will appear. It can also define certain top-level UI elements, such as the background, main menu, and toolbar.
  The shell defines the overall appearance of the application. It might define styles and borders that are present and visible in the shell layout itself, and it might also define styles, templates, and themes that will be applied to the views that are plugged into the shell.
  Typically, the shell is a part of the WPF application project or primary Silverlight project. The assembly that contains the shell might or might not reference the assemblies that contain the views to be loaded in the shell's regions.

Basic Prism Shell structure with WPF:


text:
Q: Print multiple filenames to specific lines in txt file I am trying to print a list of filenames to a text file, with the requirement of printing certain filenames on the same line. For example, I have 4 files.
Paleo_R1.fastq
Paleo_R2.fastq
Vegan_R1.fastq
Vegan_R2.fastq

I want the output to be
Paleo_R1.fastq Paleo_R2.fastq
Vegan_R1.fastq Vegan_R2.fastq

I know I can use the ls function and direct output to a text file, using ls >> file.txt but there are no options to print specific input line items to specific output lines.
Additionally, I am aware of that I can use for loops like this >
for file in Vegan*R1*.fastq;
do echo $file ${file%_R1.fastq}_R2.fastq >> file.txt;
done

But I do not want to have a separate command for each filename, ie. for vegan and paleo.
Is there a way to print certain lines to specific output lines (print input lines 1 and 2 to output line 1, and input lines 3 and 4 to output line 2, and so on...)
EDIT: The rule is based on every N=2 files, not the file names.

A: Maybe
$ ls *.fastq | xargs -n2
Bar_R1.fastq Bar_R2.fastq
Bar_R3.fastq Foo_R1.fastq
Foo_R2.fastq Foo_R3.fastq
Paleo_R1.fastq Paleo_R2.fastq
Vegan_R1.fastq Vegan_R2.fastq

or for column output
$ ls *.fastq | xargs -n2 | column -t
Bar_R1.fastq    Bar_R2.fastq
Bar_R3.fastq    Foo_R1.fastq
Foo_R2.fastq    Foo_R3.fastq
Paleo_R1.fastq  Paleo_R2.fastq
Vegan_R1.fastq  Vegan_R2.fastq

(add >> file.txt to the command to append the output to the file)
Note that both examples only work with filenames without spaces.
For files with spaces:
$ for i in *.fastq; do echo -ne "$i\0"; done | xargs -0 -n2

A: Using the solution you already have, it's just a matter of not specifying the filename prefix Vegan:
for file in *_R1.fastq; do
    printf '%s %s\n' "$file" "${file%_R1.fastq}_R2.fastq"
done >file.txt

Using printf and redirecting after the loop instead of for each output command is just my personal preference.
For the given filenames, this generates file.txt with
Paleo_R1.fastq Paleo_R2.fastq
Vegan_R1.fastq Vegan_R2.fastq

A: One option would be to set the desired filenames as the current shell arguments and then ask printf to print them in pairs:
set -- *
printf '%s %s\n' "$@"  > output

or only certain files:
set -- *_R?.fastq

The order depends on the expansion of the wildcard that you used. If you want more control over the sequencing, then you could manually split the glob up somehow, for example:
set -- Paleo*.fastq Vegan*.fastq Omnivore*.fastq FastFood*.fastq


text:
Q: Passing in array of functions as parameter, for each func in functions run the function I am trying to pass in an array of functions as a parameter to function x then execute them within the function x. I will also somehow pass in parameters but some of the parameters are only initialised within function x.
Some functions include things like:
_showData(data,type);
console.log(data);
$('#loading').remove();

Here is a sample:
// Called somewhere else
runFunctions([$('.dashboard').remove, $('.screen-loading').remove]);

var runFunctions = function(functions){
  // do some things
  for (var i = 0; i < functions.length; i++){
     functions[i]();
}

Any ideas?
EDIT:
Sorry I just realised the program doesn't know what the objects are because I'm changing scope with an ajax call.
var runFunctions = function(functions){
  $.ajax({
    method: "POST",
    url: "php/database.php",
    dataType: "JSON",
    data: {type:type},
    success: function(data, type){
      for (var i = 0; i < functions.length; i++){
        functions[i]();
      }
    }
  })
}

What about this:
  _accessDatabase(
    function(onSuccess){
      $('.dashboard').remove();
      var type = 'home';
      _showData(data,type); // it doesn't know what data is, how can I pass it through?
      $('.screen-loading').remove();
    }
  );

var _accessDatabase = function(onSuccess){
  $.ajax({
    method: "POST",
    url: "php/database.php",
    dataType: "JSON",
    data: {},
    success: function(data){
      onSuccess(data);
    }
  })
}

I want to pass through var data to the onSuccess function, how can I do this?
Solved with:
var _request_successful = function onSuccess (data){
  console.log("running onSuccess");
  $('.dashboard').remove();
  var type = 'home';
  _showData(data,type);
  $('.screen-loading').remove();
}

_accessDatabase(_request_successful);

var _accessDatabase = function(onSuccess){
  $.ajax({
    method: "POST",
    url: "php/database.php",
    dataType: "JSON",
    data: {},
    success: function(data){
      onSuccess(data);
    }
  })
}

A: The problem with this code is that the functions that you're calling within the forLoop aren't bound to anything. Take this instead.
// Called somewhere else
runFunctions([
  $('.dashboard').remove.bind($('.dashboard'))
, $('.screen-loading').remove.bind($('.screen-loading'))
]);

function runFunctions(functions){
  // do some things
  for (var i = 0; i < functions.length; i++){
     console.log("running")
     functions[i]();
  }
}

What you could do instead is this:
function call(method, objs) {
  objs.forEach(function (obj) {
     obj[method]()
  })
}
call('remove', [$('.dashboard'), $('.screen-loading')])

Here's a working fiddle: https://jsfiddle.net/ogfgocp4/
To explain a bit how it works, I don't know exactly the internal of JavaScript, but when you do: $('.dashboard').remove, it will return you the remove function. If you call it immediatly, it will be bound to the object which give you the method. If you affect it to something else, then it will be bound to the object it's being called from.
Here's a small snippet of code that explains it well I guess.
var obj = {
    fun: function () {
    console.log(this)
  }
}
var fun2 = {
    a: 1
}

//this -> obj
obj.fun()

// this -> window
fun = obj.fun
fun()

// this -> fun2
fun2.fun = obj.fun
fun2.fun()

When you call obj.fun, this will be the object obj. When you affect the method to a var, this then become window as it is the default object in this scope. Then if we finally bind the function to object fun2 and call it immediatly, this is now the object fun2.


text:
Q: how to retrive second half records from given table how to display second-half records from a given table in oracle
SELECT * FROM EMPLOYEE_DETAILS
WHERE ROWNUM <= (SELECT COUNT(*)/2 FROM EMPLOYEE_DETAILS);

it is displaying first half


text:
Q: Silverlight - Bing Pushpin on click navigation I am wanting to add an on click even for a puship pin which will show a pop up windows eg.. Message.Show window.
Also, I want to have an OnCLick navigate too option.
Here is a snippet of my code.
Pushpin palmerstonN = new Pushpin();
            palmerstonN.Background = new SolidColorBrush(Colors.Brown);
            palmerstonN.Location = new GeoCoordinate(-40.3541236542693, 175.596991862399);
            palmerstonN.Content = "Arena Manawatu - Palmerston North";

this.map1.Children.Add(palmerstonN);

Any Ideas?

A: A PushPin  has a MouseLeftButtonUp event that you can use to handle a click on the pushping. You could do something like:
Pushpin palmerstonN = new Pushpin();
        palmerstonN.Background = new SolidColorBrush(Colors.Brown);
        palmerstonN.Location = new GeoCoordinate(-40.3541236542693, 175.596991862399);
        palmerstonN.Content = "Arena Manawatu - Palmerston North";
        palmerstonN.MouseLeftButtonUp += new MouseButtonEventHandler(palmerstonN_MouseLeftButtonUp);

this.map1.Children.Add(palmerstonN);
}

void palmerstonN_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        Messabox.Show("My messagebox");
    }

I hope this helps!


text:
Q: Is it possible to update the php file while it is viewed? Let's say I have a PHP file that contains a POST or GET variable:
if(isset($_POST['data'])){
    $data = $_POST['data'];
    echo $data;
}

Is it possible to update that value, While the user is viewing that page?
So that when I (The admin) click a button on another page, A value is changed in the DB and that variable or an html element is changed?
So for example (Didn't work):
$.post('file.php', {data: data}, function(){});

Then while the user is viewing that file.php, The $data is updated with the new posted data.


text:
Q: С# получить последнюю строчку консоли Есть допустим вот такой вывод консоли. Это делается при помощи функции, и как мне получить то, что консоль мне возвратило последней строчкой? Не через какую либо функцию для получения данного вывода, а вот мы получили вывод, потом мы взяли и запихнули в переменную последнюю выведенную строку. Так можно вообще?
Вообще задание такое:

в первом процессе мы выводим строчку в консоль, запускаем второй процесс, и во втором процессе мы считываем строку, которая была записана первым процессом в консоль. Может я не правильно понял задание или просто мудрю с реализацией?

A: Решение
Я покопался и придумал решение.
Абстракция
Мы будем брать и создавать процесс сервера с 1-м listener'ом. Listener запускается параллельно отн. потока сервера (чтоб можно было прервать работу listener'а). Затем мы запускаем клиент (если в обратном порядке, то клиент выдаст ошибку TimeoutException) и появляется соединение, затем сервер берёт, и передаёт сообщение.
Реализация
Будет 2 проекта: MessagePublisher и MessageReceiver (или сервер и клиент). Обмен будем производить с помощью библиотеки System.IO.Pipes.dll (ссылка #1,2) (включена в платформу .NET Core App), а именно именованные каналы (ссылка #3), т. к. процессы создаются независимо друг от друга и не получится передать дескриптор анонимного канала.
Примечание: пропущены полноценные обработки ошибок (причина: упрощение кода).
MessagePublisher
MessagePublisher.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AssemblyName>msgpub</AssemblyName>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

App.cs
using System;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using System.Buffers;
using System.Buffers.Binary;

namespace MessagePublisher
{
    sealed class App
    {
        string? msg;
        byte[]? serMsg;

        public string Message
        {
            get
            {
                if (msg == null) throw new InvalidOperationException("Message is not readed");

                return msg;
            }
        }
        public byte[] SerializedMessage
        {
            get
            {
                if (msg == null) throw new InvalidOperationException("Message is not readed");

                return serMsg;
            }
        }

        App(ReadOnlySpan<string> args) { }

        static void Main(string[] args) => new App(args.AsSpan()).Run();
        void Run()
        {
            // Пропущена проверка на наличие такого же процесса

            Console.WriteLine("Server is working...");
            Console.WriteLine("Write message");
            Console.Write("> ");
            msg = Console.ReadLine();
            serMsg = Encoding.Unicode.GetBytes(msg);

            using var cts = new CancellationTokenSource();
            var task = Listen(cts.Token);

            Pause("Press any button to end server work...");

            cts.Cancel();
            task.Wait();

            Console.WriteLine("Server resources is disposing...");

            cts.Dispose();

            Console.WriteLine("Server resources disposed");
            Console.WriteLine("Server worked");

            Pause();
        }
        async Task Listen(CancellationToken cancellationToken = default)
        {
            using var stream = new NamedPipeServerStream("msgpub/def", PipeDirection.Out);
            using var bufferOwner = MemoryPool<byte>.Shared.Rent(4);
            var buffer = bufferOwner.Memory.Slice(0, 4);

            Console.WriteLine("Listener is working...");

            while (!cancellationToken.IsCancellationRequested)
            {
                Console.WriteLine("Listener is waiting for connection...");

                await Task.Run((Action)(() => stream.WaitForConnectionAsync(cancellationToken)));

                while (!cancellationToken.IsCancellationRequested && !stream.IsConnected) { }

                if (cancellationToken.IsCancellationRequested)
                {
                    Console.WriteLine("Cancellation...");

                    break;
                }

                Console.WriteLine("Connection getted");
                Console.WriteLine("Message is sending...");

                BinaryPrimitives.WriteInt32BigEndian(buffer.Span, serMsg!.Length);

                stream.Write(buffer.Span);
                stream.Write(serMsg);

                Console.WriteLine("Message sended");
                Console.WriteLine("Listener is disconnecting...");

                if (stream.IsConnected) stream.Disconnect();

                Console.WriteLine("Listener disconnected");
            }

            Console.WriteLine("Listener resources is disposing...");

            stream.Close();

            Console.WriteLine("Listener resources disposed");
            Console.WriteLine("Listener worked");
        }
        void Pause(string? message = null)
        {
            const string defMsg = "Press any button...";

            Console.WriteLine(message ?? defMsg);
            Console.ReadKey(true);
        }
        void PrintQuitMessageAndExit(bool isFailed = true)
        {
            Pause();

            Environment.Exit(isFailed ? -1 : 0);
        }
    }
}

MessageReceiver
MessageReceiver.csproj
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AssemblyName>msgrcv</AssemblyName>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

App.cs
using System;
using System.Text;
using System.IO;
using System.IO.Pipes;
using System.Diagnostics;
using System.Threading;
using System.Buffers;
using System.Buffers.Binary;

namespace MessageReceiver
{
    class App
    {
        App(ReadOnlySpan<string> args) { }

        static void Main(string[] args) => new App(args.AsSpan()).Run();
        void Run()
        {
            Console.WriteLine("Client is working...");

            var stream = new NamedPipeClientStream(".", "msgpub/def", PipeDirection.In);

            Console.WriteLine("Client is connecting to server...");

            try { stream.Connect(1000); }
            catch (TimeoutException) { PrintErrorMessageAndExit("Connection timed out"); }

            Console.WriteLine("Connection getted");
            Console.WriteLine("Transmission started...");

            Span<byte> encodedBufferLengthBuffer = stackalloc byte[4];

            stream.Read(encodedBufferLengthBuffer);

            var bufferLength = BinaryPrimitives.ReadInt32BigEndian(encodedBufferLengthBuffer);

            using var bufferOwner = MemoryPool<byte>.Shared.Rent(bufferLength);
            var buffer = bufferOwner.Memory.Span.Slice(0, bufferLength);

            if (stream.Read(buffer)!= bufferLength)
                PrintErrorMessageAndExit("Transmition failed");

            Console.WriteLine("Transmission completed");

            var msg = Encoding.Unicode.GetString(buffer);

            Console.WriteLine($"Received message: {msg}");
            Console.WriteLine("Client resources is disposing...");

            stream.Close();

            Console.WriteLine("Client resources disposed");
            Console.WriteLine("Client worked");

            Pause();
        }
        void Pause(string? message = null)
        {
            const string defMsg = "Press any button...";

            Console.WriteLine(message ?? defMsg);
            Console.ReadKey(true);
        }
        void PrintErrorMessageAndExit(string? message = null)
        {
            if (message != null)
            {
                var tempFc = Console.ForegroundColor;

                Console.ForegroundColor = ConsoleColor.Red;

                Console.Write("[ERROR]: ");
                Console.WriteLine(message);

                Console.ForegroundColor = tempFc;
            }

            Pause();

            Environment.Exit(-1);
        }
    }
}

Ссылки

*

*Ссылка #1 – System.IO.Pipes.dll: Документация (en-US)

*Ссылка #2 – System.IO.Pipes.dll: Документация (ru-RU (машинный перевод))

*Ссылка #3 – Практическое руководство: Использование именованных каналов для взаимодействия между процессами по сети

A: App.cs (MessagePublisher.csproj)
using env = Environment;

sealed class App
{
    string msg;

    App(string[] args)
    {
        // mute compiler
        msg = null!;
    }

    static void Main(string[] args) => new App(args).Run();
    public void Run()
    {
        const string rcvExePath = "msgrcv.exe";

        try
        {
            Console.WriteLine("Message publisher is working...");
            Console.WriteLine("Write message");
            Console.Write("> ");
            msg = Console.ReadLine();
            var encoding = Encoding.Unicode;
            var serMsgLen = encoding.GetByteCount(msg);
            var serMsgOwner = MemoryPool<byte>.Shared.Rent(serMsgLen);
            var serMsg = serMsgOwner.Memory.Slice(0, serMsgLen).Span;
            encoding.GetBytes(msg, serMsg);

            Console.WriteLine("Message publisher resources is initializing...");

            using var stream = new AnonymousPipeServerStream(PipeDirection.Out,
                HandleInheritability.Inheritable); // чтобы можно было передать в дочерний процесс

            Console.WriteLine("Message publisher resources is initialized");
            Console.WriteLine("Message receiver process is launching...");

            using var rcvProcess = new Process
            {
                StartInfo = new ProcessStartInfo(rcvExePath, stream.GetClientHandleAsString())
                {
                    UseShellExecute = false,
                }
            };
            rcvProcess.Start();

            stream.DisposeLocalCopyOfClientHandle();

            Console.WriteLine("Message receiver process is working...");

            try
            {
                Console.WriteLine("Transmission started...");

                Span<byte> encodedBufferLengthBuffer = stackalloc byte[4];
                BinaryPrimitives.WriteInt32BigEndian(encodedBufferLengthBuffer, serMsgLen);

                stream.Write(encodedBufferLengthBuffer);
                stream.Write(serMsg);
                stream.WaitForPipeDrain();

                Console.WriteLine("Transmission completed");
            }
            catch (InvalidOperationException ex) when (ex.Message.Contains("connect", StringComparison.OrdinalIgnoreCase))
            { PrintQuitMessageAndExit("Transmission aborted"); return; }

            Console.WriteLine("Message publisher is waiting for message receiver process exit");

            rcvProcess.WaitForExit();

            Console.WriteLine("Message receiver process worked");
            Console.WriteLine("Message publisher resources is disposing...");

            stream.Close();
            serMsgOwner.Dispose();
            rcvProcess.Close();

            Console.WriteLine("Message publisher resources disposed");
            Console.WriteLine("Message publisher worked");
        }
        catch (Exception ex) { PrintQuitMessageAndExit(ex.Message); }

        Pause();
    }
    void Pause(string? message = null)
    {
        const string defMsg = "Press any button...";

        Console.WriteLine(message ?? defMsg);
        Console.ReadKey(true);
    }
    void PrintQuitMessageAndExit(string? message = null, bool isError = true)
    {
        const string unknowErrMsg = "<unknow>";

        if (isError)
        {
            var tempFc = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;

            Console.Write("[ERROR]: ");
            Console.WriteLine(message ?? unknowErrMsg);

            Console.ForegroundColor = tempFc;
        }
        else if (message != null)
            Console.WriteLine(message);

        Pause();

        env.Exit(isError ? -1 : 0);
    }
}

App.cs (MessageReceiver.csproj)
using env = Environment;

sealed class App
{
    public string StreamHandle { get; }

    App(string[] args)
    {
        if (args.Length != 1) throw new ArgumentException("Invalid arg count", "args");

        StreamHandle = args[0]; // получаем дескриптор нашего потока
    }

    static void Main(string[] args) => new App(args).Run();
    public void Run()
    {
        try
        {
            Console.WriteLine("Message receiver is working...");
            Console.WriteLine("Message receiver resources is initializing...");

            using var stream = new AnonymousPipeClientStream(PipeDirection.In, StreamHandle);

            Console.WriteLine("Message receiver resources initialized");
            Console.WriteLine("Transmission started...");

            string msg;

            try
            {
                Span<byte> encodedBufferLengthBuffer = stackalloc byte[4];

                if (stream.Read(encodedBufferLengthBuffer) != 4) PrintQuitMessageAndExit("Transmission failed");

                var bufferLength = BinaryPrimitives.ReadInt32BigEndian(encodedBufferLengthBuffer);
                using var bufferOwner = MemoryPool<byte>.Shared.Rent(bufferLength);
                var buffer = bufferOwner.Memory.Slice(0, bufferLength).Span; // Memory.Slice эффективнее, чем Span.Slice (ссылка #1,2)

                if (stream.Read(buffer) != bufferLength) PrintQuitMessageAndExit("Transmission failed");

                Console.WriteLine("Transmission completed");

                msg = Encoding.Unicode.GetString(buffer);

                Console.Write("Message: ");
                Console.WriteLine(msg);

                Console.WriteLine("Message receiver resources is disposing...");

                stream.Close();
                bufferOwner.Dispose();

                Console.WriteLine("Message receiver resources disposed");
                Console.WriteLine("Message receiver worked");
            }
            catch (InvalidOperationException ex) when (ex.Message.Contains("connect", StringComparison.OrdinalIgnoreCase))
            { PrintQuitMessageAndExit("Transmission aborted"); }
        }
        catch (Exception ex) { PrintQuitMessageAndExit(ex.Message); };

        Pause();
    }
    void Pause(string? message = null)
    {
        const string defMsg = "Press any button...";

        Console.WriteLine(message ?? defMsg);
        Console.ReadKey(true);
    }
    void PrintQuitMessageAndExit(string? message = null, bool isError = true)
    {
        const string unknowErrMsg = "<unknow>";

        if (isError)
        {
            var tempFc = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;

            Console.Write("[ERROR]: ");
            Console.WriteLine(message ?? unknowErrMsg);

            Console.ForegroundColor = tempFc;
        }
        else if (message != null)
            Console.WriteLine(message);

        Pause();

        env.Exit(isError ? -1 : 0);
    }
}


text:
Q: iOS, Implementing text reading and highlighting selected text with pre saved MP3 files Im developing an application that have a text saved in an array, and mp3 files that's in the project.
i wanna to play the mp3 file with the text that been touched and highlight the text or change its background color.
my problem is with knowing the position of the text in the screen and connect touching that text with the play event and highlighting this text
im wondering if there is a sample code for this or a project somewhere.
Please Advice.

A: Depending on how complex your text layout need to be you could try a variety of options.
If your text layout doesn't need to be complicated you could just try put the text in a button and set the background colour of the label in the button when the user touches it.
Otherwise you might need some combination of webviews and js to accomplish what you need to do.

A: NSAattributedString delegate Methods to do that:
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

and for your consideration it's available for iOS6.


text:
Q: How to return all record ids which are also part of the grouping in T-SQL I have a dataset that is laid out in a vertical format with a varying number of attributes per AppId. I currently group by the Attribute and Value to determine the maximum AppId. The scale attribute is being ignored in the Group By using "Where Attribute not in ('Scale')". I would also like to know which other AppId values are included in the grouping.
Below is an example of how the data is structured in the source table followed by how the data would look if it were flattened out. Next, is a query that'll give me the maximum AppId for each unique grouping and what the output looks like. How can I also return the other AppId values which are part of the grouping.
Source table:
+--------+-------+-----------+------------+
| PartId | AppId | Attribute |   Value    |
+--------+-------+-----------+------------+
| ABC    | ABC_1 | Color     | Red        |
| ABC    | ABC_1 | Shape     | Square     |
| ABC    | ABC_1 | Material  | Plastic    |
| ABC    | ABC_1 | Scale     | Celsius    |
| ABC    | ABC_2 | Color     | RED        |
| ABC    | ABC_2 | Shape     | Square     |
| ABC    | ABC_2 | Material  | Plastic    |
| ABC    | ABC_2 | Scale     | Fahrenheit |
| ABC    | ABC_3 | Color     | Red        |
| ABC    | ABC_4 | Color     | Red        |
| ABC    | ABC_5 | Color     | Green      |
| ABC    | ABC_5 | Shape     | Round      |
+--------+-------+-----------+------------+

Pivoted representation:
+--------+-------+-------+--------+----------+------------+
| PartId | AppId | Color | Shape  | Material |   Scale    |
+--------+-------+-------+--------+----------+------------+
| ABC    | ABC_1 | Red   | Square | Plastic  | Celsius    |
| ABC    | ABC_2 | Red   | Square | Plastic  | Fahrenheit |
| ABC    | ABC_3 | Red   |        |          |            |
| ABC    | ABC_4 | Red   |        |          |            |
| ABC    | ABC_5 | Green | Round  |          |            |
+--------+-------+-------+--------+----------+------------+

My query to get the maximum AppId
Select Distinct Max(AppId) As GroupAppId
From VerticleData
Where Attribute not in ('Scale')
Group By Attribute, Value

Returns:
+------------+
| GroupAppId |
+------------+
| ABC_2      |
| ABC_4      |
| ABC_5      |
+------------+

Desired Output:
+------------+-------+
| GroupAppId | AppId |
+------------+-------+
| ABC_2      | ABC_1 |
| ABC_2      | ABC_2 |
| ABC_4      | ABC_3 |
| ABC_4      | ABC_4 |
| ABC_5      | ABC_5 |
+------------+-------+

A: Here is an approach using window functions:
select distinct GroupAppId, AppId
from (select vd.*, max(AppId) over (partition by Attribute, Value) as GroupAppId
      from VerticleData vd
      Where Attribute not in ('Scale')
     ) vd
Where Attribute not in ('Scale');

EDIT:
I think you may want something like this:
select max( GroupAppId), AppId
from (select vd.*, max(AppId) over (partition by Attribute, Value) as GroupAppId
      from VerticleData vd
      Where Attribute not in ('Scale')
     ) vd
where Attribute not in ('Scale')
group by AppId;

But I don't understand why App_4 is not the right match for App_1 and App_2 (as this query gives).
EDIT II (by lmingle):
Working query:
Select distinct min(GroupAppID), AppId
From
(
    select distinct GroupAppId, AppId
    from (select vd.*, max(AppId) over (partition by Attribute, Value) as GroupAppId
        from VerticleData vd
        Where Attribute not in ('Scale')
        ) vd
    Where Attribute not in ('Scale')
) as a
Group By AppId


text:
Q: deep, conditional merge of js objects I'm trying to conditionally merge data from two http request together into a single object. Please consider these objects.
vehicles: [
{
  vId: 1,
  color: 'green',
  passengers: [
    {
      name: 'Joe',
      age: 22
    },
    {
      name: 'Jack',
      age: 32
    }
  ]
}
more vehicles....]

pDetails: [
  {
    vId: 1,
    detail: tall
  },
  {
    vId: 1,
    detail: 'fat'
  },
  {
    vId 2,
    detail: 'sad'
  } more details.....
]

Where the vIds match between two objects I want to push the pDetails object into a new array in the matching object in the vehicles array. I'm using Angular 5, TS and have added Lodash to my project. I'm getting hung up on how to iterate through nested arrays. I'm new to JS an not yet very familiar with the apis. Is there something in TS, ES6, Angular, or Lodash that might make this easier?
Here's the closest I've gotten so far:
this.getVehicles().subscribe(
      data => { v = data.result.objects },
      err => console.error(err),
      () => Object.keys(v).forEach(key => {
      console.log(v[key]); //mapping logic here
    })

This successfully iterates through the vehicles array but what I think I want to do is integrate though each v.passenger object and for each do a search on the pDetails array, copy matches, push to a temp array and then assign to v.passengers. I'm still having trouble figuring out how to iterate each vehicle's passenger array.

A: Using the rxjs functions would help you in this kind of concerns.
Here is code suggestion to get vehicules with detail using combineLatest (code for demonstration, not tested) :
// The first observable pushed value would be
// and array of the pushed values by the Observables
combineLatest(this.getVehiclesDetails(),this.getVehicles())
.pipe(
    // Using the returned values, you could transform them to what you want
    map(([vehicules, details]) =>
        // Here we transform our vehicules array to vehiculesWithDetail array
        vehicules.map(vehicule => {
            // We get the detail for the processed vehicule
            const detail = details.find(d => d.vdId == vehicule.vdId);
            // We merge the two objects in one
            return Object.Assign(vehicule, detail);
        })
    )
)


text:
Q: Vue.js - Property or method is not defined on the instance but referenced during render I am getting error "Property or method "processForm" is not defined on the instance but referenced during render" and error "TypeError: _vm.processForm is not a function". I am calling the processForm function in my contact form via @submit.prevent="processForm". I'm not sure what to do from this point. Any help appreciated.
render.js:
const mjml2html = require('mjml')
const Vue = require('vue')

const app = new Vue({
data: {
    el: '#signupform',
    name: ''
},
template: `
<mj-section>
 <mj-column>
   <mj-text font-size="20px" color="#F45E43" font-family="helvetica">Hello {{ name }}</mj-text>
 </mj-column>
</mj-section>`,
methods: {
processForm: function() {
    renderer.renderToString(app).then(html => {
        const htmlWithoutDataServerRenderedAttribute = html.replace(`data-server-rendered="true"`,'')
        const plainHtml = mjml2html(htmlWithoutDataServerRenderedAttribute)
        console.log(plainHtml.html)
    })}}})

const renderer = require('vue-server-renderer').createRenderer({
template: `
<mjml>
 <mj-body>

 </mj-body>
</mjml>`
})

And my form template:
<template>

      <form class="form-signup" @submit.prevent="processForm">
      <input type="text" name="name" placeholder="Enter First Name" required/>
      <input type="text" name="lname" placeholder="Enter Last Name" required/>
      <input type="email" name="mailaddr" placeholder="Your email address" required/>

      <router-link to="/">
        <button id="canlbtn" type="cancel" class="clbtn">
          Cancel
        </button>
         </router-link>
        <button id="signupbtn" type="submit" name="sendmsg-button" class="signbtn">
          Sign Up
        </button>

    </form>


text:
Q: Can Y Axis on GraphView in eclipse be set to 2 decimal places GraphViewData[] data = new GraphViewData[numElements];
for (int c = 0; c<numElements; c++) {
data[c] = new GraphViewData(c+1, pvalueArray[c]);
}
GraphView graphView = new LineGraphView(this, Captionname);
GraphViewSeries graphViewSeries = new GraphViewSeries(data);

I am populating a graph as above, my array contains values set to 2 decimal places.
When I use the graph on my app, the Y axis goes up to 3 decimal places. Can I force it to be 2?
I am using version 3.1.3. I don't really want to upgrade and have to change loads of code.
How do I use DefaultLabelFormatter? - Sorry I can't add a comment as I'm new!

A: I have had to upgrade to version 4 then I can use
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(1);
nf.setMinimumIntegerDigits(2);
graph.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter(nf, nf));

Now stuck on how to add data from my array!!!


text:
Q: What does the "first hit props" message do? In Mk11, when one character hits another with an attack, being the first one,  it gives a message saying "first hit props". Does this have any benefit to the player?

A: I don't think it does anything. In MkX, you get an extra bar meter but in Mk11 you start off with all 4 bars.

A: It gives you points, and some Brutalities only work if you landed the first hit.


text:
Q: target specifies product type 'com.apple.product-type.bundle.ui-testing', but there's no such product type for the 'iphonesimulator' platform When i was running my swift project, I got this error.

target specifies product type
  'com.apple.product-type.bundle.ui-testing', but there's no such
  product type for the 'iphonesimulator' platform

I found some similar questions on SO but this answer didn't solve my problem. I googled it too, there are no project with this product type inside.
I'm using xcode 6.4 and swift 1.2

A: In my case, clean did not work.
Open AppName.xcodeproj/project.pbxproj, replace all com.apple.product-type.* (there are 3 of them) with com.apple.product-type.application solved my problem.
It seems apple changed the type name in Xcode 7.

A: I had this issue after adding a product for UI testing using Xcode 7 Beta and constantly switching between Xcode 6.4 and 7 Beta. A simple clean made it go away.


text:
Q: How handle external application window? MFC I need handle another running application by name, id, or process handle. I get the ID and Process handles but I don't know how get handle of window to change external program title.
There is my code:
BOOL CFindProcess::OnInitDialog()
{
    CDialogEx::OnInitDialog();
    CComboBox* pComboBox = (CComboBox*)GetDlgItem(IDC_COMBO_PROCESS);
    HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32 proc;
    proc.dwSize = sizeof(PROCESSENTRY32);
    if (Process32First(hSnap, &proc)){
        pComboBox->AddString(proc.szExeFile);
        while (Process32Next(hSnap, &proc)){
            if (0!=wcscmp(proc.szExeFile, L"svchost.exe"))
                pComboBox->AddString(proc.szExeFile);
            if (wcscmp(proc.szExeFile, L"notepad.exe") == 0){
                HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proc.th32ProcessID);
                GetProcessId(hProcess);
                AfxMessageBox(L"Handeled");
                //SetWindowText(hProcess, L"Weather");
                CloseHandle(hProcess);
            }
        }
    }
    CloseHandle(hSnap);
    return TRUE;
}

my question is how get window handle of notepad.exe by name or ID, Process handles with MFC?

A: This code demonstrates what Jerry is referring to:
struct MYFINDSTRUCT
{
    DWORD dwPID;
    HWND hWnd;
};

BOOL CALLBACK MyWndEnum(HWND hwnd,LPARAM lParam)
{
    MYFINDSTRUCT* pP = (MYFINDSTRUCT*)lParam;
        DWORD dwPID = 0;
    GetWindowThreadProcessId(hwnd,&dwPID);
    if(dwPID==pP->dwPID)
    {
        pP->hWnd = hwnd;
        return 0;
    }
    return 1;
}

HWND GetProcessHWND(unsigned int nPID)
{
    MYFINDSTRUCT p;
    p.hWnd = 0;
    p.dwPID = nPID;
    EnumWindows(MyWndEnum,(LPARAM)&p);
    return p.hWnd;
}


text:
Q: How to define the indentations in a loop in python This is an example how my directory looks like:
> SSSRRR2.bam               SSSRRR24.bam
>
> SSSRRR2.bam.bai           SSSRRR24.bam.bai
>
> SSSRRR2.split.bam         SSSRRR24.split.bam
>
> SSSRRR2.ump.fastq         SSSRRR24.ump.fastq

The only files I need are .split.bam and .bam files for each ID in order to apply subprocess.check_output. This is the python script I made:
#!/usr/bin/env python

import os
import subprocess

if __name__=='__main__':
    path = os.getcwd()
    dir_files = os.listdir(path)
    pair_reads = {}

    for file in sorted(dir_files):
        if file.endswith(".split.bam"):
            ID_1 = file.split(".")[0]
            file1 = file

        if file.endswith(".bam") and not file.endswith(".split.bam") and not file.endswith(".bam.bai"):
            ID_2 = file.split(".")[0]
            file2 = file

        if ID_1 == ID_2:
             pair_reads[file1] = file2

    for key, value in pair_reads.items():
#        print(key)
        name = key.split(".")[0]
        subprocess.check_output("tepid-discover -k -d -i --strict -D -p 36 -n " + name + " -c " + key + " s " + value, shell  = True)

However, my problem is the indentation when I apply the loops. If each block of if is independent to each other how can I introduce a connection to both, for instance in this block:
if ID_1 == ID_2:
    pair_reads[file1] = file2

This is the error I got:
if ID_1 == ID_2:
NameError: name 'ID_1' is not defined

Additionaly, I am using python2 because the program works with python2.
Thank you in advance for your help. I hope I made myself clear.

A: This doesn't seem to have anything to do with indentation. Your program doesn't run the first if statement. I don't know what you want to do, but you can put that comparison nested in something like
try:
    ID_1 and ID_2
except:
    print("qwe")

A: In one iteration of your loop, only one of ID_1 and ID_2 can be defined, because it only looks at one file at a time and the two conditions are mutually exclusive.
There are two simple fixes to that problem: you could give ID_1 and ID_2 default values, or you could add another condition before checking that they are the same (e.g. "if both IDs were defined and they are the same").
However, this may not make your program work, because os.listdir might list the files in a different order than you are expecting.
The easiest solution might be to just look only the .split.bam files or the .bam files, and construct the other yourself.
import os

for file in os.listdir(path):
    # separate the last two file extensions from the base name
    basename, *extensions = file.rsplit(os.extsep, 2)
    if extensions == ['split', 'bam'] and basename:
        # found basename.split.bam
        bamfile = basename + '.bam'
        if os.path.exists(bamfile):
            # use basename, bamfile, and file however you want
            subprocess.check_output(...)

This finds every .split.bam file, and checks if the corresponding .bam file exists before running the last line.


text:
Q: Android:id throws me error inside a DrawerLayout content View I'm trying to place a textview in main activity with left drawer. Textview can be placed with no problem, but when i'am adding Android:id in Textview, then it throws me Error:

Android.Views.InflateException: Binary XML file line #15: Binary XML file line #15: Error inflating class android.support.design.internal.NavigationMenuItemView.

This Code: Works
    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/drawer_layout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true"
  tools:openDrawer="start">

  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        tools:showIn="@layout/app_bar_main"
        android:text="Hello World!" />

  <android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

But this code doesn't
    <?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/drawer_layout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true"
  tools:openDrawer="start">

  <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        tools:showIn="@layout/app_bar_main"
        android:id="@+id/textView1"
        android:text="Hello World!" />

  <android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

I just have add one line of code
android:id="@+id/textView1"

A: This problem will likely occur when the version of your appcompat library and design support library doesn't match.
 compile 'com.android.support:appcompat-v7:23.1.1' // appcompat library
 compile 'com.android.support:design:23.1.1'       //design support library


text:
Q: Clip a vector without losing geometries - QGIS 3.22 I experienced a lot of issues trying to keep only a German region from the vector I have of Europe. I've tried everything, using mask+clip with my shapefile of the German region, using "Select by Location", using "Intersect"...
Each time I get a file with very very few objects left.
Does someone have an idea of what I could do?
I attached a picture of my last try with "Select by Location" but the algorithm gets back to 0 after running and nothing happen.
Plus other pictures of me trying to draw a super simple polygon and clip vector by mask layer function...

A: I added a 0 distance buffer and I could eventually clip afterwards.


text:
Q: Why do I hear "to" in quick speaking english sound like "the"? I'm looking to track down a suspect
This man (Barry Allen) said "I'm looking to ..." But I can just hear "I'm looking the ..."
Sound track is in the above link.

A: English speakers often pronounce the words "to" in two different ways. One sounds like "too" (like the "oo" sound in "tooth") and the other sounds more like "tuh" (like the "u" sound in "tugboat"). In the audio clip you shared when the speaker says "I'm looking to", they are using the latter pronunciation.
Likewise the word "the" is commonly pronounced in two different ways. One sounds like "thee" and the other sounds more like "thuh". So the "to" in the audio clip probably sounded like this latter pronunciation of "the".